diff --git a/.eslintrc.yml b/.eslintrc.yml
index edbc47195..0d74348f2 100644
--- a/.eslintrc.yml
+++ b/.eslintrc.yml
@@ -36,3 +36,7 @@ rules:
jasmine/no-focused-tests: 0
jasmine/prefer-toHaveBeenCalledWith: 0
arrow-spacing: ["error", { "before": true, "after": true }]
+ no-restricted-syntax:
+ - "error"
+ - selector: "NewExpression[callee.name='Date']"
+ message: "Use Date.vnNew() instead of new Date()."
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 57848aa7f..73ebecabc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,117 @@
+# Version 24.48 - 2024-11-25
+
+### Added 🆕
+
+- feat: refs #4948 Added ticket_selfConsumptionPackaging by:guillermo
+- feat: refs #6818 add config table by:jorgep
+- feat: refs #6818 add records by:jorgep
+- feat: refs #6818 saysimple integration by:jorgep
+- feat: refs #6845 userInterface by:sergiodt
+- feat: refs #6869 add back by:jorgep
+- feat: refs #6869 define model by:jorgep
+- feat: refs #6869 refs#6869 itemShelving_get (origin/6869-createGetDetails) by:sergiodt
+- feat: refs #7006 itemTypeLog by:guillermo
+- feat: refs #7006 itemTypeLog created by:guillermo
+- feat: refs #7006 Requested changes by:guillermo
+- feat: refs #7193 added scope in parking model by:Jon
+- feat: refs #7244 Requested changes by:guillermo
+- feat: refs #7266 Added details and improvements in item label reports by:guillermo
+- feat: refs #7266 buyFkForPrint by:sergiodt
+- feat: refs #7266 First commit by:guillermo
+- feat: refs #7266 Item label barcode by:guillermo
+- feat: refs #7266 Item label QR by:guillermo
+- feat: refs #7266 Item label QR finished by:guillermo
+- feat: refs #7266 Minor change by:guillermo
+- feat: refs #7266 Print corrections by:guillermo
+- feat: refs #7266 Requested changes and improvements by:guillermo
+- feat: refs #7266 Requested changes and query optimization by:guillermo
+- feat: refs #7266 Version by:guillermo
+- feat: refs #7289 #7289 apply option 1 by:Javier Segarra
+- feat: refs #7289 #7289 remove bad translation by:Javier Segarra
+- feat: refs #7524 restrict fields by:jorgep
+- feat: refs #7641 fine tunning by:jorgep
+- feat: refs #7641 improve style by:jorgep
+- feat: refs #7743 add simple spec for sendMail by:pablone
+- feat: refs #7743 add try catch stmt to the test by:pablone
+- feat: refs #7874 add default type by:jorgep
+- feat: refs #7874 use name by:jorgep
+- feat: refs #7920 Added ItemShelving in shelvingLog by:guillermo
+- feat: refs #7921 refs#7921 sendLostExpedition by:sergiodt
+- feat: refs #7922 refs #792 scanOrder by:sergiodt
+- feat: refs #7943 quitar lectura en metodos comunes by:jgallego
+- feat: refs #7943 return just the required content by:jorgep
+- feat: refs #7943 usa back con permisos by:jgallego
+- feat: refs #8020 machineWorkerDeprecated by:sergiodt
+- feat: refs #8057 Added data updates by:guillermo
+- feat: refs #8057 Added data updates (origin/8057-geoFk) by:guillermo
+- feat: refs #8057 Added geoFk columns by:guillermo
+- feat: refs #8057 Fix version by:guillermo
+- feat: refs #8057 More precision in getGeo by:guillermo
+- feat: refs #8057 Requested changes by:guillermo
+- feat: refs #8071 quitar esquema by:robert
+- feat: refs #8071 travel_weeklyClone by:robert
+- feat: refs #8080 Added column comment by:guillermo
+- feat: refs #8083 add prop by:jorgep
+- feat: refs #8087 Traspasar redadas a travels by:Carlos Andrés
+- feat: refs #8099 refs#8099 addComplmentSalary by:sergiodt
+- feat: refs #8124 Enrutadores nuevos requerimientos by:Carlos Andrés
+- feat: refs #8124 Enrutadores nuevos requerimientos (origin/8124-enrutadoresNuevosRequerimientos) by:Carlos Andrés
+- feat: refs #8127 entry_getCommission by:robert
+- feat: refs #8127 quitar esquemas by:robert
+- feat: refs #8135 refs#8135 updateTicketACL (origin/8135-ticketACL) by:sergiodt
+- feat: refs #8143 deprecate recoverPass and sync from account.user by:ivanm
+- feat: refs #8150 movExpeditions by:sergiodt
+- feat: refs #8151 Added test by:guillermo
+- feat: refs #8151 moveExpeditions by:guillermo
+- feat: refs #8151 Requested changes by:guillermo
+- feat(Supplier): refs #6828 add companySize by:alexm
+- refactor: refs #7641 entry report style by:jorgep
+
+### Changed 📦
+
+- refactor: refs #6920 add correct role by:alexm
+- refactor: refs #7242 Deleted select column by:guillermo
+- refactor: refs #7457 Added from param if not exists by:guillermo
+- refactor: refs #7641 entry report style by:jorgep
+- refactor: refs #7715 Deleted hasNewLabelMrwMethod column by:guillermo
+- refactor: refs #7920 Fix tests by:guillermo
+- refactor: refs #7920 Fix version by:guillermo
+- refactor: refs #7920 itemShelvingLog by:guillermo
+- refactor: refs #7920 Main change by:guillermo
+- refactor: refs #7920 Major changes by:guillermo
+- refactor: refs #7920 No changes in itemShelvingLog table by:guillermo
+- refactor: refs #7920 Requested changes by:guillermo
+- refactor: refs #7950 Created cmr model (7950-cmrModelUnify) by:guillermo
+- refactor: refs #7950 Requested changes by:guillermo
+- refactor: refs #8153 Optimized order_getTax by:guillermo
+
+### Fixed 🛠️
+
+- fix: clean deletes also zoneEvent range records by:jgallego
+- fix: more data for fixture.before by:Pako
+- fix: refs #4948 Tests by:guillermo
+- fix: refs #6644 email and translations by:carlossa
+- fix: refs #6818 add config by:jorgep
+- fix: refs #6818 add defaultChannel by:jorgep
+- fix: refs #6818 use right col type by:jorgep
+- fix: refs #6869 use id as primaryKey by:jorgep
+- fix: refs #7244 Added collection ACL by:guillermo
+- fix: refs #7283 item filters by:carlossa
+- fix: refs #7283 remove by:carlossa
+- fix: refs #7283 remove tests by:carlossa
+- fix: refs #7283 tback by:carlossa
+- fix: refs #7323 add remaining fields (origin/7323-warfix-addRemainingFields) by:jorgep
+- fix: refs #7457 add with on select to reduce by:pablone
+- fix: refs #7457 empty commit for gitea by:pablone
+- fix: refs #7457 error on empty from param and add translate by:pablone
+- fix: refs #7457 remove group by calc time reduce bellow 1s by:pablone
+- fix: refs #7457 remove translate and use param definition for restriction by:pablone
+- fix: refs #7641 align columns by:jorgep
+- fix: refs #7641 drop boilerplate code by:jorgep
+- fix: refs #7920 refs#7920 itemShelvingLog by:sergiodt
+- fix: refs #8153 Version by:guillermo
+- revert cd7ed6987a88e00275b562d3248f368b6333620c by:Javier Segarra
+
# Version 24.38 - 2024-09-17
### Added 🆕
diff --git a/Jenkinsfile b/Jenkinsfile
index 19f47c5b0..06addc940 100644
--- a/Jenkinsfile
+++ b/Jenkinsfile
@@ -7,7 +7,8 @@ def RUN_BUILD
def BRANCH_ENV = [
test: 'test',
- master: 'production'
+ master: 'production',
+ beta: 'production'
]
node {
@@ -18,7 +19,8 @@ node {
PROTECTED_BRANCH = [
'dev',
'test',
- 'master'
+ 'master',
+ 'beta'
].contains(env.BRANCH_NAME)
FROM_GIT = env.JOB_NAME.startsWith('gitea/')
@@ -62,6 +64,18 @@ pipeline {
PROJECT_NAME = 'salix'
}
stages {
+ stage('Version') {
+ when {
+ expression { RUN_BUILD }
+ }
+ steps {
+ script {
+ def packageJson = readJSON file: 'package.json'
+ def version = "${packageJson.version}-build${env.BUILD_ID}"
+ writeFile(file: 'VERSION.txt', text: version)
+ }
+ }
+ }
stage('Install') {
environment {
NODE_ENV = ''
@@ -118,11 +132,10 @@ pipeline {
when {
expression { RUN_BUILD }
}
+ environment {
+ VERSION = readFile 'VERSION.txt'
+ }
steps {
- script {
- def packageJson = readJSON file: 'package.json'
- env.VERSION = "${packageJson.version}-build${env.BUILD_ID}"
- }
sh 'docker-compose build back'
}
}
@@ -156,11 +169,10 @@ pipeline {
when {
expression { RUN_BUILD }
}
+ environment {
+ VERSION = readFile 'VERSION.txt'
+ }
steps {
- script {
- def packageJson = readJSON file: 'package.json'
- env.VERSION = "${packageJson.version}-build${env.BUILD_ID}"
- }
sh 'gulp build'
sh 'docker-compose build front'
}
@@ -175,12 +187,9 @@ pipeline {
}
environment {
CREDENTIALS = credentials('docker-registry')
+ VERSION = readFile 'VERSION.txt'
}
steps {
- script {
- def packageJson = readJSON file: 'package.json'
- env.VERSION = "${packageJson.version}-build${env.BUILD_ID}"
- }
sh 'docker login --username $CREDENTIALS_USR --password $CREDENTIALS_PSW $REGISTRY'
sh 'docker-compose push'
}
@@ -207,11 +216,10 @@ pipeline {
when {
expression { FROM_GIT }
}
+ environment {
+ VERSION = readFile 'VERSION.txt'
+ }
steps {
- script {
- def packageJson = readJSON file: 'package.json'
- env.VERSION = "${packageJson.version}-build${env.BUILD_ID}"
- }
withKubeConfig([
serverUrl: "$KUBERNETES_API",
credentialsId: 'kubernetes',
diff --git a/back/Dockerfile b/back/Dockerfile
index 363192a0b..0f75f6949 100644
--- a/back/Dockerfile
+++ b/back/Dockerfile
@@ -32,8 +32,7 @@ RUN apt-get update \
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
samba-common-bin samba-dsdb-modules\
- && rm -rf /var/lib/apt/lists/* \
- && npm -g install pm2
+ && rm -rf /var/lib/apt/lists/*
# Salix
@@ -55,7 +54,4 @@ COPY \
README.md \
./
-CMD ["pm2-runtime", "./back/process.yml"]
-
-HEALTHCHECK --interval=15s --timeout=10s \
- CMD curl -f http://localhost:3000/api/Applications/status || exit 1
+CMD ["node", "--tls-min-v1.0", "--openssl-legacy-provider", "./loopback/server/server.js"]
\ No newline at end of file
diff --git a/back/methods/collection/assignCollection.js b/back/methods/collection/assignCollection.js
index 2ff37ab59..2a7ec9ad5 100644
--- a/back/methods/collection/assignCollection.js
+++ b/back/methods/collection/assignCollection.js
@@ -19,8 +19,15 @@ module.exports = Self => {
if (typeof options == 'object')
Object.assign(myOptions, options);
- const [info, info2, [{'@vCollectionFk': collectionFk}]] = await Self.rawSql(
- 'CALL vn.collection_getAssigned(?, @vCollectionFk);SELECT @vCollectionFk', [userId], myOptions);
+
+ const randStr = Math.random().toString(36).substring(3);
+ const result = await Self.rawSql(`
+ CALL vn.collection_getAssigned(?, @vCollectionFk);
+ SELECT @vCollectionFk ?
+ `, [userId, randStr], myOptions);
+
+ const collectionFk = result.find(item => item[0]?.[randStr] !== undefined)?.[0]?.[randStr];
+
if (!collectionFk) throw new UserError('There are not picking tickets');
await Self.rawSql('CALL vn.collection_printSticker(?, NULL)', [collectionFk], myOptions);
diff --git a/back/methods/collection/getSales.js b/back/methods/collection/getSales.js
index a9e5f2e60..f3575672f 100644
--- a/back/methods/collection/getSales.js
+++ b/back/methods/collection/getSales.js
@@ -29,10 +29,8 @@ module.exports = Self => {
});
Self.getSales = async(ctx, collectionOrTicketFk, print, source, options) => {
- const models = Self.app.models;
const userId = ctx.req.accessToken.userId;
const myOptions = {userId};
- const $t = ctx.req.__;
if (typeof options == 'object')
Object.assign(myOptions, options);
@@ -59,22 +57,6 @@ module.exports = Self => {
if (print) await Self.rawSql('CALL vn.collection_printSticker(?,NULL)', [id], myOptions);
- for (let ticket of tickets) {
- if (ticket.observaciones) {
- let observations = ticket.observaciones.split(' ');
-
- for (let observation of observations) {
- const salesPerson = ticket.salesPersonFk;
- if (observation.startsWith('#') || observation.startsWith('@')) {
- await models.Chat.send(ctx,
- observation,
- $t('ticketCommercial', {ticket: ticket.ticketFk, salesPerson})
- );
- }
- }
- }
- }
-
return getCollection(id, tickets, sales, placements, myOptions);
};
diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js
index 2a2b67524..677c9e444 100644
--- a/back/methods/collection/getTickets.js
+++ b/back/methods/collection/getTickets.js
@@ -57,12 +57,14 @@ module.exports = Self => {
ROW_NUMBER () OVER (PARTITION BY s.id ORDER BY pickingOrder) currentItemShelving,
COUNT(*) OVER (PARTITION BY s.id ORDER BY s.id) totalItemShelving,
sh.code,
- p2.code parkingCode,
- p2.pickingOrder pickingOrder,
- p.code parkingCodePrevia,
- p.pickingOrder pickingOrderPrevia,
+ p2.code parkingCodePrevia,
+ p2.pickingOrder pickingOrderPrevia,
+ p.code parkingCode,
+ p.pickingOrder pickingOrder,
iss.id itemShelvingSaleFk,
- iss.isPicked
+ iss.isPicked,
+ iss.itemShelvingFk,
+ st.code stateCode
FROM ticketCollection tc
LEFT JOIN collection c ON c.id = tc.collectionFk
JOIN sale s ON s.ticketFk = tc.ticketFk
@@ -72,10 +74,11 @@ module.exports = Self => {
JOIN item i ON i.id = s.itemFk
JOIN itemShelvingSale iss ON iss.saleFk = s.id
LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
- LEFT JOIN shelving sh ON sh.code = ish.shelvingFk
+ LEFT JOIN shelving sh ON sh.id = ish.shelvingFk
LEFT JOIN parking p ON p.id = sh.parkingFk
LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk
LEFT JOIN origin o ON o.id = i.originFk
+ LEFT JOIN state st ON st.id = sg.stateFk
WHERE tc.collectionFk = ?
GROUP BY s.id, ish.id, p.code, p2.code
UNION ALL
@@ -102,7 +105,9 @@ module.exports = Self => {
p.code,
p.pickingOrder,
iss.id itemShelvingSaleFk,
- iss.isPicked
+ iss.isPicked,
+ iss.itemShelvingFk,
+ st.code stateCode
FROM sectorCollection sc
JOIN sectorCollectionSaleGroup ss ON ss.sectorCollectionFk = sc.id
JOIN saleGroup sg ON sg.id = ss.saleGroupFk
@@ -112,10 +117,11 @@ module.exports = Self => {
JOIN item i ON i.id = s.itemFk
JOIN itemShelvingSale iss ON iss.saleFk = s.id
LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
- LEFT JOIN shelving sh ON sh.code = ish.shelvingFk
+ LEFT JOIN shelving sh ON sh.id = ish.shelvingFk
LEFT JOIN parking p ON p.id = sh.parkingFk
LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk
LEFT JOIN origin o ON o.id = i.originFk
+ LEFT JOIN state st ON st.id = sg.stateFk
WHERE sc.id = ?
AND sgd.saleGroupFk
GROUP BY s.id, ish.id, p.code, p2.code`, [id, id], myOptions);
diff --git a/back/methods/collection/spec/assign.spec.js b/back/methods/collection/spec/assign.spec.js
index 745343819..b00631d22 100644
--- a/back/methods/collection/spec/assign.spec.js
+++ b/back/methods/collection/spec/assign.spec.js
@@ -28,9 +28,10 @@ describe('ticket assign()', () => {
await tx.rollback();
});
- it('should throw an error when there is not picking tickets', async() => {
+ it('should throw an error when there are no picking tickets', async() => {
try {
await models.Collection.assign(ctx, options);
+ fail('Expected an error to be thrown, but none was thrown.');
} catch (e) {
expect(e.message).toEqual('There are not picking tickets');
}
diff --git a/back/methods/docuware/core.js b/back/methods/docuware/core.js
index 74d922236..3de33b786 100644
--- a/back/methods/docuware/core.js
+++ b/back/methods/docuware/core.js
@@ -4,21 +4,45 @@ module.exports = Self => {
/**
* Returns basic headers
*
- * @param {string} cookie - The docuware cookie
* @return {object} - The headers
*/
Self.getOptions = async() => {
const docuwareConfig = await Self.app.models.DocuwareConfig.findOne();
+ const now = Date.vnNow();
+ let {url, username, password, token, expired} = docuwareConfig;
+
+ if (process.env.NODE_ENV && (!expired || expired < now + 60)) {
+ const {data: {IdentityServiceUrl}} = await axios.get(`${url}/Home/IdentityServiceInfo`);
+ const {data: {token_endpoint}} = await axios.get(`${IdentityServiceUrl}/.well-known/openid-configuration`);
+ const {data} = await axios.post(token_endpoint, {
+ grant_type: 'password',
+ scope: 'docuware.platform',
+ client_id: 'docuware.platform.net.client',
+ username,
+ password
+ }, {headers: {
+ 'Accept': 'application/json',
+ 'Content-Type': 'application/x-www-form-urlencoded'
+ }});
+
+ const newToken = data.access_token;
+ token = data.token_type + ' ' + newToken;
+ await docuwareConfig.updateAttributes({
+ token,
+ expired: now + data.expires_in
+ });
+ }
+
const headers = {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
- 'Cookie': docuwareConfig.cookie
+ 'Authorization': token
}
};
return {
- url: docuwareConfig.url,
+ url,
headers
};
};
diff --git a/back/methods/docuware/specs/core.spec.js b/back/methods/docuware/specs/core.spec.js
index cdf8a3b62..47580483d 100644
--- a/back/methods/docuware/specs/core.spec.js
+++ b/back/methods/docuware/specs/core.spec.js
@@ -2,87 +2,54 @@ const axios = require('axios');
const models = require('vn-loopback/server/server').models;
describe('Docuware core', () => {
- beforeAll(() => {
+ const fileCabinetCode = 'deliveryNote';
+ beforeAll(async() => {
process.env.NODE_ENV = 'testing';
- });
- afterAll(() => {
- delete process.env.NODE_ENV;
- });
-
- describe('getOptions()', () => {
- it('should return url and headers', async() => {
- const result = await models.Docuware.getOptions();
-
- expect(result.url).toBeDefined();
- expect(result.headers).toBeDefined();
+ const docuwareInfo = await models.Docuware.findOne({
+ where: {
+ code: fileCabinetCode
+ }
});
- });
- describe('getDialog()', () => {
- it('should return dialogId', async() => {
- const dialogs = {
- data: {
- Dialog: [
- {
- DisplayName: 'find',
- Id: 'getDialogTest'
- }
- ]
- }
- };
- spyOn(axios, 'get').and.returnValue(new Promise(resolve => resolve(dialogs)));
- const result = await models.Docuware.getDialog('deliveryNote', 'find', 'randomFileCabinetId');
+ spyOn(axios, 'get').and.callFake(url => {
+ if (url.includes('IdentityServiceInfo')) return {data: {IdentityServiceUrl: 'IdentityServiceUrl'}};
+ if (url.includes('IdentityServiceUrl')) return {data: {token_endpoint: 'token_endpoint'}};
+ if (url.includes('dialogs')) {
+ return {
+ data: {
+ Dialog: [
+ {
+ DisplayName: 'find',
+ Id: 'getDialogTest'
+ }
+ ]
+ }
+ };
+ }
- expect(result).toEqual('getDialogTest');
- });
- });
-
- describe('getFileCabinet()', () => {
- it('should return fileCabinetId', async() => {
- const code = 'deliveryNote';
- const docuwareInfo = await models.Docuware.findOne({
- where: {
- code
- }
- });
- const dialogs = {
- data: {
+ if (url.includes('FileCabinets')) {
+ return {data: {
FileCabinet: [
{
Name: docuwareInfo.fileCabinetName,
Id: 'getFileCabinetTest'
}
]
- }
- };
- spyOn(axios, 'get').and.returnValue(new Promise(resolve => resolve(dialogs)));
- const result = await models.Docuware.getFileCabinet(code);
-
- expect(result).toEqual('getFileCabinetTest');
- });
- });
-
- describe('get()', () => {
- it('should return data without parse', async() => {
- spyOn(models.Docuware, 'getFileCabinet').and.returnValue((new Promise(resolve => resolve(Math.random()))));
- spyOn(models.Docuware, 'getDialog').and.returnValue((new Promise(resolve => resolve(Math.random()))));
- const data = {
- data: {
- id: 1
- }
- };
- spyOn(axios, 'post').and.returnValue(new Promise(resolve => resolve(data)));
- const result = await models.Docuware.get('deliveryNote');
-
- expect(result.id).toEqual(1);
+ }};
+ }
});
- it('should return data with parse', async() => {
- spyOn(models.Docuware, 'getFileCabinet').and.returnValue((new Promise(resolve => resolve(Math.random()))));
- spyOn(models.Docuware, 'getDialog').and.returnValue((new Promise(resolve => resolve(Math.random()))));
- const data = {
- data: {
+ spyOn(axios, 'post').and.callFake(url => {
+ if (url.includes('token_endpoint')) {
+ return {data: {
+ access_token: 'access_token',
+ token_type: 'bearer',
+ expires_in: 10000
+ }};
+ }
+ if (url.includes('DialogExpression')) {
+ return {data: {
Items: [{
Fields: [
{
@@ -103,12 +70,52 @@ describe('Docuware core', () => {
]
}]
}
- };
+ };
+ }
+ });
+ });
+
+ afterAll(() => {
+ delete process.env.NODE_ENV;
+ });
+
+ describe('getOptions()', () => {
+ it('should return url and headers', async() => {
+ const result = await models.Docuware.getOptions();
+
+ expect(result.url).toBeDefined();
+ expect(result.headers).toBeDefined();
+ });
+ });
+
+ describe('Dialog()', () => {
+ it('should return dialogId', async() => {
+ const result = await models.Docuware.getDialog('deliveryNote', 'find', 'randomFileCabinetId');
+
+ expect(result).toEqual('getDialogTest');
+ });
+ });
+
+ describe('getFileCabinet()', () => {
+ it('should return fileCabinetId', async() => {
+ const result = await models.Docuware.getFileCabinet(fileCabinetCode);
+
+ expect(result).toEqual('getFileCabinetTest');
+ });
+ });
+
+ describe('get()', () => {
+ it('should return data without parse', async() => {
+ const [result] = await models.Docuware.get('deliveryNote');
+
+ expect(result.firstRequiredField).toEqual(1);
+ });
+
+ it('should return data with parse', async() => {
const parse = {
'firstRequiredField': 'id',
'secondRequiredField': 'name',
};
- spyOn(axios, 'post').and.returnValue(new Promise(resolve => resolve(data)));
const [result] = await models.Docuware.get('deliveryNote', null, parse);
expect(result.id).toEqual(1);
@@ -119,17 +126,14 @@ describe('Docuware core', () => {
describe('getById()', () => {
it('should return data', async() => {
- spyOn(models.Docuware, 'getFileCabinet').and.returnValue((new Promise(resolve => resolve(Math.random()))));
- spyOn(models.Docuware, 'getDialog').and.returnValue((new Promise(resolve => resolve(Math.random()))));
- const data = {
- data: {
- id: 1
- }
- };
- spyOn(axios, 'post').and.returnValue(new Promise(resolve => resolve(data)));
- const result = await models.Docuware.getById('deliveryNote', 1);
+ spyOn(models.Docuware, 'get');
+ await models.Docuware.getById('deliveryNote', 1);
- expect(result.id).toEqual(1);
+ expect(models.Docuware.get).toHaveBeenCalledWith(
+ 'deliveryNote',
+ {condition: [Object({DBName: 'N__ALBAR_N', Value: [1]})]},
+ undefined
+ );
});
});
});
diff --git a/back/methods/docuware/upload.js b/back/methods/docuware/upload.js
index 0102911e0..5b35b7598 100644
--- a/back/methods/docuware/upload.js
+++ b/back/methods/docuware/upload.js
@@ -143,7 +143,7 @@ module.exports = Self => {
headers: {
'Content-Type': 'multipart/form-data',
'X-File-ModifiedDate': Date.vnNew(),
- 'Cookie': docuwareOptions.headers.headers.Cookie,
+ 'Authorization': docuwareOptions.headers.headers.Authorization,
...data.getHeaders()
},
};
diff --git a/back/methods/machine-worker/specs/updateInTime.spec.js b/back/methods/machine-worker/specs/updateInTime.spec.js
deleted file mode 100644
index f166214b0..000000000
--- a/back/methods/machine-worker/specs/updateInTime.spec.js
+++ /dev/null
@@ -1,132 +0,0 @@
-const {models} = require('vn-loopback/server/server');
-
-describe('machineWorker updateInTime()', () => {
- const itBoss = 104;
- const davidCharles = 1106;
-
- beforeAll(async() => {
- ctx = {
- req: {
- accessToken: {},
- headers: {origin: 'http://localhost'},
- __: value => value
- }
- };
- });
-
- it('should throw an error if the plate does not exist', async() => {
- const tx = await models.MachineWorker.beginTransaction({});
- const options = {transaction: tx};
- const plate = 'RE-123';
- ctx.req.accessToken.userId = 1106;
- try {
- await models.MachineWorker.updateInTime(ctx, plate, options);
- await tx.rollback();
- } catch (e) {
- const error = e;
-
- expect(error.message).toContain('the plate does not exist');
- await tx.rollback();
- }
- });
-
- it('should grab a machine where is not in use', async() => {
- const tx = await models.MachineWorker.beginTransaction({});
- const options = {transaction: tx};
- const plate = 'RE-003';
- ctx.req.accessToken.userId = 1107;
- try {
- const totalBefore = await models.MachineWorker.find(null, options);
- await models.MachineWorker.updateInTime(ctx, plate, options);
- const totalAfter = await models.MachineWorker.find(null, options);
-
- expect(totalAfter.length).toEqual(totalBefore.length + 1);
- await tx.rollback();
- } catch (e) {
- await tx.rollback();
- }
- });
-
- describe('less than 12h', () => {
- const plate = 'RE-001';
- it('should trow an error if it is not himself', async() => {
- const tx = await models.MachineWorker.beginTransaction({});
- const options = {transaction: tx};
- ctx.req.accessToken.userId = davidCharles;
-
- try {
- await models.MachineWorker.updateInTime(ctx, plate, options);
- await tx.rollback();
- } catch (e) {
- const error = e;
-
- expect(error.message).toContain('This machine is already in use');
- await tx.rollback();
- }
- });
-
- it('should throw an error if it is himself with a different machine', async() => {
- const tx = await models.MachineWorker.beginTransaction({});
- const options = {transaction: tx};
- ctx.req.accessToken.userId = itBoss;
- const plate = 'RE-003';
- try {
- await models.MachineWorker.updateInTime(ctx, plate, options);
- await tx.rollback();
- } catch (e) {
- const error = e;
-
- expect(error.message).toEqual('You are already using a machine');
- await tx.rollback();
- }
- });
-
- it('should set the out time if it is himself', async() => {
- const tx = await models.MachineWorker.beginTransaction({});
- const options = {transaction: tx};
- ctx.req.accessToken.userId = itBoss;
-
- try {
- const isNotParked = await models.MachineWorker.findOne({
- where: {workerFk: itBoss}
- }, options);
- await models.MachineWorker.updateInTime(ctx, plate, options);
- const isParked = await models.MachineWorker.findOne({
- where: {workerFk: itBoss}
- }, options);
-
- expect(isNotParked.outTime).toBeNull();
- expect(isParked.outTime).toBeDefined();
- await tx.rollback();
- } catch (e) {
- await tx.rollback();
- }
- });
- });
-
- describe('equal or more than 12h', () => {
- const plate = 'RE-002';
- it('should set the out time and grab the machine', async() => {
- const tx = await models.MachineWorker.beginTransaction({});
- const options = {transaction: tx};
- ctx.req.accessToken.userId = davidCharles;
- const filter = {
- where: {workerFk: davidCharles, machineFk: 2}
- };
- try {
- const isNotParked = await models.MachineWorker.findOne(filter, options);
- const totalBefore = await models.MachineWorker.find(null, options);
- await models.MachineWorker.updateInTime(ctx, plate, options);
- const isParked = await models.MachineWorker.findOne(filter, options);
- const totalAfter = await models.MachineWorker.find(null, options);
-
- expect(isNotParked.outTime).toBeNull();
- expect(isParked.outTime).toBeDefined();
- expect(totalAfter.length).toEqual(totalBefore.length + 1);
- await tx.rollback();
- } catch (e) {
- await tx.rollback();
- }
- });
- });
-});
diff --git a/back/methods/machine-worker/updateInTime.js b/back/methods/machine-worker/updateInTime.js
deleted file mode 100644
index 44fad2c05..000000000
--- a/back/methods/machine-worker/updateInTime.js
+++ /dev/null
@@ -1,77 +0,0 @@
-const UserError = require('vn-loopback/util/user-error');
-module.exports = Self => {
- Self.remoteMethodCtx('updateInTime', {
- description: 'Updates the corresponding registry if the worker has been registered in the last few hours',
- accessType: 'WRITE',
- accepts: [
- {
- arg: 'plate',
- type: 'string',
- }
- ],
- http: {
- path: `/updateInTime`,
- verb: 'POST'
- }
- });
-
- Self.updateInTime = async(ctx, plate, options) => {
- const models = Self.app.models;
- const userId = ctx.req.accessToken.userId;
- const $t = ctx.req.__;
-
- let tx;
- const myOptions = {};
-
- if (typeof options == 'object')
- Object.assign(myOptions, options);
-
- if (!myOptions.transaction) {
- tx = await Self.beginTransaction({});
- myOptions.transaction = tx;
- }
-
- try {
- const machine = await models.Machine.findOne({
- fields: ['id', 'plate'],
- where: {plate}
- }, myOptions);
-
- if (!machine)
- throw new UserError($t('the plate does not exist', {plate}));
-
- const machineWorker = await Self.findOne({
- where: {
- or: [{machineFk: machine.id}, {workerFk: userId}],
- outTime: null,
- }
- }, myOptions);
-
- const {maxHours} = await models.MachineWorkerConfig.findOne({fields: ['maxHours']}, myOptions);
- const hoursDifference = (Date.vnNow() - machineWorker?.inTime?.getTime() ?? 0) / (60 * 60 * 1000);
-
- if (machineWorker) {
- const isHimself = userId == machineWorker.workerFk;
- const isSameMachine = machine.id == machineWorker.machineFk;
-
- if (hoursDifference < maxHours && !isHimself)
- throw new UserError($t('This machine is already in use.'));
-
- if (hoursDifference < maxHours && isHimself && !isSameMachine)
- throw new UserError($t('You are already using a machine'));
-
- await machineWorker.updateAttributes({
- outTime: Date.vnNew()
- }, myOptions);
- }
-
- if (!machineWorker || hoursDifference >= maxHours)
- await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions);
-
- if (tx) await tx.commit();
- } catch (e) {
- if (tx) await tx.rollback();
- throw e;
- }
- };
-};
diff --git a/back/methods/mrw-config/cancelShipment.js b/back/methods/mrw-config/cancelShipment.js
index 56d206529..e96d6d694 100644
--- a/back/methods/mrw-config/cancelShipment.js
+++ b/back/methods/mrw-config/cancelShipment.js
@@ -24,12 +24,13 @@ module.exports = Self => {
Self.cancelShipment = async expeditionFk => {
const models = Self.app.models;
-
const mrw = await models.MrwConfig.findOne();
const {externalId} = await models.Expedition.findById(expeditionFk);
const clientType = await models.MrwConfig.getClientType(expeditionFk);
const template = fs.readFileSync(__dirname + '/cancelShipment.ejs', 'utf-8');
const renderedXml = ejs.render(template, {mrw, externalId, clientType});
+
+ await Self.rawSql('CALL util.debugAdd(?,?);', ['cancelShipment', renderedXml]);
const response = await axios.post(mrw.url, renderedXml, {
headers: {
'Content-Type': 'application/soap+xml; charset=utf-8'
@@ -37,9 +38,11 @@ module.exports = Self => {
});
const xmlString = response.data;
+ await Self.rawSql('CALL util.debugAdd(?,?);', ['cancelShipmentResponse', xmlString]);
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
+
const result = xmlDoc.getElementsByTagName('Mensaje')[0].textContent;
- return result.toLowerCase().includes('se ha cancelado correctamente');
+ return ['no se ha encontrado', 'se ha cancelado correctamente'].some(res => result.toLowerCase().includes(res));
};
};
diff --git a/back/methods/osrm-config/optimize.js b/back/methods/osrm-config/optimize.js
new file mode 100644
index 000000000..e0412c74c
--- /dev/null
+++ b/back/methods/osrm-config/optimize.js
@@ -0,0 +1,112 @@
+const UserError = require('vn-loopback/util/user-error');
+const axios = require('axios');
+
+module.exports = Self => {
+ Self.remoteMethod('optimize', {
+ description: 'Return optimized coords',
+ accessType: 'READ',
+ accepts: [{
+ arg: 'addressIds',
+ type: 'array',
+ required: true
+ }, {
+ arg: 'firstAddressId',
+ type: 'number',
+ required: false
+ }, {
+ arg: 'lastAddressId',
+ type: 'number',
+ required: false
+ }],
+ returns: {
+ type: 'object',
+ root: true
+ },
+ http: {
+ path: `/optimize`,
+ verb: 'GET'
+ }
+ });
+
+ Self.optimize = async(addressIds, firstAddressId, lastAddressId) => {
+ const models = Self.app.models;
+ try {
+ const osrmConfig = await models.OsrmConfig.findOne();
+ if (!osrmConfig) throw new UserError(`OSRM service is not configured`);
+
+ let coords = [];
+ if (firstAddressId) {
+ const address = await models.Address.findById(firstAddressId);
+ if (address.latitude && address.longitude) {
+ coords.push({
+ addressId: address.id,
+ latitude: address.latitude.toFixed(6),
+ longitude: address.longitude.toFixed(6)
+ });
+ }
+ }
+
+ for (const addressId of addressIds) {
+ const address = await models.Address.findById(addressId);
+ if (address.latitude && address.longitude) {
+ coords.push({
+ addressId,
+ latitude: address.latitude.toFixed(6),
+ longitude: address.longitude.toFixed(6)
+ });
+ }
+ }
+
+ if (lastAddressId) {
+ const firstAddress = await models.Address.findById(lastAddressId);
+ if (firstAddress.latitude && firstAddress.longitude) {
+ coords.push({
+ addressId: firstAddress.id,
+ latitude: firstAddress.latitude.toFixed(6),
+ longitude: firstAddress.longitude.toFixed(6)
+ });
+ }
+ }
+
+ if (!coords.length) throw new UserError('No address has coordinates');
+
+ const concatCoords = coords
+ .map(coord => `${coord.longitude},${coord.latitude}`)
+ .join(';');
+ const response = await axios.post(`
+ ${osrmConfig.url}/trip/v1/driving/${concatCoords}?source=first&destination=last&roundtrip=true
+ `);
+ const tolerance = osrmConfig.tolerance;
+ for (const waypoint of response.data.waypoints) {
+ const longitude = waypoint.location[0];
+ const latitude = waypoint.location[1];
+
+ const matchedAddress = coords.find(coord =>
+ coord.position === undefined &&
+ Math.abs(coord.latitude - latitude) <= tolerance &&
+ Math.abs(coord.longitude - longitude) <= tolerance
+ );
+ if (matchedAddress)
+ matchedAddress.position = waypoint.waypoint_index;
+ }
+ coords.sort((a, b) => {
+ const posA = a.position !== undefined ? a.position : Infinity;
+ const posB = b.position !== undefined ? b.position : Infinity;
+ return posA - posB;
+ });
+
+ return coords;
+ } catch (err) {
+ switch (err.response?.data?.code) {
+ case 'NoTrips':
+ throw new UserError('No trips found because input coordinates are not connected');
+ case 'NotImplemented':
+ throw new UserError('This request is not supported');
+ case 'InvalidOptions':
+ throw new UserError('Invalid options or too many coordinates');
+ default:
+ throw err;
+ }
+ }
+ };
+};
diff --git a/back/methods/osrm-config/specs/optimize.spec.js b/back/methods/osrm-config/specs/optimize.spec.js
new file mode 100644
index 000000000..9f2adccc6
--- /dev/null
+++ b/back/methods/osrm-config/specs/optimize.spec.js
@@ -0,0 +1,33 @@
+const models = require('vn-loopback/server/server').models;
+
+describe('osrmConfig optimize()', function() {
+ it('should send coords, receive OSRM response, and return a correctly ordered result', async function() {
+ const result = await models.OsrmConfig.optimize([4, 3], 1, 2);
+
+ // Verifications
+ expect(Array.isArray(result)).toBe(true);
+ expect(result.length).toBe(4);
+
+ // Check the order
+ expect(result[0].addressId).toBe(1);
+ expect(result[1].addressId).toBe(4);
+ expect(result[2].addressId).toBe(3);
+ expect(result[3].addressId).toBe(2);
+
+ // Check the coordinates format
+ expect(result[0].latitude).toBe('10.111111');
+ expect(result[0].longitude).toBe('-74.111111');
+ });
+
+ it('should throw an error if no addresses are provided', async function() {
+ let error;
+ try {
+ await models.OsrmConfig.optimize([], null);
+ } catch (e) {
+ error = e;
+ }
+
+ expect(error).toBeDefined();
+ expect(error.message).toBe('No address has coordinates');
+ });
+});
diff --git a/back/methods/osticket/sendToSupport.js b/back/methods/osticket/sendToSupport.js
index e17093839..dabd35f80 100644
--- a/back/methods/osticket/sendToSupport.js
+++ b/back/methods/osticket/sendToSupport.js
@@ -29,35 +29,34 @@ module.exports = Self => {
});
Self.sendToSupport = async(ctx, reason, additionalData) => {
+ const userId = ctx.req.accessToken.userId;
const emailUser =
- await Self.app.models.EmailUser.findById(ctx.req.accessToken.userId, {fields: ['email']});
+ await Self.app.models.EmailUser.findById(userId, {fields: ['email']});
- let html = `Motivo : ${reason} `;
- html += `Usuario : ${ctx.req.accessToken.userId} ${emailUser.email} `;
+ let html = `
Motivo: ${reason} `;
+ html += `Usuario: ${userId} ${emailUser.email} `;
+ html += `Additional Data: `;
+ html += '';
+ for (const [key, val] of Object.entries(additionalData)) {
+ if (key !== 'config') html += `${key}: ${parse(val)} `;
+ else {
+ html += `${key}: `;
+ for (const [confKey, confVal] of Object.entries(val))
+ html += `${confKey}: ${parse(confVal)} `;
+ html += ' ';
+ }
+ }
+ html += ' ';
- delete additionalData.backError.config.headers.Authorization;
- const httpRequest = JSON.parse(additionalData?.httpRequest);
-
- if (httpRequest)
- delete httpRequest.config.headers.Authorization;
- additionalData.httpRequest = httpRequest;
-
- for (const data in additionalData)
- html += `${data} : ${tryParse(additionalData[data])} `;
-
- const subjectReason = httpRequest?.data?.error;
+ const {message, path, name} = additionalData;
await smtp.send({
to: `${config.app.reportEmail}, ${emailUser.email}`,
- subject:
- '[Support-Salix] ' +
- additionalData?.frontPath + ' ' +
- subjectReason?.name + ':' +
- subjectReason?.message,
+ subject: `[Support-Salix] ${path} ${name}: ${message}`,
html
});
};
- function tryParse(value) {
+ function parse(value) {
try {
try {
value = JSON.parse(value);
diff --git a/back/methods/quadminds-api-config/sendOrders.js b/back/methods/quadminds-api-config/sendOrders.js
deleted file mode 100644
index 760d622b6..000000000
--- a/back/methods/quadminds-api-config/sendOrders.js
+++ /dev/null
@@ -1,88 +0,0 @@
-const axios = require('axios');
-const UserError = require('vn-loopback/util/user-error');
-const moment = require('moment');
-
-module.exports = Self => {
- Self.remoteMethod('sendOrders', {
- description: 'Sends a set of orders',
- accessType: 'WRITE',
- accepts: [{
- arg: 'tickets',
- type: ['number'],
- required: true
- }
- ],
- returns: {
- type: 'string',
- root: true
- },
- http: {
- path: `/sendOrders`,
- verb: 'POST'
- }
- });
- Self.sendOrders = async tickets => {
- const config = await Self.app.models.QuadmindsApiConfig.findOne();
- if (!config) throw new UserError('Config params not set');
-
- if (tickets.length > config.maxObjects)
- throw new UserError(`Quadminds does not support more than ${config.maxObjects} tickets`);
-
- let poisData = [];
- let isOk;
- for (let offset = 0; !isOk; offset = offset + config.limit) {
- const pois = await axios.get(`${config.url}pois/search?limit=${config.limit}&offset=${offset}`, {
- headers: {
- 'Accept': 'application/json',
- 'X-Saas-Apikey': config.key
- }
- });
- pois.data.data.length ? poisData.push(...pois.data.data) : isOk = true;
- }
-
- const poiMap = new Map(poisData.map(poi => [poi.code, poi._id]));
-
- let orders = await Self.rawSql(`
- SELECT a.id poiCode,
- t.id code,
- t.shipped date,
- 'PEDIDO' operation,
- t.totalWithVat totalAmount,
- t.totalWithoutVat totalAmountWithoutTaxes,
- SUM(sv.volume) volume
- FROM ticket t
- JOIN address a ON a.id = t.addressFk
- JOIN saleVolume sv ON sv.ticketFk = t.id
- WHERE t.id IN (?)
- GROUP BY t.id
- `, [tickets]);
-
- // Transformo code en string ya que lo obtenermos como integer
- orders = orders.map(order => {
- return {
- ...order,
- poiId: poiMap.get(order.poiCode.toString()) || undefined,
- code: order.code.toString(),
- date: moment(order.date).format('YYYY-MM-DD'),
- totalAmount: order.totalAmount || undefined,
- totalAmountWithoutTaxes: order.totalAmountWithoutTaxes || undefined,
- timeWindow: [{
- from: config.orderTimeFrom,
- to: config.orderTimeTo
- }],
- orderMeasures: [{
- constraintId: 3, // Volumen
- value: order.volume
- }]
- };
- });
-
- await axios.post(`${config.url}orders`, orders, {
- headers: {
- 'Accept': 'application/json',
- 'Content-Type': 'application/json',
- 'X-Saas-Apikey': config.key
- }
- });
- };
-};
diff --git a/back/methods/quadminds-api-config/sendPois.js b/back/methods/quadminds-api-config/sendPois.js
deleted file mode 100644
index cb5eef93e..000000000
--- a/back/methods/quadminds-api-config/sendPois.js
+++ /dev/null
@@ -1,87 +0,0 @@
-const axios = require('axios');
-const UserError = require('vn-loopback/util/user-error');
-
-module.exports = Self => {
- Self.remoteMethod('sendPois', {
- description: 'Sends a set of pois',
- accessType: 'WRITE',
- accepts: [{
- arg: 'tickets',
- type: ['number'],
- required: true
- }
- ],
- returns: {
- type: 'string',
- root: true
- },
- http: {
- path: `/sendPois`,
- verb: 'POST'
- }
- });
- Self.sendPois = async tickets => {
- const config = await Self.app.models.QuadmindsApiConfig.findOne();
- if (!config) throw new UserError('Config params not set');
-
- if (tickets.length > config.maxObjects)
- throw new UserError(`Quadminds does not support more than ${config.maxObjects} tickets`);
-
- let pois = await Self.rawSql(`
- WITH deliveryNotes AS (
- SELECT t.id, t.routeFk, tn.description
- FROM ticket t
- JOIN ticketObservation tn ON tn.ticketFk = t.id
- JOIN observationType ot ON ot.id = tn.observationTypeFk
- WHERE ot.code = 'delivery'
- )
- SELECT a.id code,
- c.socialName name,
- IF(ABS(a.latitude - ROUND(a.latitude)) < 0.000001, NULL, a.latitude) latitude,
- IF(ABS(a.longitude - ROUND(a.longitude)) < 0.000001, NULL, a.longitude) longitude,
- a.street,
- a.city locality,
- p.name state,
- co.name country,
- CONCAT_WS(', ', IFNULL(a.street, ''), IFNULL(a.city, ''), IFNULL(p.name, '')) longAddress,
- CONCAT(IFNULL(a.mobile, c.mobile)) phoneNumber,
- dn.description poiDeliveryComments,
- c.email email
- FROM ticket t
- 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 client c ON c.id = t.clientFk
- LEFT JOIN deliveryNotes dn ON dn.id = t.id
- WHERE t.id IN (?)
- GROUP BY t.id
- `, [tickets]);
-
- // Transformo code en string ya que lo obtenermos como integer
- pois = pois.map(poi => {
- return {
- ...poi,
- code: poi.code.toString(),
- latitude: poi.latitude || undefined,
- longitude: poi.longitude || undefined,
- address: {
- street: poi.street || undefined,
- locality: poi.locality || undefined,
- state: poi.state || undefined,
- country: poi.country || undefined
- },
- poiDeliveryComments: poi.poiDeliveryComments || undefined,
- phoneNumber: poi.phoneNumber || undefined,
- email: poi.email || undefined
- };
- });
-
- await axios.post(`${config.url}pois`, pois, {
- headers: {
- 'Accept': 'application/json',
- 'Content-Type': 'application/json',
- 'X-Saas-Apikey': config.key
- }
- });
- };
-};
diff --git a/back/methods/url/getUrl.js b/back/methods/url/getUrl.js
index 5c6e5655f..fa3f7fdad 100644
--- a/back/methods/url/getUrl.js
+++ b/back/methods/url/getUrl.js
@@ -22,7 +22,7 @@ module.exports = Self => {
const url = await Self.app.models.Url.findOne({
where: {
appName,
- environment: process.env.NODE_ENV || 'dev'
+ environment: process.env.NODE_ENV || 'development'
}
});
return url?.url;
diff --git a/back/methods/vn-user/acls.js b/back/methods/vn-user/acls.js
index 7da75ed2c..347cfa426 100644
--- a/back/methods/vn-user/acls.js
+++ b/back/methods/vn-user/acls.js
@@ -19,7 +19,7 @@ module.exports = Self => {
if (acl.principalType == 'ROLE' && acl.permission == 'ALLOW') {
const staticAcl = {
model: model.name,
- property: '*',
+ property: acl.property,
accessType: acl.accessType,
permission: acl.permission,
principalType: acl.principalType,
diff --git a/back/methods/vn-user/specs/renew-token.spec.js b/back/methods/vn-user/specs/renew-token.spec.js
index 8f1bb54c1..8941916ec 100644
--- a/back/methods/vn-user/specs/renew-token.spec.js
+++ b/back/methods/vn-user/specs/renew-token.spec.js
@@ -72,9 +72,9 @@ describe('Renew Token', () => {
}
expect(error).toBeDefined();
- const query = 'SELECT * FROM util.debug';
- const debugLog = await models.Application.rawSql(query, null);
+ const query = 'SELECT * FROM util.debug WHERE variable = "renewToken"';
+ const debugLog = await models.Application.rawSql(query);
expect(debugLog.length).toEqual(1);
});
diff --git a/back/methods/workerActivity/add.js b/back/methods/workerActivity/add.js
index 4592a0797..89131491d 100644
--- a/back/methods/workerActivity/add.js
+++ b/back/methods/workerActivity/add.js
@@ -31,7 +31,7 @@ module.exports = Self => {
return await Self.rawSql(`
INSERT INTO workerActivity (workerFk, workerActivityTypeFk, model)
SELECT ?, ?, ?
- FROM workerTimeControlParams wtcp
+ FROM workerTimeControlConfig wtcc
LEFT JOIN (
SELECT wa.workerFk,
wa.created,
@@ -44,7 +44,7 @@ module.exports = Self => {
) sub ON TRUE
WHERE sub.workerFk IS NULL
OR sub.code <> ?
- OR TIMESTAMPDIFF(SECOND, sub.created, util.VN_NOW()) > wtcp.dayBreak;`
+ OR TIMESTAMPDIFF(SECOND, sub.created, util.VN_NOW()) > wtcc.dayBreak;`
, [userId, code, model, userId, code], myOptions);
};
};
diff --git a/back/methods/workerActivity/specs/add.spec.js b/back/methods/workerActivity/specs/add.spec.js
index 352d67723..751cce009 100644
--- a/back/methods/workerActivity/specs/add.spec.js
+++ b/back/methods/workerActivity/specs/add.spec.js
@@ -10,10 +10,10 @@ describe('workerActivity insert()', () => {
try {
await models.WorkerActivityType.create(
- {'code': 'STOP', 'description': 'STOP'}, options
+ {'code': 'TEST', 'description': 'TEST'}, options
);
- await models.WorkerActivity.add(ctx, 'STOP', 'APP', options);
+ await models.WorkerActivity.add(ctx, 'TEST', 'APP', options);
count = await models.WorkerActivity.count(
{'workerFK': 1106}, options
diff --git a/back/model-config.json b/back/model-config.json
index 20bfb06bd..2ced867f7 100644
--- a/back/model-config.json
+++ b/back/model-config.json
@@ -79,21 +79,21 @@
"ImageCollectionSize": {
"dataSource": "vn"
},
+ "ImageConfig": {
+ "dataSource": "vn"
+ },
"ImageContainer": {
"dataSource": "imageStorage"
},
"Language": {
"dataSource": "vn"
},
+ "OsrmConfig": {
+ "dataSource": "vn"
+ },
"Machine": {
"dataSource": "vn"
},
- "MachineWorker": {
- "dataSource": "vn"
- },
- "MachineWorkerConfig": {
- "dataSource": "vn"
- },
"MobileAppVersionControl": {
"dataSource": "vn"
},
@@ -124,18 +124,21 @@
"Province": {
"dataSource": "vn"
},
- "QuadmindsApiConfig": {
- "dataSource": "vn"
- },
"Autonomy": {
"dataSource": "vn"
},
"Payment": {
"dataSource": "vn"
},
+ "PbxConfig": {
+ "dataSource": "vn"
+ },
"Postcode": {
"dataSource": "vn"
},
+ "Prefix": {
+ "dataSource": "vn"
+ },
"ReferenceRate": {
"dataSource": "vn"
},
@@ -145,6 +148,12 @@
"StarredModule": {
"dataSource": "vn"
},
+ "SaySimpleCountry": {
+ "dataSource": "vn"
+ },
+ "SaySimpleConfig": {
+ "dataSource": "vn"
+ },
"TempContainer": {
"dataSource": "tempStorage"
},
@@ -175,6 +184,9 @@
"PrintConfig": {
"dataSource": "vn"
},
+ "QueueMember": {
+ "dataSource": "vn"
+ },
"ViaexpressConfig": {
"dataSource": "vn"
},
diff --git a/back/models/autonomy.json b/back/models/autonomy.json
index 8c9d82936..214061cf5 100644
--- a/back/models/autonomy.json
+++ b/back/models/autonomy.json
@@ -16,6 +16,10 @@
"name": {
"type": "string",
"required": true
+ },
+ "hasDailyInvoice": {
+ "type": "boolean",
+ "description": "Indicates if the autonomy has daily invoice enabled"
}
},
"relations": {
@@ -40,4 +44,4 @@
"permission": "ALLOW"
}
]
-}
\ No newline at end of file
+}
diff --git a/back/models/country.json b/back/models/country.json
index 5b9d842a8..ee72ae49d 100644
--- a/back/models/country.json
+++ b/back/models/country.json
@@ -28,6 +28,10 @@
},
"continentFk": {
"type": "number"
+ },
+ "hasDailyInvoice": {
+ "type": "boolean",
+ "description": "Indicates if the autonomy has daily invoice enabled"
}
},
"relations": {
@@ -40,6 +44,11 @@
"type": "belongsTo",
"model": "Continent",
"foreignKey": "continentFk"
+ },
+ "saySimpleCountry": {
+ "type": "hasOne",
+ "model": "SaySimpleCountry",
+ "foreignKey": "countryFk"
}
},
"acls": [
@@ -50,4 +59,4 @@
"permission": "ALLOW"
}
]
-}
+}
\ No newline at end of file
diff --git a/back/models/docuware-config.json b/back/models/docuware-config.json
index 9d06c4874..b15cb4c03 100644
--- a/back/models/docuware-config.json
+++ b/back/models/docuware-config.json
@@ -16,17 +16,17 @@
"url": {
"type": "string"
},
- "cookie": {
+ "token": {
"type": "string"
+ },
+ "username": {
+ "type": "string"
+ },
+ "password": {
+ "type": "string"
+ },
+ "expired":{
+ "type": "number"
}
- },
- "acls": [
- {
- "property": "*",
- "accessType": "*",
- "principalType": "ROLE",
- "principalId": "$everyone",
- "permission": "ALLOW"
- }
- ]
+ }
}
diff --git a/back/models/expedition_PrintOut.json b/back/models/expedition_PrintOut.json
index dd49b0234..23a2fdbc4 100644
--- a/back/models/expedition_PrintOut.json
+++ b/back/models/expedition_PrintOut.json
@@ -14,9 +14,6 @@
},
"itemFk": {
"type": "number"
- },
- "isChecked": {
- "type": "boolean"
}
}
}
\ No newline at end of file
diff --git a/back/models/image-config.json b/back/models/image-config.json
new file mode 100644
index 000000000..11f4c2284
--- /dev/null
+++ b/back/models/image-config.json
@@ -0,0 +1,22 @@
+{
+ "name": "ImageConfig",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "hedera.imageConfig"
+ }
+ },
+ "properties": {
+ "url": {
+ "type": "string"
+ }
+ },
+ "acls": [
+ {
+ "accessType": "READ",
+ "principalType": "ROLE",
+ "principalId": "$authenticated",
+ "permission": "ALLOW"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/back/models/machine-worker-config.json b/back/models/machine-worker-config.json
deleted file mode 100644
index dfb77124e..000000000
--- a/back/models/machine-worker-config.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "name": "MachineWorkerConfig",
- "base": "VnModel",
- "options": {
- "mysql": {
- "table": "vn.machineWorkerConfig"
- }
- },
- "properties": {
- "id": {
- "type": "number",
- "id": true
- },
- "maxHours": {
- "type": "number"
- }
- }
-}
diff --git a/back/models/machine-worker.js b/back/models/machine-worker.js
deleted file mode 100644
index cbc5fd53e..000000000
--- a/back/models/machine-worker.js
+++ /dev/null
@@ -1,3 +0,0 @@
-module.exports = Self => {
- require('../methods/machine-worker/updateInTime')(Self);
-};
diff --git a/back/models/machine-worker.json b/back/models/machine-worker.json
deleted file mode 100644
index 2244a533f..000000000
--- a/back/models/machine-worker.json
+++ /dev/null
@@ -1,33 +0,0 @@
-{
- "name": "MachineWorker",
- "base": "VnModel",
- "options": {
- "mysql": {
- "table": "vn.machineWorker"
- }
- },
- "properties": {
- "id": {
- "type": "number",
- "id": true
- },
- "workerFk": {
- "type": "number"
- },
- "machineFk": {
- "type": "number"
- },
- "inTime": {
- "type": "date",
- "mysql": {
- "columnName": "inTimed"
- }
- },
- "outTime": {
- "type": "date",
- "mysql": {
- "columnName": "outTimed"
- }
- }
- }
-}
diff --git a/back/models/osrm-config.js b/back/models/osrm-config.js
new file mode 100644
index 000000000..f738f305c
--- /dev/null
+++ b/back/models/osrm-config.js
@@ -0,0 +1,4 @@
+module.exports = Self => {
+ require('../methods/osrm-config/optimize')(Self);
+};
+
diff --git a/back/models/osrm-config.json b/back/models/osrm-config.json
new file mode 100644
index 000000000..ae712ba05
--- /dev/null
+++ b/back/models/osrm-config.json
@@ -0,0 +1,24 @@
+{
+ "name": "OsrmConfig",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "osrmConfig"
+ }
+ },
+ "properties": {
+ "id": {
+ "type": "number",
+ "id": true,
+ "required": true
+ },
+ "url": {
+ "type": "string",
+ "required": true
+ },
+ "tolerance": {
+ "type": "number",
+ "required": false
+ }
+ }
+}
diff --git a/back/models/pbx-config.json b/back/models/pbx-config.json
new file mode 100644
index 000000000..44137b55d
--- /dev/null
+++ b/back/models/pbx-config.json
@@ -0,0 +1,27 @@
+{
+ "name": "PbxConfig",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "pbx.config"
+ }
+ },
+ "properties": {
+ "id": {
+ "type": "number",
+ "id": true
+ },
+ "defaultPrefix": {
+ "type": "string"
+ }
+ },
+ "acls": [
+ {
+ "property": "*",
+ "accessType": "READ",
+ "principalType": "ROLE",
+ "principalId": "employee",
+ "permission": "ALLOW"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/back/models/prefix.json b/back/models/prefix.json
new file mode 100644
index 000000000..762354caa
--- /dev/null
+++ b/back/models/prefix.json
@@ -0,0 +1,27 @@
+{
+ "name": "Prefix",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "pbx.prefix"
+ }
+ },
+ "properties": {
+ "country": {
+ "type": "string",
+ "id": true
+ },
+ "prefix": {
+ "type": "string"
+ }
+ },
+ "acls": [
+ {
+ "property": "*",
+ "accessType": "READ",
+ "principalType": "ROLE",
+ "principalId": "employee",
+ "permission": "ALLOW"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/back/models/production-config.json b/back/models/production-config.json
index 2fc6d71ff..048264e8c 100644
--- a/back/models/production-config.json
+++ b/back/models/production-config.json
@@ -20,6 +20,9 @@
},
"backupPrinterNotificationDelay": {
"type": "string"
+ },
+ "itemOrderReviewHours": {
+ "type": "number"
}
}
}
\ No newline at end of file
diff --git a/back/models/province.json b/back/models/province.json
index 77e0b24a6..61a1574d7 100644
--- a/back/models/province.json
+++ b/back/models/province.json
@@ -16,6 +16,9 @@
"name": {
"type": "string",
"required": true
+ },
+ "autonomyFk": {
+ "type": "number"
}
},
"relations": {
@@ -55,4 +58,4 @@
"permission": "ALLOW"
}
]
-}
\ No newline at end of file
+}
diff --git a/back/models/quadminds-api-config.js b/back/models/quadminds-api-config.js
deleted file mode 100644
index c2773fa0b..000000000
--- a/back/models/quadminds-api-config.js
+++ /dev/null
@@ -1,4 +0,0 @@
-module.exports = Self => {
- require('../methods/quadminds-api-config/sendPois')(Self);
- require('../methods/quadminds-api-config/sendOrders')(Self);
-};
diff --git a/back/models/quadminds-api-config.json b/back/models/quadminds-api-config.json
deleted file mode 100644
index 4001badf3..000000000
--- a/back/models/quadminds-api-config.json
+++ /dev/null
@@ -1,34 +0,0 @@
-{
- "name": "QuadmindsApiConfig",
- "base": "VnModel",
- "options": {
- "mysql": {
- "table": "quadmindsApiConfig"
- }
- },
- "properties": {
- "id": {
- "type": "number",
- "id": true,
- "required": true
- },
- "url": {
- "type": "string"
- },
- "key": {
- "type": "string"
- },
- "maxObjects": {
- "type": "number"
- },
- "limit": {
- "type": "number"
- },
- "orderTimeFrom": {
- "type": "string"
- },
- "orderTimeTo": {
- "type": "string"
- }
- }
-}
diff --git a/back/models/queue-member.json b/back/models/queue-member.json
new file mode 100644
index 000000000..93ca2ebd7
--- /dev/null
+++ b/back/models/queue-member.json
@@ -0,0 +1,38 @@
+{
+ "name": "QueueMember",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "pbx.queueMember"
+ }
+ },
+ "properties": {
+ "id": {
+ "type": "number",
+ "id": true
+ },
+ "queue": {
+ "type": "string"
+ },
+ "extension": {
+ "type": "string"
+ }
+ },
+ "relations": {
+ "queueRelation": {
+ "type": "belongsTo",
+ "model": "Queue",
+ "foreignKey": "queue",
+ "primaryKey": "name"
+ }
+ },
+ "acls": [
+ {
+ "property": "*",
+ "accessType": "READ",
+ "principalType": "ROLE",
+ "principalId": "employee",
+ "permission": "ALLOW"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/back/models/say-simple-config.json b/back/models/say-simple-config.json
new file mode 100644
index 000000000..d5d4f8a6f
--- /dev/null
+++ b/back/models/say-simple-config.json
@@ -0,0 +1,29 @@
+{
+ "name": "SaySimpleConfig",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "saySimpleConfig"
+ }
+ },
+ "properties": {
+ "id": {
+ "type": "number",
+ "id": true
+ },
+ "url": {
+ "type": "string"
+ },
+ "defaultChannel": {
+ "type": "number"
+ }
+ },
+ "acls": [
+ {
+ "accessType": "READ",
+ "principalType": "ROLE",
+ "principalId": "$authenticated",
+ "permission": "ALLOW"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/back/models/say-simple-country.json b/back/models/say-simple-country.json
new file mode 100644
index 000000000..adddddc02
--- /dev/null
+++ b/back/models/say-simple-country.json
@@ -0,0 +1,26 @@
+{
+ "name": "SaySimpleCountry",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "saySimpleCountry"
+ }
+ },
+ "properties": {
+ "countryFk": {
+ "type": "number",
+ "id": true
+ },
+ "channel": {
+ "type": "number"
+ }
+ },
+ "acls": [
+ {
+ "accessType": "READ",
+ "principalType": "ROLE",
+ "principalId": "$authenticated",
+ "permission": "ALLOW"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/back/process.yml b/back/process.yml
deleted file mode 100644
index 94072b57d..000000000
--- a/back/process.yml
+++ /dev/null
@@ -1,7 +0,0 @@
-apps:
- - script: ./loopback/server/server.js
- name: salix-back
- instances: 1
- max_restarts: 0
- autorestart: false
- node_args: --tls-min-v1.0 --openssl-legacy-provider
diff --git a/db/.pullinfo.json b/db/.pullinfo.json
index 5b75584d1..b890ffc31 100644
--- a/db/.pullinfo.json
+++ b/db/.pullinfo.json
@@ -9,7 +9,7 @@
},
"vn": {
"view": {
- "expeditionPallet_Print": "99f75145ac2e7b612a6d71e74b6e55f194a465780fd9875a15eb01e6596b447e"
+ "expeditionPallet_Print": "04fc5f2967ce53bfbb85f7f48b9a3dca4a4f7111ac41e1775f4cc7d6538774b2"
}
}
}
diff --git a/db/dump/.dump/data.sql b/db/dump/.dump/data.sql
index 5800d6ecd..cd978e4a8 100644
--- a/db/dump/.dump/data.sql
+++ b/db/dump/.dump/data.sql
@@ -4,7 +4,7 @@ USE `util`;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
-INSERT INTO `version` VALUES ('vn-database','11196','91ee956fbd1557848e4ab522bc5d39b2ec10e9b2','2024-09-18 07:28:14','11245');
+INSERT INTO `version` VALUES ('vn-database','11377','d3fe5098277c3935c434838b53facb271f84ebec','2024-12-10 07:22:33','11379');
INSERT INTO `versionLog` VALUES ('vn-database','10107','00-firstScript.sql','jenkins@10.0.2.69','2022-04-23 10:53:53',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','10112','00-firstScript.sql','jenkins@10.0.2.69','2022-05-09 09:14:53',NULL,NULL);
@@ -862,6 +862,7 @@ INSERT INTO `versionLog` VALUES ('vn-database','11083','00-firstScript.sql','jen
INSERT INTO `versionLog` VALUES ('vn-database','11084','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11086','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-27 10:02:02',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11087','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11088','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:44:48',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11089','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:39:16',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11090','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:35',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11092','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-07 08:21:23',NULL,NULL);
@@ -875,12 +876,37 @@ INSERT INTO `versionLog` VALUES ('vn-database','11103','00-firstScript.sql','jen
INSERT INTO `versionLog` VALUES ('vn-database','11104','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11105','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-20 15:36:07',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11106','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:39:49',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:44:48',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','01-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:44:48',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','02-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:44:48',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','03-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:44:48',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','04-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:44:49',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','05-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:44:49',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','06-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:45:04',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','07-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:45:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','08-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:45:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','09-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:45:47',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','10-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:45:48',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','11-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:45:59',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','12-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:46:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','14-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:46:00',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','15-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:46:06',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','17-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:46:06',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','18-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:46:06',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','19-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:46:19',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','20-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:46:19',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','21-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:34',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','22-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:34',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','23-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:35',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11107','24-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:35',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11108','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-17 07:38:39',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11109','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-18 19:09:56',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11110','00-clientUnpaid.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11111','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11112','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-17 07:38:40',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11113','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:35',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11114','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:39:49',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11115','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:35',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11116','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11117','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11118','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-07-19 12:28:49',NULL,NULL);
@@ -942,6 +968,7 @@ INSERT INTO `versionLog` VALUES ('vn-database','11172','14-firstScript.sql','jen
INSERT INTO `versionLog` VALUES ('vn-database','11172','15-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-03 08:57:44',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11175','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-03 08:57:44',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11177','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-07-30 12:42:28',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11178','00-aclSetWeight.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:35',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11179','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-08-20 08:34:43',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11180','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-08-20 08:34:43',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11182','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-08-09 08:19:36',NULL,NULL);
@@ -961,18 +988,147 @@ INSERT INTO `versionLog` VALUES ('vn-database','11194','00-firstScript.sql','jen
INSERT INTO `versionLog` VALUES ('vn-database','11195','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-03 08:58:01',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11196','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-18 07:28:14',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11197','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-03 08:58:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11198','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 07:42:49',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11201','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-08-27 13:04:26',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11204','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-03 08:58:01',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11205','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-04 13:54:55',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11206','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-17 07:38:42',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11207','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-17 07:38:42',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11209','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-03 08:58:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11210','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:35',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11210','01-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:35',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11210','02-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:40',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11210','03-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:41',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11211','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-17 07:38:42',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11213','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-06 06:31:13',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11215','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-17 07:38:42',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11216','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:41',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11217','00-hederaMessages.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-09 12:21:45',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11219','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11221','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11222','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11223','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11224','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11225','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11225','01-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11225','02-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:41',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11227','00-addWorkerTimeControlMailAcl.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:41',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11229','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-16 08:24:17',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11230','00-addClientObservationType.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 07:42:52',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11234','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:42',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11235','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11236','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11236','01-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11237','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL);
INSERT INTO `versionLog` VALUES ('vn-database','11239','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-17 12:57:06',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11240','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11241','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-20 09:08:25',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11242','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 07:42:52',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11246','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-18 12:39:53',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11247','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-19 12:10:08',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11248','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-23 11:12:17',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11249','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11251','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 07:43:38',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11251','01-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 07:57:30',NULL,'Connection lost: The server closed the connection.');
+INSERT INTO `versionLog` VALUES ('vn-database','11253','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-20 14:41:27',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11254','00-thermographTemperature.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:13',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11254','01-thermographFk.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:15',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11255','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11256','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-23 12:18:24',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11258','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:15',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11260','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:15',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11261','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:15',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11262','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11263','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-27 12:05:32',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11264','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:15',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11271','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:15',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11272','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:15',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11273','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 10:50:51',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11274','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:16',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11274','00-firstScript2.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:29',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11274','00-firstScript3.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11274','00-firstScript5.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:35',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11274','00-firstScript6.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:35',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11274','00-firstScript7.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:36',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11277','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:36',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11278','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11279','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-10-02 08:05:24',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11280','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-02 08:46:50',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11281','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:36',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11283','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:36',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11284','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:36',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11285','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:37',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11287','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:37',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11288','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-10 08:26:34',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11289','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-15 07:01:33',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11290','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:37',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11291','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-17 09:10:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11294','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:37',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11295','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-10 08:45:13',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11297','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:05:29',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11297','01-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:05:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11298','00-closure.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:37',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11300','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-18 08:27:05',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11302','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:57',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11308','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-23 12:41:55',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11311','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:57',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11312','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-12-10 07:20:04',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11314','00-restrictedAsterisk.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:05:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11315','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:05:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11316','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:05:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11317','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:05:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11319','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:05:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11321','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:05:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11322','00-entryAcl.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-12-10 07:20:04',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11324','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-13 10:49:47',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11325','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:05:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11326','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:05:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11330','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:05:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11331','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:05:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11332','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-12-10 07:20:04',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11336','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:05:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11337','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:05:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11338','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 09:14:12',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11339','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:05:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11341','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-12-10 07:20:04',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11342','00-itemShelving.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:06:34',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11342','01-itemShelving.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:06:35',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11342','02-itemShelving.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:06:37',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11342','03-itemShelving.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:11:07',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11342','04-itemShelvingLog.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:11:07',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11342','05-itemShelvingLog.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:11:07',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11342','06-itemShelvingLog.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:11:07',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11343','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:11:07',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11344','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-13 17:36:45',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11344','01-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-13 17:46:26',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11345','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:11:08',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11346','00-address.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:15:02',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11346','01-client.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:16:29',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11346','02-supplier.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:27:57',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11347','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:27:57',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11348','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:28:14',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11349','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:28:14',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11350','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:28:14',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11351','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-12-10 07:20:04',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11353','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:28:14',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11354','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-12-10 07:20:04',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11355','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:28:14',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11357','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:28:16',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11358','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-26 07:28:21',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11359','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-12-10 07:20:04',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11362','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-28 08:52:33',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11363','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-12-10 07:20:04',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11366','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-12-10 07:20:04',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11367','00-deprecate.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-12-10 07:20:04',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11369','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-12-10 07:20:05',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11371','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-12-10 07:20:05',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11371','01-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-12-10 07:20:47',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11371','02-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-12-10 07:22:29',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11371','03-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-12-10 07:22:31',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11372','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-12-09 13:30:30',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11373','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-12-02 16:09:01',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11375','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-12-03 08:58:20',NULL,NULL);
+INSERT INTO `versionLog` VALUES ('vn-database','11377','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-12-10 07:22:31',NULL,NULL);
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
@@ -1345,6 +1501,10 @@ INSERT INTO `roleInherit` VALUES (373,131,2,19295);
INSERT INTO `roleInherit` VALUES (375,120,131,1437);
INSERT INTO `roleInherit` VALUES (376,124,21,19336);
INSERT INTO `roleInherit` VALUES (377,47,49,19295);
+INSERT INTO `roleInherit` VALUES (378,101,15,19294);
+INSERT INTO `roleInherit` VALUES (379,103,121,19294);
+INSERT INTO `roleInherit` VALUES (381,119,123,19295);
+INSERT INTO `roleInherit` VALUES (382,48,72,783);
INSERT INTO `userPassword` VALUES (1,7,1,0,2,1);
@@ -1445,7 +1605,7 @@ INSERT INTO `ACL` VALUES (112,'Defaulter','*','READ','ALLOW','ROLE','employee',N
INSERT INTO `ACL` VALUES (113,'ClientRisk','*','READ','ALLOW','ROLE','trainee',NULL);
INSERT INTO `ACL` VALUES (114,'Receipt','*','READ','ALLOW','ROLE','trainee',NULL);
INSERT INTO `ACL` VALUES (115,'Receipt','*','WRITE','ALLOW','ROLE','administrative',NULL);
-INSERT INTO `ACL` VALUES (116,'BankEntity','*','*','ALLOW','ROLE','employee',NULL);
+INSERT INTO `ACL` VALUES (116,'BankEntity','*','READ','ALLOW','ROLE','employee',10578);
INSERT INTO `ACL` VALUES (117,'ClientSample','*','*','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson',NULL);
INSERT INTO `ACL` VALUES (119,'Travel','*','READ','ALLOW','ROLE','employee',NULL);
@@ -1526,7 +1686,6 @@ INSERT INTO `ACL` VALUES (209,'Ticket','recalculateComponents','WRITE','ALLOW','
INSERT INTO `ACL` VALUES (211,'TravelLog','*','READ','ALLOW','ROLE','buyer',NULL);
INSERT INTO `ACL` VALUES (212,'Thermograph','*','*','ALLOW','ROLE','buyer',NULL);
INSERT INTO `ACL` VALUES (213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer',NULL);
-INSERT INTO `ACL` VALUES (214,'Entry','*','*','ALLOW','ROLE','buyer',NULL);
INSERT INTO `ACL` VALUES (216,'TravelThermograph','*','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (218,'Intrastat','*','*','ALLOW','ROLE','buyer',NULL);
INSERT INTO `ACL` VALUES (221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','guest',NULL);
@@ -1541,8 +1700,6 @@ INSERT INTO `ACL` VALUES (234,'WorkerLog','find','READ','ALLOW','ROLE','hr',NULL
INSERT INTO `ACL` VALUES (235,'CustomsAgent','*','*','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (236,'Buy','*','*','ALLOW','ROLE','buyer',NULL);
INSERT INTO `ACL` VALUES (237,'WorkerDms','filter','*','ALLOW','ROLE','employee',NULL);
-INSERT INTO `ACL` VALUES (238,'Town','*','WRITE','ALLOW','ROLE','deliveryAssistant',NULL);
-INSERT INTO `ACL` VALUES (239,'Province','*','WRITE','ALLOW','ROLE','deliveryAssistant',NULL);
INSERT INTO `ACL` VALUES (241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative',NULL);
INSERT INTO `ACL` VALUES (248,'RoleMapping','*','READ','ALLOW','ROLE','account',NULL);
INSERT INTO `ACL` VALUES (249,'UserPassword','*','READ','ALLOW','ROLE','account',NULL);
@@ -1556,8 +1713,7 @@ INSERT INTO `ACL` VALUES (257,'FixedPrice','*','*','ALLOW','ROLE','buyer',NULL);
INSERT INTO `ACL` VALUES (258,'PayDem','*','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant',NULL);
INSERT INTO `ACL` VALUES (260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee',NULL);
-INSERT INTO `ACL` VALUES (261,'SupplierAccount','*','*','ALLOW','ROLE','administrative',NULL);
-INSERT INTO `ACL` VALUES (262,'Entry','*','*','ALLOW','ROLE','administrative',NULL);
+INSERT INTO `ACL` VALUES (261,'SupplierAccount','*','WRITE','ALLOW','ROLE','administrative',783);
INSERT INTO `ACL` VALUES (263,'InvoiceIn','*','READ','ALLOW','ROLE','administrative',NULL);
INSERT INTO `ACL` VALUES (264,'StarredModule','*','*','ALLOW','ROLE','$authenticated',NULL);
INSERT INTO `ACL` VALUES (265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss',NULL);
@@ -1663,7 +1819,6 @@ INSERT INTO `ACL` VALUES (378,'OsTicket','osTicketReportEmail','WRITE','ALLOW','
INSERT INTO `ACL` VALUES (379,'Item','buyerWasteEmail','WRITE','ALLOW','ROLE','system',NULL);
INSERT INTO `ACL` VALUES (380,'Claim','claimPickupPdf','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (381,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','claimManager',NULL);
-INSERT INTO `ACL` VALUES (382,'Item','labelPdf','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (383,'Sector','*','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (384,'Sector','*','WRITE','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (385,'Route','driverRoutePdf','READ','ALLOW','ROLE','employee',NULL);
@@ -1875,13 +2030,11 @@ INSERT INTO `ACL` VALUES (605,'Ticket','sendSms','WRITE','ALLOW','ROLE','employe
INSERT INTO `ACL` VALUES (606,'Ticket','isLocked','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (607,'Ticket','freightCost','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (608,'Ticket','getComponentsSum','READ','ALLOW','ROLE','employee',NULL);
-INSERT INTO `ACL` VALUES (609,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','delivery',NULL);
+INSERT INTO `ACL` VALUES (609,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','delivery',19295);
INSERT INTO `ACL` VALUES (610,'Ticket','deliveryNoteCsv','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (611,'State','find','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (612,'State','findById','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (613,'State','findOne','READ','ALLOW','ROLE','employee',NULL);
-INSERT INTO `ACL` VALUES (614,'Worker','find','READ','ALLOW','ROLE','employee',NULL);
-INSERT INTO `ACL` VALUES (616,'Worker','findOne','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (617,'Worker','filter','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (618,'Worker','getWorkedHours','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (619,'Worker','active','READ','ALLOW','ROLE','employee',NULL);
@@ -1931,7 +2084,7 @@ INSERT INTO `ACL` VALUES (699,'TicketSms','find','READ','ALLOW','ROLE','salesPer
INSERT INTO `ACL` VALUES (701,'Docuware','upload','WRITE','ALLOW','ROLE','deliveryAssistant',NULL);
INSERT INTO `ACL` VALUES (702,'Ticket','docuwareDownload','READ','ALLOW','ROLE','salesPerson',NULL);
INSERT INTO `ACL` VALUES (703,'Worker','search','READ','ALLOW','ROLE','employee',NULL);
-INSERT INTO `ACL` VALUES (704,'ExpeditionState','addExpeditionState','WRITE','ALLOW','ROLE','delivery',NULL);
+INSERT INTO `ACL` VALUES (704,'ExpeditionState','addExpeditionState','WRITE','ALLOW','ROLE','production',19294);
INSERT INTO `ACL` VALUES (705,'SaleGroupDetail','deleteById','WRITE','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (706,'Ticket','setDeleted','WRITE','ALLOW','ROLE','buyer',NULL);
INSERT INTO `ACL` VALUES (707,'DeviceLog','create','WRITE','ALLOW','ROLE','employee',NULL);
@@ -1947,7 +2100,6 @@ INSERT INTO `ACL` VALUES (716,'ExpeditionMistake','*','WRITE','ALLOW','ROLE','em
INSERT INTO `ACL` VALUES (717,'WorkerMistake','*','WRITE','ALLOW','ROLE','coolerAssist',NULL);
INSERT INTO `ACL` VALUES (718,'MistakesTypes','*','WRITE','ALLOW','ROLE','coolerAssist',NULL);
INSERT INTO `ACL` VALUES (719,'MistakeType','*','READ','ALLOW','ROLE','employee',NULL);
-INSERT INTO `ACL` VALUES (720,'MachineWorker','*','READ','ALLOW','ROLE','coolerAssist',NULL);
INSERT INTO `ACL` VALUES (721,'Printer','*','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (722,'SaleMistake','*','WRITE','ALLOW','ROLE','production',NULL);
INSERT INTO `ACL` VALUES (723,'Item','setVisibleDiscard','WRITE','ALLOW','ROLE','employee',NULL);
@@ -1976,7 +2128,7 @@ INSERT INTO `ACL` VALUES (746,'Claim','getSummary','READ','ALLOW','ROLE','claimV
INSERT INTO `ACL` VALUES (747,'CplusRectificationType','*','READ','ALLOW','ROLE','administrative',NULL);
INSERT INTO `ACL` VALUES (748,'SiiTypeInvoiceOut','*','READ','ALLOW','ROLE','salesPerson',NULL);
INSERT INTO `ACL` VALUES (749,'InvoiceCorrectionType','*','READ','ALLOW','ROLE','salesPerson',NULL);
-INSERT INTO `ACL` VALUES (750,'InvoiceOut','transferInvoice','WRITE','ALLOW','ROLE','administrative',NULL);
+INSERT INTO `ACL` VALUES (750,'InvoiceOut','transfer','WRITE','ALLOW','ROLE','administrative',NULL);
INSERT INTO `ACL` VALUES (751,'Application','executeProc','*','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (752,'Application','executeFunc','*','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (753,'NotificationSubscription','getList','READ','ALLOW','ROLE','employee',NULL);
@@ -1985,13 +2137,10 @@ INSERT INTO `ACL` VALUES (755,'Route','findById','READ','ALLOW','ROLE','employee
INSERT INTO `ACL` VALUES (756,'Route','findOne','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (757,'Route','getRoutesByWorker','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (758,'Route','canViewAllRoute','READ','ALLOW','ROLE','deliveryAssistant',NULL);
-INSERT INTO `ACL` VALUES (759,'Route','cmr','READ','ALLOW','ROLE','employee',NULL);
-INSERT INTO `ACL` VALUES (760,'Route','downloadCmrsZip','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (761,'Route','downloadZip','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (762,'Route','filter','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (763,'Route','getByWorker','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (764,'Route','getDeliveryPoint','READ','ALLOW','ROLE','employee',NULL);
-INSERT INTO `ACL` VALUES (765,'Route','cmrs','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (766,'Route','getSuggestedTickets','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (767,'Route','getTickets','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (768,'Route','guessPriority','WRITE','ALLOW','ROLE','employee',NULL);
@@ -2032,7 +2181,6 @@ INSERT INTO `ACL` VALUES (802,'MailAliasAccount','deleteById','WRITE','ALLOW','R
INSERT INTO `ACL` VALUES (804,'DeviceProduction','*','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (805,'Collection','assign','WRITE','ALLOW','ROLE','production',NULL);
INSERT INTO `ACL` VALUES (806,'ExpeditionPallet','getPallet','READ','ALLOW','ROLE','production',NULL);
-INSERT INTO `ACL` VALUES (807,'MachineWorker','updateInTime','WRITE','ALLOW','ROLE','production',NULL);
INSERT INTO `ACL` VALUES (808,'MobileAppVersionControl','getVersion','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (809,'SaleTracking','delete','WRITE','ALLOW','ROLE','production',NULL);
INSERT INTO `ACL` VALUES (810,'SaleTracking','updateTracking','WRITE','ALLOW','ROLE','production',NULL);
@@ -2115,13 +2263,12 @@ INSERT INTO `ACL` VALUES (892,'WorkerIncome','*','*','ALLOW','ROLE','hr',NULL);
INSERT INTO `ACL` VALUES (893,'PayrollComponent','*','*','ALLOW','ROLE','hr',NULL);
INSERT INTO `ACL` VALUES (894,'Worker','__get__incomes','*','ALLOW','ROLE','hr',NULL);
INSERT INTO `ACL` VALUES (895,'ItemShelvingLog','*','READ','ALLOW','ROLE','production',NULL);
-INSERT INTO `ACL` VALUES (897,'WorkerLog','*','READ','ALLOW','ROLE','employee',NULL);
INSERT INTO `ACL` VALUES (901,'WorkerTimeControl','sendMail','WRITE','ALLOW','ROLE','system',NULL);
INSERT INTO `ACL` VALUES (902,'Entry','filter','READ','ALLOW','ROLE','supplier',NULL);
INSERT INTO `ACL` VALUES (903,'Entry','getBuys','READ','ALLOW','ROLE','supplier',NULL);
-INSERT INTO `ACL` VALUES (904,'Entry','buyLabel','READ','ALLOW','ROLE','supplier',NULL);
+INSERT INTO `ACL` VALUES (904,'Entry','buyLabelSupplier','READ','ALLOW','ROLE','supplier',19295);
INSERT INTO `ACL` VALUES (905,'AddressWaste','*','READ','ALLOW','ROLE','production',NULL);
-INSERT INTO `ACL` VALUES (906,'Entry','print','READ','ALLOW','ROLE','supplier',NULL);
+INSERT INTO `ACL` VALUES (906,'Entry','labelSupplier','READ','ALLOW','ROLE','supplier',19295);
INSERT INTO `ACL` VALUES (907,'Expedition_PrintOut','*','*','ALLOW','ROLE','production',NULL);
INSERT INTO `ACL` VALUES (908,'Docuware','upload','WRITE','ALLOW','ROLE','hrBuyer',13657);
INSERT INTO `ACL` VALUES (909,'Entry','getBuysCsv','READ','ALLOW','ROLE','supplier',19295);
@@ -2131,12 +2278,97 @@ INSERT INTO `ACL` VALUES (912,'Worker','__get__medicalReview','*','ALLOW','ROLE'
INSERT INTO `ACL` VALUES (913,'VnToken','*','READ','ALLOW','ROLE','developer',10578);
INSERT INTO `ACL` VALUES (914,'VnToken','killSession','*','ALLOW','ROLE','developer',10578);
INSERT INTO `ACL` VALUES (915,'ACL','*','WRITE','ALLOW','ROLE','developerBoss',10578);
-INSERT INTO `ACL` VALUES (916,'Entry','getBuysCsv','READ','ALLOW','ROLE','supplier',10578);
INSERT INTO `ACL` VALUES (917,'InvoiceOut','refundAndInvoice','WRITE','ALLOW','ROLE','administrative',10578);
INSERT INTO `ACL` VALUES (918,'Worker','__get__descriptor','READ','ALLOW','ROLE','employee',10578);
-INSERT INTO `ACL` VALUES (919,'Worker','findById','READ','ALLOW','ROLE','$subordinate',10578);
INSERT INTO `ACL` VALUES (920,'QuadmindsApiConfig','*','*','ALLOW','ROLE','delivery',19295);
-INSERT INTO `ACL` VALUES (921,'Worker','findById','READ','ALLOW','ROLE','employee',NULL);
+INSERT INTO `ACL` VALUES (922,'SaleGroup','*','WRITE','ALLOW','ROLE','production',19294);
+INSERT INTO `ACL` VALUES (923,'Worker','__get__advancedSummary','READ','ALLOW','ROLE','hr',10578);
+INSERT INTO `ACL` VALUES (924,'Worker','__get__summary','READ','ALLOW','ROLE','employee',10578);
+INSERT INTO `ACL` VALUES (925,'Postcode','*','WRITE','ALLOW','ROLE','administrative',10578);
+INSERT INTO `ACL` VALUES (926,'Province','*','WRITE','ALLOW','ROLE','administrative',10578);
+INSERT INTO `ACL` VALUES (927,'Town','*','WRITE','ALLOW','ROLE','administrative',10578);
+INSERT INTO `ACL` VALUES (928,'ExpeditionStateType','*','READ','ALLOW','ROLE','employee',19294);
+INSERT INTO `ACL` VALUES (929,'ExpeditionState','addExpeditionState','WRITE','ALLOW','ROLE','delivery',19294);
+INSERT INTO `ACL` VALUES (930,'SupplierAccount','*','READ','ALLOW','ROLE','buyer',783);
+INSERT INTO `ACL` VALUES (931,'StockBought','*','READ','ALLOW','ROLE','buyer',10578);
+INSERT INTO `ACL` VALUES (932,'StockBought','*','WRITE','ALLOW','ROLE','buyer',10578);
+INSERT INTO `ACL` VALUES (933,'Buyer','*','READ','ALLOW','ROLE','buyer',10578);
+INSERT INTO `ACL` VALUES (934,'Ticket','setWeight','WRITE','ALLOW','ROLE','salesPerson',10578);
+INSERT INTO `ACL` VALUES (935,'BankEntity','*','WRITE','ALLOW','ROLE','financial',10578);
+INSERT INTO `ACL` VALUES (936,'Device','handleUser','*','ALLOW','ROLE','employee',10578);
+INSERT INTO `ACL` VALUES (937,'WorkerTimeControlMail','count','READ','ALLOW','ROLE','employee',10578);
+INSERT INTO `ACL` VALUES (938,'Worker','__get__mail','READ','ALLOW','ROLE','hr',10578);
+INSERT INTO `ACL` VALUES (939,'Machine','*','*','ALLOW','ROLE','productionBoss',10578);
+INSERT INTO `ACL` VALUES (940,'ItemTypeLog','find','READ','ALLOW','ROLE','employee',10578);
+INSERT INTO `ACL` VALUES (941,'Entry','buyLabel','READ','ALLOW','ROLE','employee',10578);
+INSERT INTO `ACL` VALUES (942,'Cmr','filter','READ','ALLOW','ROLE','production',10578);
+INSERT INTO `ACL` VALUES (943,'Cmr','downloadZip','READ','ALLOW','ROLE','production',10578);
+INSERT INTO `ACL` VALUES (944,'Cmr','print','READ','ALLOW','ROLE','production',10578);
+INSERT INTO `ACL` VALUES (945,'Collection','create','WRITE','ALLOW','ROLE','productionBoss',10578);
+INSERT INTO `ACL` VALUES (946,'Collection','upsert','WRITE','ALLOW','ROLE','productionBoss',10578);
+INSERT INTO `ACL` VALUES (947,'Collection','replaceById','WRITE','ALLOW','ROLE','productionBoss',10578);
+INSERT INTO `ACL` VALUES (948,'Collection','updateAll','WRITE','ALLOW','ROLE','productionBoss',10578);
+INSERT INTO `ACL` VALUES (949,'Collection','updateAttributes','WRITE','ALLOW','ROLE','productionBoss',10578);
+INSERT INTO `ACL` VALUES (950,'Collection','deleteById','WRITE','ALLOW','ROLE','productionBoss',10578);
+INSERT INTO `ACL` VALUES (951,'Collection','destroyAll','WRITE','ALLOW','ROLE','productionBoss',10578);
+INSERT INTO `ACL` VALUES (952,'Collection','destroyById','WRITE','ALLOW','ROLE','productionBoss',10578);
+INSERT INTO `ACL` VALUES (953,'RouteAction','find','READ','ALLOW','ROLE','delivery',10578);
+INSERT INTO `ACL` VALUES (954,'RouteComplement','find','READ','ALLOW','ROLE','delivery',10578);
+INSERT INTO `ACL` VALUES (955,'RouteComplement','create','WRITE','ALLOW','ROLE','delivery',10578);
+INSERT INTO `ACL` VALUES (956,'RouteComplement','deleteById','WRITE','ALLOW','ROLE','delivery',10578);
+INSERT INTO `ACL` VALUES (957,'SaleGroup','find','READ','ALLOW','ROLE','production',10578);
+INSERT INTO `ACL` VALUES (958,'Worker','canCreateAbsenceInPast','WRITE','ALLOW','ROLE','hr',10578);
+INSERT INTO `ACL` VALUES (959,'WorkerRelative','updateAttributes','*','ALLOW','ROLE','hr',10578);
+INSERT INTO `ACL` VALUES (960,'WorkerRelative','crud','WRITE','ALLOW','ROLE','hr',10578);
+INSERT INTO `ACL` VALUES (961,'WorkerRelative','findById','*','ALLOW','ROLE','hr',10578);
+INSERT INTO `ACL` VALUES (962,'WorkerRelative','find','*','ALLOW','ROLE','hr',10578);
+INSERT INTO `ACL` VALUES (963,'WorkerRelative','upsert','*','ALLOW','ROLE','hr',10578);
+INSERT INTO `ACL` VALUES (964,'WorkerRelative','filter','*','ALLOW','ROLE','hr',10578);
+INSERT INTO `ACL` VALUES (965,'WorkerIrpf','updateAttributes','*','ALLOW','ROLE','hr',10578);
+INSERT INTO `ACL` VALUES (966,'WorkerIrpf','crud','*','ALLOW','ROLE','hr',10578);
+INSERT INTO `ACL` VALUES (967,'WorkerIrpf','findById','*','ALLOW','ROLE','hr',10578);
+INSERT INTO `ACL` VALUES (968,'WorkerIrpf','find','*','ALLOW','ROLE','hr',10578);
+INSERT INTO `ACL` VALUES (969,'WorkerIrpf','upsert','*','ALLOW','ROLE','hr',10578);
+INSERT INTO `ACL` VALUES (970,'WorkerIrpf','filter','*','ALLOW','ROLE','hr',10578);
+INSERT INTO `ACL` VALUES (971,'DisabilityGrade','updateAttributes','*','ALLOW','ROLE','hr',10578);
+INSERT INTO `ACL` VALUES (972,'DisabilityGrade','crud','*','ALLOW','ROLE','hr',10578);
+INSERT INTO `ACL` VALUES (973,'DisabilityGrade','findById','*','ALLOW','ROLE','hr',10578);
+INSERT INTO `ACL` VALUES (974,'DisabilityGrade','find','*','ALLOW','ROLE','hr',10578);
+INSERT INTO `ACL` VALUES (975,'DisabilityGrade','upsert','*','ALLOW','ROLE','hr',10578);
+INSERT INTO `ACL` VALUES (976,'Entry','upsert','WRITE','ALLOW','ROLE','administrative',10578);
+INSERT INTO `ACL` VALUES (977,'Entry','updateAttributes','WRITE','ALLOW','ROLE','administrative',10578);
+INSERT INTO `ACL` VALUES (978,'Entry','isBooked','READ','ALLOW','ROLE','administrative',10578);
+INSERT INTO `ACL` VALUES (979,'Entry','findById','READ','ALLOW','ROLE','administrative',10578);
+INSERT INTO `ACL` VALUES (980,'Entry','find','READ','ALLOW','ROLE','administrative',10578);
+INSERT INTO `ACL` VALUES (981,'Entry','filter','READ','ALLOW','ROLE','administrative',10578);
+INSERT INTO `ACL` VALUES (982,'Entry','count','READ','ALLOW','ROLE','administrative',10578);
+INSERT INTO `ACL` VALUES (983,'Entry','getEntry','READ','ALLOW','ROLE','administrative',10578);
+INSERT INTO `ACL` VALUES (984,'Entry','getBuys','READ','ALLOW','ROLE','administrative',10578);
+INSERT INTO `ACL` VALUES (985,'Entry','findOne','READ','ALLOW','ROLE','administrative',10578);
+INSERT INTO `ACL` VALUES (986,'Entry','deleteBuys','WRITE','ALLOW','ROLE','administrative',10578);
+INSERT INTO `ACL` VALUES (987,'Entry','editLatestBuys','WRITE','ALLOW','ROLE','administrative',10578);
+INSERT INTO `ACL` VALUES (988,'Entry','importBuys','WRITE','ALLOW','ROLE','administrative',10578);
+INSERT INTO `ACL` VALUES (989,'Entry','importBuysPreview','READ','ALLOW','ROLE','administrative',10578);
+INSERT INTO `ACL` VALUES (990,'Entry','lastItemBuys','READ','ALLOW','ROLE','administrative',10578);
+INSERT INTO `ACL` VALUES (991,'Entry','latestBuysFilter','READ','ALLOW','ROLE','administrative',10578);
+INSERT INTO `ACL` VALUES (992,'Entry','upsert','WRITE','ALLOW','ROLE','buyer',10578);
+INSERT INTO `ACL` VALUES (993,'Entry','updateAttributes','WRITE','ALLOW','ROLE','buyer',10578);
+INSERT INTO `ACL` VALUES (994,'Entry','findById','READ','ALLOW','ROLE','buyer',10578);
+INSERT INTO `ACL` VALUES (995,'Entry','find','READ','ALLOW','ROLE','buyer',10578);
+INSERT INTO `ACL` VALUES (996,'Entry','filter','READ','ALLOW','ROLE','buyer',10578);
+INSERT INTO `ACL` VALUES (997,'Entry','count','READ','ALLOW','ROLE','buyer',10578);
+INSERT INTO `ACL` VALUES (998,'Entry','getEntry','READ','ALLOW','ROLE','buyer',10578);
+INSERT INTO `ACL` VALUES (999,'Entry','getBuys','READ','ALLOW','ROLE','buyer',10578);
+INSERT INTO `ACL` VALUES (1000,'Entry','findOne','READ','ALLOW','ROLE','buyer',10578);
+INSERT INTO `ACL` VALUES (1001,'Entry','deleteBuys','WRITE','ALLOW','ROLE','buyer',10578);
+INSERT INTO `ACL` VALUES (1002,'Entry','editLatestBuys','WRITE','ALLOW','ROLE','buyer',10578);
+INSERT INTO `ACL` VALUES (1003,'Entry','importBuys','WRITE','ALLOW','ROLE','buyer',10578);
+INSERT INTO `ACL` VALUES (1004,'Entry','importBuysPreview','READ','ALLOW','ROLE','buyer',10578);
+INSERT INTO `ACL` VALUES (1005,'Entry','lastItemBuys','READ','ALLOW','ROLE','buyer',10578);
+INSERT INTO `ACL` VALUES (1006,'Entry','latestBuysFilter','READ','ALLOW','ROLE','buyer',10578);
+INSERT INTO `ACL` VALUES (1007,'ItemShelving','getItemsByReviewOrder','READ','ALLOW','ROLE','production',19294);
+INSERT INTO `ACL` VALUES (1008,'Entry','buyLabelSupplier','READ','ALLOW','ROLE','employee',19295);
+INSERT INTO `ACL` VALUES (1009,'Entry','buyLabel','READ','ALLOW','ROLE','supplier',19295);
INSERT INTO `fieldAcl` VALUES (1,'Client','name','update','employee');
INSERT INTO `fieldAcl` VALUES (2,'Client','contact','update','employee');
@@ -2311,69 +2543,51 @@ INSERT INTO `cplusTaxBreak` VALUES (7,'E6 - Exenta por otros');
INSERT INTO `claimResponsible` VALUES (1,'Compradores',0,'buy');
INSERT INTO `claimResponsible` VALUES (2,'Proveedor',0,'sup');
-INSERT INTO `claimResponsible` VALUES (3,'Entradores',0,'ent');
INSERT INTO `claimResponsible` VALUES (4,'Camareros',0,'bar');
INSERT INTO `claimResponsible` VALUES (6,'Sacadores',0,'pic');
INSERT INTO `claimResponsible` VALUES (7,'Revisadores',0,'chk');
-INSERT INTO `claimResponsible` VALUES (8,'Calidad general',0,'qas');
INSERT INTO `claimResponsible` VALUES (9,'Encajadores',0,'pck');
INSERT INTO `claimResponsible` VALUES (10,'Clima',0,'wea');
INSERT INTO `claimResponsible` VALUES (11,'Comerciales',1,'com');
INSERT INTO `claimResponsible` VALUES (12,'Clientes',1,'cli');
-INSERT INTO `claimResponsible` VALUES (13,'Administración',0,'adm');
INSERT INTO `claimResponsible` VALUES (14,'Agencia',0,'age');
INSERT INTO `claimResponsible` VALUES (15,'Repartidores',0,'del');
INSERT INTO `claimResponsible` VALUES (16,'Informatica',0,'ite');
INSERT INTO `claimResponsible` VALUES (17,'Transp.origen',0,'tra');
INSERT INTO `claimResponsible` VALUES (18,'Confeccion',0,'con');
INSERT INTO `claimResponsible` VALUES (19,'OTROS',0,'oth');
-INSERT INTO `claimResponsible` VALUES (21,'Gerencia',0,'man');
INSERT INTO `claimResponsible` VALUES (22,'Paletizadores',0,'pal');
INSERT INTO `claimResponsible` VALUES (23,'Preparación Previa',0,'pre');
-INSERT INTO `claimResponsible` VALUES (24,'Almacén PCA',0,'war');
INSERT INTO `claimResponsible` VALUES (25,'Huelga',0,'str');
+INSERT INTO `claimResponsible` VALUES (27,'Prep. por caja',0,'pbb');
+INSERT INTO `claimResponsible` VALUES (45,'Negativo',0,'neg');
-INSERT INTO `claimReason` VALUES (1,'Prisas',0);
-INSERT INTO `claimReason` VALUES (2,'Novato',0);
INSERT INTO `claimReason` VALUES (3,'Exceso de confianza',0);
-INSERT INTO `claimReason` VALUES (4,'Exceso de celo',0);
-INSERT INTO `claimReason` VALUES (5,'Indiferencia',0);
INSERT INTO `claimReason` VALUES (6,'Extraviado o Hurto',0);
INSERT INTO `claimReason` VALUES (7,'Incompetencia',0);
-INSERT INTO `claimReason` VALUES (8,'Ubicación erronea',0);
-INSERT INTO `claimReason` VALUES (9,'Dat.Inctos/Pak.conf',0);
-INSERT INTO `claimReason` VALUES (10,'Datos duplicados',0);
-INSERT INTO `claimReason` VALUES (11,'Fallo stock',0);
-INSERT INTO `claimReason` VALUES (12,'Innovación',0);
INSERT INTO `claimReason` VALUES (13,'Distracción',1);
-INSERT INTO `claimReason` VALUES (15,'Portes indebidos',0);
INSERT INTO `claimReason` VALUES (16,'Baja calidad',0);
INSERT INTO `claimReason` VALUES (17,'Defectuoso',0);
-INSERT INTO `claimReason` VALUES (19,'Endiñado',0);
INSERT INTO `claimReason` VALUES (20,'Calor',0);
INSERT INTO `claimReason` VALUES (21,'Frio',0);
INSERT INTO `claimReason` VALUES (22,'Cambiado',0);
-INSERT INTO `claimReason` VALUES (24,'Cansancio',1);
INSERT INTO `claimReason` VALUES (25,'Mal etiquetado',1);
-INSERT INTO `claimReason` VALUES (26,'Cantidad malentendido',0);
-INSERT INTO `claimReason` VALUES (30,'No revisado',1);
INSERT INTO `claimReason` VALUES (34,'Error fotografia',0);
INSERT INTO `claimReason` VALUES (40,'Fallo Personal VN',0);
-INSERT INTO `claimReason` VALUES (41,'Fallo Personal Cliente',0);
INSERT INTO `claimReason` VALUES (42,'Otros',0);
INSERT INTO `claimReason` VALUES (43,'Precio alto',0);
-INSERT INTO `claimReason` VALUES (44,'Abuso de confianza',0);
INSERT INTO `claimReason` VALUES (45,'Retraso Agencia',0);
INSERT INTO `claimReason` VALUES (46,'Delicado',0);
-INSERT INTO `claimReason` VALUES (47,'Seco',0);
INSERT INTO `claimReason` VALUES (48,'Retraso Reparto',0);
INSERT INTO `claimReason` VALUES (49,'Mal Embalado',0);
INSERT INTO `claimReason` VALUES (50,'Tumbado',0);
INSERT INTO `claimReason` VALUES (51,'Enfermo/Plaga',0);
INSERT INTO `claimReason` VALUES (52,'Mala gestión comercial',0);
INSERT INTO `claimReason` VALUES (53,'Mala gestión comprador',0);
-INSERT INTO `claimReason` VALUES (54,'A2',0);
INSERT INTO `claimReason` VALUES (55,'Entrega 48h o más',0);
+INSERT INTO `claimReason` VALUES (56,'Error cliente',0);
+INSERT INTO `claimReason` VALUES (57,'A2/B1',0);
+INSERT INTO `claimReason` VALUES (58,'Seguro',0);
INSERT INTO `claimRedelivery` VALUES (1,'Cliente');
INSERT INTO `claimRedelivery` VALUES (2,'No dev./No especif.');
@@ -2381,8 +2595,8 @@ INSERT INTO `claimRedelivery` VALUES (3,'Reparto');
INSERT INTO `claimRedelivery` VALUES (4,'Agencia');
INSERT INTO `claimRedelivery` VALUES (5,'Tour');
INSERT INTO `claimRedelivery` VALUES (6,'Fuera Peninsula');
+INSERT INTO `claimRedelivery` VALUES (7,'Francia');
-INSERT INTO `claimResult` VALUES (1,'Otros daños');
INSERT INTO `claimResult` VALUES (2,'Roces');
INSERT INTO `claimResult` VALUES (3,'Humedad');
INSERT INTO `claimResult` VALUES (4,'Deshidratacion');
@@ -2391,26 +2605,20 @@ INSERT INTO `claimResult` VALUES (6,'Incompleto (Faltas)');
INSERT INTO `claimResult` VALUES (7,'Error packing');
INSERT INTO `claimResult` VALUES (8,'Error color');
INSERT INTO `claimResult` VALUES (9,'Error medida');
-INSERT INTO `claimResult` VALUES (10,'Error origen');
INSERT INTO `claimResult` VALUES (11,'Envejecido');
-INSERT INTO `claimResult` VALUES (12,'Venta Perdida');
INSERT INTO `claimResult` VALUES (13,'Duplicacion');
INSERT INTO `claimResult` VALUES (14,'Rechazado');
INSERT INTO `claimResult` VALUES (15,'Rotura');
INSERT INTO `claimResult` VALUES (16,'Deterioro/Estropeado');
INSERT INTO `claimResult` VALUES (17,'Podrido');
-INSERT INTO `claimResult` VALUES (18,'Baboso');
-INSERT INTO `claimResult` VALUES (19,'Cocido');
INSERT INTO `claimResult` VALUES (20,'Congelado');
INSERT INTO `claimResult` VALUES (21,'Machacado');
-INSERT INTO `claimResult` VALUES (22,'Error precio');
INSERT INTO `claimResult` VALUES (23,'Manchado');
INSERT INTO `claimResult` VALUES (24,'No entregado');
-INSERT INTO `claimResult` VALUES (25,'Cobro indebido');
INSERT INTO `claimResult` VALUES (26,'Decepcion/Esperaba mas');
INSERT INTO `claimResult` VALUES (27,'Otros');
INSERT INTO `claimResult` VALUES (28,'Baboso/Cocido');
-INSERT INTO `claimResult` VALUES (29,'Video Camara');
+INSERT INTO `claimResult` VALUES (29,'Videocámaras');
INSERT INTO `component` VALUES (10,'Precios Especiales',4,NULL,NULL,1,'specialPrices',0);
INSERT INTO `component` VALUES (14,'porte extra por dia semana',6,NULL,NULL,1,'extraCostPerWeekDay',0);
@@ -2437,6 +2645,7 @@ INSERT INTO `component` VALUES (45,'maná reclamacion',7,4,NULL,0,'manaClaim',0)
INSERT INTO `component` VALUES (46,'recargo a particular',2,NULL,0.25,0,'individual',0);
INSERT INTO `component` VALUES (48,'fusión de lineas',4,NULL,NULL,1,'lineFusion',0);
INSERT INTO `component` VALUES (49,'sustitución',4,NULL,NULL,1,'substitution',0);
+INSERT INTO `component` VALUES (50,'bonus',4,NULL,NULL,1,'bonus',0);
INSERT INTO `componentType` VALUES (1,'cost','coste',1,0);
INSERT INTO `componentType` VALUES (2,NULL,'com ventas',1,1);
@@ -2457,63 +2666,71 @@ INSERT INTO `continent` VALUES (3,'África','AF');
INSERT INTO `continent` VALUES (4,'Europa','EU');
INSERT INTO `continent` VALUES (5,'Oceanía','OC');
-INSERT INTO `department` VALUES (1,'VN','VERDNATURA',1,114,763,0,0,0,0,26,NULL,'/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (1,'VN','VERDNATURA',1,130,763,0,0,0,0,26,NULL,'/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
INSERT INTO `department` VALUES (22,'shopping','COMPRAS',2,5,NULL,72,0,0,1,1,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
INSERT INTO `department` VALUES (23,'CMA','CAMARA',15,16,NULL,72,1,1,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,1,NULL,NULL,NULL,'PREVIOUS');
-INSERT INTO `department` VALUES (31,'it','INFORMATICA',6,7,NULL,72,0,0,1,0,1,'/1/','informatica-cau',1,NULL,1,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (31,'it','INFORMATICA',6,7,NULL,72,0,0,1,0,1,'/1/','informatica-cau',1,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
INSERT INTO `department` VALUES (34,'accounting','CONTABILIDAD',8,9,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (35,'finance','FINANZAS',10,11,NULL,0,0,0,1,0,1,'/1/',NULL,1,'begonya@verdnatura.es',1,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (35,'finance','FINANZAS',10,11,NULL,0,0,0,1,0,1,'/1/',NULL,1,'begonya@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL);
INSERT INTO `department` VALUES (36,'labor','LABORAL',12,13,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL);
INSERT INTO `department` VALUES (37,'PROD','PRODUCCION',14,37,NULL,72,1,1,1,11,1,'/1/',NULL,0,NULL,0,1,1,1,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (38,'picking','SACADO',17,18,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,'ON_PREPARATION');
+INSERT INTO `department` VALUES (38,'picking','SACADO',17,18,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,0,1,NULL,NULL,NULL,'ON_PREPARATION');
INSERT INTO `department` VALUES (39,'packing','ENCAJADO',19,20,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,'PACKING');
INSERT INTO `department` VALUES (41,'administration','ADMINISTRACION',38,39,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (43,'VT','VENTAS',40,73,NULL,0,0,0,1,16,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (44,'management','GERENCIA',74,75,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (45,'logistic','LOGISTICA',76,77,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (46,'delivery','REPARTO',78,79,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,'DELIVERY');
-INSERT INTO `department` VALUES (48,'storage','ALMACENAJE',80,81,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,'STORAGE');
-INSERT INTO `department` VALUES (49,NULL,'PROPIEDAD',82,83,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (52,NULL,'CARGA AEREA',84,85,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (53,'marketing','MARKETING Y COMUNICACIÓN',41,42,NULL,72,0,0,2,0,43,'/1/43/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (54,NULL,'ORNAMENTALES',86,87,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (43,'VT','VENTAS',40,89,NULL,0,0,0,1,24,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (44,'management','GERENCIA',90,91,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (45,'logistic','LOGISTICA',92,93,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (46,'delivery','REPARTO',94,95,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,'DELIVERY');
+INSERT INTO `department` VALUES (48,'storage','ALMACENAJE',96,97,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,'STORAGE');
+INSERT INTO `department` VALUES (49,NULL,'PROPIEDAD',98,99,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (52,NULL,'CARGA AEREA',100,101,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (53,'marketing','MARKETING Y COMUNICACIÓN',41,42,NULL,72,0,0,2,0,43,'/1/43/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (54,NULL,'ORNAMENTALES',102,103,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
INSERT INTO `department` VALUES (55,NULL,'TALLER NATURAL',21,22,14548,72,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,0,1118,NULL,NULL,NULL);
INSERT INTO `department` VALUES (56,NULL,'TALLER ARTIFICIAL',23,24,8470,72,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,0,1927,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (58,'CMP','CAMPOS',88,91,NULL,72,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,'FIELD');
-INSERT INTO `department` VALUES (59,'maintenance','MANTENIMIENTO',92,93,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (60,'claims','RECLAMACIONES',43,44,NULL,72,0,0,2,0,43,'/1/43/',NULL,0,NULL,1,1,0,0,NULL,NULL,NULL,'CLAIM');
-INSERT INTO `department` VALUES (61,NULL,'VNH',94,97,NULL,73,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (66,NULL,'VERDNAMADRID',98,99,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (58,'CMP','CAMPOS',104,107,NULL,72,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,'FIELD');
+INSERT INTO `department` VALUES (59,'maintenance','MANTENIMIENTO',108,109,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (60,'claims','RECLAMACIONES',43,44,NULL,72,0,0,2,0,43,'/1/43/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,'CLAIM');
+INSERT INTO `department` VALUES (61,NULL,'VNH',110,113,NULL,73,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (66,NULL,'VERDNAMADRID',114,115,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
INSERT INTO `department` VALUES (68,NULL,'COMPLEMENTOS',25,26,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (69,NULL,'VERDNABARNA',100,101,NULL,74,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (80,'spainTeam5','EQUIPO ESPAÑA 5',45,46,4250,0,0,0,2,0,43,'/1/43/','es5_equipo',1,'es5@verdnatura.es',0,0,0,0,NULL,NULL,'5300',NULL);
-INSERT INTO `department` VALUES (86,NULL,'LIMPIEZA',102,103,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (89,NULL,'COORDINACION',104,105,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (90,NULL,'TRAILER',95,96,NULL,0,0,0,2,0,61,'/1/61/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (69,NULL,'VERDNABARNA',116,117,NULL,74,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (80,'spainTeam5','EQUIPO ESPAÑA 5',45,46,4250,0,0,0,2,0,43,'/1/43/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (86,NULL,'LIMPIEZA',118,119,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (89,NULL,'COORDINACION',120,121,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (90,NULL,'TRAILER',111,112,NULL,0,0,0,2,0,61,'/1/61/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
INSERT INTO `department` VALUES (91,'artificial','ARTIFICIAL',27,28,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,'PREVIOUS');
INSERT INTO `department` VALUES (92,NULL,'EQUIPO SILVERIO',47,48,1203,0,0,0,2,0,43,'/1/43/','sdc_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (94,'spainTeam2','EQUIPO ESPAÑA 2',49,50,3797,0,0,0,2,0,43,'/1/43/','es2_equipo',1,'es2@verdnatura.es',0,0,0,0,NULL,NULL,'5100',NULL);
-INSERT INTO `department` VALUES (95,'spainTeam1','EQUIPO ESPAÑA 1',51,52,24065,0,0,0,2,0,43,'/1/43/','es1_equipo',1,'es1@verdnatura.es',0,0,0,0,NULL,NULL,'5000',NULL);
+INSERT INTO `department` VALUES (94,'spainTeam2','EQUIPO ESPAÑA 2',49,50,3797,0,0,0,2,0,43,'/1/43/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (95,'spainTeam1','EQUIPO ESPAÑA 1',51,52,24065,0,0,0,2,0,43,'/1/43/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
INSERT INTO `department` VALUES (96,NULL,'EQUIPO C LOPEZ',53,54,4661,0,0,0,2,0,43,'/1/43/','cla_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL);
INSERT INTO `department` VALUES (115,NULL,'EQUIPO CLAUDI',55,56,3810,0,0,0,2,0,43,'/1/43/','csr_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL);
INSERT INTO `department` VALUES (123,NULL,'EQUIPO ELENA BASCUÑANA',57,58,7102,0,0,0,2,0,43,'/1/43/','ebt_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (124,NULL,'CONTROL INTERNO',106,107,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,1,0,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (125,'spainTeam3','EQUIPO ESPAÑA 3',59,60,1118,0,0,0,2,0,43,'/1/43/','es3_equipo',1,'es3@verdnatura.es',0,0,0,0,NULL,NULL,'5200',NULL);
+INSERT INTO `department` VALUES (124,NULL,'CONTROL INTERNO',122,123,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (125,'spainTeam3','EQUIPO ESPAÑA 3',59,60,1118,0,0,0,2,0,43,'/1/43/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
INSERT INTO `department` VALUES (126,NULL,'PRESERVADO',29,30,NULL,0,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,0,NULL,NULL,NULL,NULL);
INSERT INTO `department` VALUES (128,NULL,'PALETIZADO',31,32,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,'PALLETIZING');
INSERT INTO `department` VALUES (130,NULL,'REVISION',33,34,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,'ON_CHECKING');
-INSERT INTO `department` VALUES (131,'greenhouse','INVERNADERO',89,90,NULL,0,0,0,2,0,58,'/1/58/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (131,'greenhouse','INVERNADERO',105,106,NULL,0,0,0,2,0,58,'/1/58/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL);
INSERT INTO `department` VALUES (132,NULL,'EQUIPO DC',61,62,1731,0,0,0,2,0,43,'/1/43/','dc_equipo',1,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (133,'franceTeam','EQUIPO FRANCIA',63,64,1731,72,0,0,2,0,43,'/1/43/','fr_equipo',1,'gestionfrancia@verdnatura.es',0,0,0,0,NULL,NULL,'3300',NULL);
-INSERT INTO `department` VALUES (134,'portugalTeam','EQUIPO PORTUGAL',65,66,6264,0,0,0,2,0,43,'/1/43/','pt_equipo',1,'portugal@verdnatura.es',0,0,0,0,NULL,NULL,'3500',NULL);
-INSERT INTO `department` VALUES (135,'routers','ENRUTADORES',108,109,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (136,'heavyVehicles','VEHICULOS PESADOS',110,111,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (137,'sorter','SORTER',112,113,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (139,'spainTeam4','EQUIPO ESPAÑA 4',67,68,3803,0,0,0,2,0,43,'/1/43/','es4_equipo',1,'es4@verdnatura.es',0,0,0,0,NULL,NULL,'5400',NULL);
-INSERT INTO `department` VALUES (140,'hollandTeam','EQUIPO HOLANDA',69,70,NULL,0,0,0,2,0,43,'/1/43/','nl_equipo',1,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (141,NULL,'PREVIA',35,36,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (133,'franceTeamManagement','EQUIPO GESTIÓN FRANCIA',63,64,9751,72,0,0,2,0,43,'/1/43/','fr_equipo',1,'gestionfrancia@verdnatura.es',0,0,0,0,NULL,NULL,'3300',NULL);
+INSERT INTO `department` VALUES (134,'portugalTeam','EQUIPO PORTUGAL',65,66,8964,0,0,0,2,0,43,'/1/43/','pt_equipo',1,'portugal@verdnatura.es',0,0,0,0,NULL,NULL,'3500',NULL);
+INSERT INTO `department` VALUES (135,'routers','ENRUTADORES',124,125,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (136,'heavyVehicles','VEHICULOS PESADOS',126,127,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (137,'sorter','SORTER',128,129,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (139,'spainTeam4','EQUIPO ESPAÑA 4',67,68,3803,0,0,0,2,0,43,'/1/43/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (140,'internationalTeam','EQUIPO INTERNACIONAL',69,70,24065,0,0,0,2,0,43,'/1/43/','int_equipo',1,'international@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL);
+INSERT INTO `department` VALUES (141,NULL,'PREVIA',35,36,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,'PREVIOUS');
INSERT INTO `department` VALUES (146,NULL,'VERDNACOLOMBIA',3,4,NULL,72,0,0,2,0,22,'/1/22/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL);
-INSERT INTO `department` VALUES (147,'spainTeamAsia','EQUIPO ESPAÑA ASIA',71,72,40214,0,0,0,2,0,43,'/1/43/','esA_equipo',0,'esA@verdnatura.es',0,0,0,0,NULL,NULL,'5500',NULL);
+INSERT INTO `department` VALUES (147,'spainTeamAsia','EQUIPO ESPAÑA ASIA',71,72,40214,0,0,0,2,0,43,'/1/43/','esA_equipo',1,'esA@verdnatura.es',0,0,0,0,NULL,NULL,'5500',NULL);
+INSERT INTO `department` VALUES (148,'franceTeamCatchment','EQUIPO CAPTACIÓN FRANCIA',73,74,25178,0,0,0,2,0,43,'/1/43/',NULL,1,NULL,0,0,0,0,NULL,NULL,'6000',NULL);
+INSERT INTO `department` VALUES (149,'spainTeamCatchment','EQUIPO ESPAÑA CAPTACIÓN',75,76,1203,0,0,0,2,0,43,'/1/43/','es_captacion_equipo',1,'es_captacion@verdnatura.es',0,0,0,0,NULL,NULL,'5700',NULL);
+INSERT INTO `department` VALUES (150,'spainTeamLevanteIslands','EQUIPO ESPAÑA LEVANTE/ISLAS',77,78,1118,0,0,0,2,0,43,'/1/43/','es_levanteislas_equipo',1,'levanteislas.verdnatura@gmail.com',0,0,0,0,NULL,NULL,'5000',NULL);
+INSERT INTO `department` VALUES (151,'spainTeamNorthwest','EQUIPO ESPAÑA NOROESTE',79,80,7102,0,0,0,2,0,43,'/1/43/','es_noroeste_equipo',1,'noroeste.verdnatura@gmail.com',0,0,0,0,NULL,NULL,'5300',NULL);
+INSERT INTO `department` VALUES (152,'spainTeamNortheast','EQUIPO ESPAÑA NORESTE',81,82,1118,0,0,0,2,0,43,'/1/43/','es_noreste_equipo',1,'noreste.verdnatura@gmail.com',0,0,0,0,NULL,NULL,'5200',NULL);
+INSERT INTO `department` VALUES (153,'spainTeamSouth','EQUIPO ESPAÑA SUR',83,84,36578,0,0,0,2,0,43,'/1/43/','es_sur_equipo',1,'sur.verdnatura@gmail.com',0,0,0,0,NULL,NULL,'5400',NULL);
+INSERT INTO `department` VALUES (154,'spainTeamCenter','EQUIPO ESPAÑA CENTRO',85,86,4661,0,0,0,2,0,43,'/1/43/','es_centro_equipo',1,'centro.verdnatura@gmail.com',0,0,0,0,NULL,NULL,'5100',NULL);
+INSERT INTO `department` VALUES (155,'spainTeamVip','EQUIPO ESPAÑA VIP',87,88,5432,0,0,0,2,0,43,'/1/43/','es_vip_equipo',1,'vip.verdnatura@gmail.com',0,0,0,0,NULL,NULL,'5600',NULL);
INSERT INTO `docuware` VALUES (1,'deliveryNote','Albaranes cliente','find','find','N__ALBAR_N',NULL);
INSERT INTO `docuware` VALUES (2,'deliveryNote','Albaranes cliente','store','Archivar','N__ALBAR_N',NULL);
@@ -2568,7 +2785,7 @@ INSERT INTO `sample` VALUES (16,'letter-debtor-nd','Aviso reiterado por saldo de
INSERT INTO `sample` VALUES (17,'client-lcr','Email de solicitud de datos bancarios LCR',0,1,1,0,NULL);
INSERT INTO `sample` VALUES (18,'client-debt-statement','Extracto del cliente',1,0,1,1,'Clients');
INSERT INTO `sample` VALUES (19,'credit-request','Solicitud de crédito',1,1,1,0,'Clients');
-INSERT INTO `sample` VALUES (20,'incoterms-authorization','Autorización de incoterms',1,1,1,0,'Clients');
+INSERT INTO `sample` VALUES (20,'incoterms-authorization','Entregas intracomunitarias recogidas por el cliente',1,1,1,0,'Clients');
INSERT INTO `siiTrascendencyInvoiceIn` VALUES (1,'Operación de régimen general');
INSERT INTO `siiTrascendencyInvoiceIn` VALUES (2,'Operaciones por las que los empresarios satisfacen compensaciones REAGYP');
@@ -2605,50 +2822,58 @@ INSERT INTO `siiTypeInvoiceOut` VALUES (7,'R3','Factura rectificativa (Art. 80.4
INSERT INTO `siiTypeInvoiceOut` VALUES (8,'R4','Factura rectificativa (Resto)');
INSERT INTO `siiTypeInvoiceOut` VALUES (9,'R5','Factura rectificativa en facturas simplificadas');
-INSERT INTO `state` VALUES (1,'Arreglar',2,0,'FIXING',NULL,1,0,0,0,0,0,0,4,1,'alert');
-INSERT INTO `state` VALUES (2,'Libre',2,0,'FREE',NULL,2,0,0,0,0,0,0,4,1,'notice');
-INSERT INTO `state` VALUES (3,'OK',3,0,'OK',3,28,1,0,1,0,1,1,3,0,'success');
-INSERT INTO `state` VALUES (4,'Impreso',4,0,'PRINTED',2,29,1,0,1,0,0,1,2,0,'success');
-INSERT INTO `state` VALUES (5,'Preparación',6,2,'ON_PREPARATION',7,14,0,0,0,2,0,0,2,0,'warning');
-INSERT INTO `state` VALUES (6,'En Revisión',7,2,'ON_CHECKING',NULL,6,0,1,0,3,0,0,1,0,'warning');
-INSERT INTO `state` VALUES (7,'Sin Acabar',1,0,'NOT_READY',NULL,7,0,0,0,0,0,0,4,1,'alert');
-INSERT INTO `state` VALUES (8,'Revisado',8,2,'CHECKED',NULL,8,0,1,0,3,0,0,1,0,'warning');
-INSERT INTO `state` VALUES (9,'Encajando',9,3,'PACKING',NULL,9,0,1,0,0,0,0,1,0,NULL);
-INSERT INTO `state` VALUES (10,'Encajado',10,3,'PACKED',NULL,10,0,1,0,0,0,0,0,0,NULL);
-INSERT INTO `state` VALUES (11,'Facturado',0,4,'INVOICED',NULL,11,0,1,0,0,0,0,0,0,NULL);
-INSERT INTO `state` VALUES (12,'Bloqueado',0,0,'BLOCKED',NULL,12,0,0,0,0,0,0,4,1,'alert');
-INSERT INTO `state` VALUES (13,'En Reparto',11,4,'ON_DELIVERY',NULL,13,0,1,0,0,0,0,0,0,NULL);
-INSERT INTO `state` VALUES (14,'Preparado',6,2,'PREPARED',NULL,14,0,1,0,2,0,0,1,0,'warning');
-INSERT INTO `state` VALUES (15,'Pte Recogida',12,4,'WAITING_FOR_PICKUP',NULL,15,0,1,0,0,0,0,0,0,NULL);
-INSERT INTO `state` VALUES (16,'Entregado',13,4,'DELIVERED',NULL,16,0,1,0,0,0,0,0,0,NULL);
-INSERT INTO `state` VALUES (20,'Asignado',4,0,'PICKER_DESIGNED',NULL,20,1,0,0,0,0,0,2,0,'success');
-INSERT INTO `state` VALUES (21,'Retornado',4,2,'PRINTED_BACK',6,21,0,0,0,0,0,0,2,0,'success');
-INSERT INTO `state` VALUES (22,'Pte. Ampliar',2,0,'EXPANDABLE',NULL,22,0,0,0,0,0,0,4,1,'alert');
-INSERT INTO `state` VALUES (23,'URGENTE',5,2,'LAST_CALL',NULL,23,1,0,1,0,0,0,4,1,'success');
-INSERT INTO `state` VALUES (24,'Encadenado',4,0,'CHAINED',4,24,0,0,0,0,0,0,3,1,'success');
-INSERT INTO `state` VALUES (25,'Embarcando',3,0,'BOARDING',5,25,1,0,0,0,0,0,3,0,'alert');
-INSERT INTO `state` VALUES (26,'Prep Previa',5,0,'PREVIOUS_PREPARATION',1,28,1,0,0,1,0,0,2,0,'warning');
-INSERT INTO `state` VALUES (27,'Prep Asistida',5,2,'ASSISTED_PREPARATION',7,27,0,0,0,0,0,0,2,0,'success');
-INSERT INTO `state` VALUES (28,'Previa OK',3,0,'OK PREVIOUS',3,28,1,0,1,1,1,1,3,0,'warning');
-INSERT INTO `state` VALUES (29,'Previa Impreso',4,0,'PRINTED PREVIOUS',2,29,1,0,1,0,0,1,2,0,'success');
-INSERT INTO `state` VALUES (30,'Embarcado',4,2,'BOARD',5,30,0,0,0,2,0,0,3,0,'success');
-INSERT INTO `state` VALUES (31,'Polizon Impreso',4,2,'PRINTED STOWAWAY',2,29,1,0,1,0,0,1,2,0,'success');
-INSERT INTO `state` VALUES (32,'Polizon OK',3,2,'OK STOWAWAY',3,31,1,0,0,1,1,1,3,0,'warning');
-INSERT INTO `state` VALUES (33,'Auto_Impreso',4,0,'PRINTED_AUTO',2,29,1,0,1,0,0,1,2,0,'success');
-INSERT INTO `state` VALUES (34,'Pte Pago',3,0,'WAITING_FOR_PAYMENT',NULL,34,0,0,0,0,0,0,4,1,'alert');
-INSERT INTO `state` VALUES (35,'Semi-Encajado',9,3,'HALF_PACKED',NULL,10,0,1,0,0,0,0,1,0,NULL);
-INSERT INTO `state` VALUES (36,'Previa Revisando',3,0,'PREVIOUS_CONTROL',2,37,1,0,0,4,0,1,2,0,'warning');
-INSERT INTO `state` VALUES (37,'Previa Revisado',3,0,'PREVIOUS_CONTROLLED',2,29,1,0,1,0,0,1,2,0,'warning');
-INSERT INTO `state` VALUES (38,'Prep Cámara',6,2,'COOLER_PREPARATION',7,14,0,0,0,2,0,0,2,0,'warning');
-INSERT INTO `state` VALUES (41,'Prep Parcial',6,2,'PARTIAL_PREPARATION',7,14,0,0,0,2,0,0,2,0,'warning');
-INSERT INTO `state` VALUES (42,'Entregado en parte',13,3,'PARTIAL_DELIVERED',NULL,16,0,1,0,0,0,0,0,0,NULL);
-INSERT INTO `state` VALUES (43,'Preparación por caja',6,2,'BOX_PICKING',7,42,0,0,0,2,0,0,2,0,'warning');
+INSERT INTO `state` VALUES (1,'Arreglar',2,0,'FIXING',1,0,0,0,0,0,0,4,1,'alert');
+INSERT INTO `state` VALUES (2,'Libre',2,0,'FREE',2,0,0,0,0,0,0,4,1,'notice');
+INSERT INTO `state` VALUES (3,'OK',3,0,'OK',28,1,0,1,0,1,1,3,0,'success');
+INSERT INTO `state` VALUES (4,'Impreso',4,0,'PRINTED',29,1,0,1,0,0,1,2,0,'success');
+INSERT INTO `state` VALUES (5,'Preparación',6,2,'ON_PREPARATION',14,0,0,0,2,0,0,2,0,'warning');
+INSERT INTO `state` VALUES (6,'En Revisión',7,2,'ON_CHECKING',6,0,1,0,3,0,0,1,0,'warning');
+INSERT INTO `state` VALUES (7,'Sin Acabar',1,0,'NOT_READY',7,0,0,0,0,0,0,4,1,'alert');
+INSERT INTO `state` VALUES (8,'Revisado',8,2,'CHECKED',8,0,1,0,3,0,0,1,0,'warning');
+INSERT INTO `state` VALUES (9,'Encajando',9,3,'PACKING',9,0,1,0,0,0,0,1,0,NULL);
+INSERT INTO `state` VALUES (10,'Encajado',10,3,'PACKED',10,0,1,0,0,0,0,0,0,NULL);
+INSERT INTO `state` VALUES (12,'Bloqueado',0,0,'BLOCKED',12,0,0,0,0,0,0,4,1,'alert');
+INSERT INTO `state` VALUES (13,'En Reparto',11,4,'ON_DELIVERY',13,0,1,0,0,0,0,0,0,NULL);
+INSERT INTO `state` VALUES (14,'Preparado',6,2,'PREPARED',14,0,1,0,2,0,0,1,0,'warning');
+INSERT INTO `state` VALUES (15,'Pte Recogida',12,4,'WAITING_FOR_PICKUP',15,0,1,0,0,0,0,0,0,NULL);
+INSERT INTO `state` VALUES (16,'Entregado',13,4,'DELIVERED',16,0,1,0,0,0,0,0,0,NULL);
+INSERT INTO `state` VALUES (20,'Asignado',4,0,'PICKER_DESIGNED',20,1,0,0,0,0,0,2,0,'success');
+INSERT INTO `state` VALUES (21,'Retornado',4,2,'PRINTED_BACK',21,0,0,0,0,0,0,2,0,'success');
+INSERT INTO `state` VALUES (22,'Pte. Ampliar',2,0,'EXPANDABLE',22,0,0,0,0,0,0,4,1,'alert');
+INSERT INTO `state` VALUES (23,'URGENTE',5,2,'LAST_CALL',23,1,0,1,0,0,0,4,1,'success');
+INSERT INTO `state` VALUES (24,'Encadenado',4,0,'CHAINED',24,0,0,0,0,0,0,3,1,'success');
+INSERT INTO `state` VALUES (25,'Embarcando',3,0,'BOARDING',25,1,0,0,0,0,0,3,0,'alert');
+INSERT INTO `state` VALUES (26,'Prep Previa',5,0,'PREVIOUS_PREPARATION',28,1,0,0,1,0,0,2,0,'warning');
+INSERT INTO `state` VALUES (28,'Previa OK',3,0,'OK PREVIOUS',28,1,0,1,1,1,1,3,0,'warning');
+INSERT INTO `state` VALUES (29,'Previa Impreso',4,0,'PRINTED PREVIOUS',29,1,0,1,0,0,1,2,0,'success');
+INSERT INTO `state` VALUES (31,'Polizon Impreso',4,2,'PRINTED STOWAWAY',29,1,0,1,0,0,1,2,0,'success');
+INSERT INTO `state` VALUES (33,'Auto_Impreso',4,0,'PRINTED_AUTO',29,1,0,1,0,0,1,2,0,'success');
+INSERT INTO `state` VALUES (34,'Pte Pago',3,0,'WAITING_FOR_PAYMENT',34,0,0,0,0,0,0,4,1,'alert');
+INSERT INTO `state` VALUES (35,'Semi-Encajado',9,3,'HALF_PACKED',10,0,1,0,0,0,0,1,0,NULL);
+INSERT INTO `state` VALUES (36,'Previa Revisando',3,0,'PREVIOUS_CONTROL',37,1,0,0,4,0,1,2,0,'warning');
+INSERT INTO `state` VALUES (37,'Previa Revisado',3,0,'PREVIOUS_CONTROLLED',29,1,0,1,0,0,1,2,0,'warning');
+INSERT INTO `state` VALUES (38,'Prep Cámara',6,2,'COOLER_PREPARATION',14,0,0,0,2,0,0,2,0,'warning');
+INSERT INTO `state` VALUES (42,'Entregado en parte',13,3,'PARTIAL_DELIVERED',16,0,1,0,0,0,0,0,0,NULL);
+INSERT INTO `state` VALUES (43,'Preparación por caja',6,2,'BOX_PICKING',42,0,0,0,2,0,0,2,0,'warning');
INSERT INTO `ticketUpdateAction` VALUES (1,'Cambiar los precios en el ticket','renewPrices');
INSERT INTO `ticketUpdateAction` VALUES (2,'Convertir en maná','mana');
+INSERT INTO `ticketCanAdvanceConfig` VALUES (1,5);
+
INSERT INTO `volumeConfig` VALUES (2.67,1.60,0.8,150,0.30,120,57,2.0,50,200,10,167.0);
+INSERT INTO `workerActivityType` VALUES ('CLAIM','RECLAMACIONES');
+INSERT INTO `workerActivityType` VALUES ('DELIVERY','REPARTO');
+INSERT INTO `workerActivityType` VALUES ('FIELD','CAMPOS');
+INSERT INTO `workerActivityType` VALUES ('ON_CHECKING','REVISION');
+INSERT INTO `workerActivityType` VALUES ('ON_PREPARATION','SACADO');
+INSERT INTO `workerActivityType` VALUES ('PACKING','ENCAJADO');
+INSERT INTO `workerActivityType` VALUES ('PALLETIZING','PALETIZADO');
+INSERT INTO `workerActivityType` VALUES ('PREVIOUS','ARTIFICIAL-CÁMARA');
+INSERT INTO `workerActivityType` VALUES ('STOP','PARADA');
+INSERT INTO `workerActivityType` VALUES ('STORAGE','ALMACENAJE');
+
INSERT INTO `workCenter` VALUES (1,'Silla',20,859,1,'Av espioca 100',552703,NULL);
INSERT INTO `workCenter` VALUES (2,'Mercaflor',19,NULL,NULL,NULL,NULL,NULL);
INSERT INTO `workCenter` VALUES (3,'Marjales',26,20008,NULL,NULL,NULL,NULL);
@@ -2659,6 +2884,7 @@ INSERT INTO `workCenter` VALUES (7,'Tenerife',NULL,NULL,NULL,NULL,NULL,NULL);
INSERT INTO `workCenter` VALUES (8,'Silla-Agrario',26,NULL,NULL,NULL,NULL,NULL);
INSERT INTO `workCenter` VALUES (9,'Algemesi',20,1354,60,'Fenollars, 2',523549,NULL);
INSERT INTO `workCenter` VALUES (10,'Rubi',88,NULL,84,'Av. de la Llana, 131',549722,NULL);
+INSERT INTO `workCenter` VALUES (11,'Colombia',NULL,NULL,NULL,NULL,NULL,NULL);
INSERT INTO `workerTimeControlError` VALUES (1,'IS_NOT_ALLOWED_FUTURE','No se permite fichar a futuro');
INSERT INTO `workerTimeControlError` VALUES (2,'INACTIVE_BUSINESS','No hay un contrato en vigor');
@@ -2977,6 +3203,7 @@ USE `sage`;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
INSERT INTO `TiposIva` VALUES (2,0,'Operaciones no sujetas',0.0000000000,0.0000000000,0.0000000000,'','4770000020','','','','','','','95B21A93-5910-489D-83BB-C32788C9B19D','','','','','','','','','',0);
+INSERT INTO `TiposIva` VALUES (3,0,'IVA ESPECIAL 2%',0.0000000000,2.0000000000,0.0000000000,'4720000002','4770000012','','','','','','','9E6160D5-984E-4643-ACBC-1EBC3BF73360','','','','','','','','','',0);
INSERT INTO `TiposIva` VALUES (4,0,'I.V.A. 4%',0.0000000000,4.0000000000,0.0000000000,'4720000004','4770000004','','6310000000','','','','','9E6160D5-984E-4643-ACBC-1EBC3BF73360','','','','','','','','','',0);
INSERT INTO `TiposIva` VALUES (5,0,'I.V.A. 4% y R.E. 0.5%',0.0000000000,4.0000000000,0.5000000000,'','4770000504','4770000405','','','','','','DBEFA562-63FB-4FFC-8171-64F0C6F065FF','','','','','','','','','',0);
INSERT INTO `TiposIva` VALUES (6,0,'H.P. IVA 4% CEE',0.0000000000,4.0000000000,0.0000000000,'4721000004','4771000004','','','','','','','DD0ECBA8-2EF5-425E-911B-623580BADA77','','','','','','','','','',0);
diff --git a/db/dump/.dump/privileges.sql b/db/dump/.dump/privileges.sql
index 8ee823cfa..f608d0e8a 100644
--- a/db/dump/.dump/privileges.sql
+++ b/db/dump/.dump/privileges.sql
@@ -49,6 +49,7 @@ INSERT IGNORE INTO `db` VALUES ('','geo','developerBoss','Y','Y','Y','Y','N','N'
INSERT IGNORE INTO `db` VALUES ('','floranet','developer','Y','Y','Y','Y','N','N','N','N','N','N','N','N','N','N','N','N','Y','N','N','N');
INSERT IGNORE INTO `db` VALUES ('','tmp','guest','Y','Y','Y','Y','N','Y','N','N','N','N','Y','N','N','N','N','N','N','N','N','N');
INSERT IGNORE INTO `db` VALUES ('','util','salix','Y','Y','Y','Y','N','N','N','N','N','N','Y','N','N','N','N','N','Y','N','N','N');
+INSERT IGNORE INTO `db` VALUES ('','srt','maintenanceBoss','Y','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N');
INSERT IGNORE INTO `db` VALUES ('','dipole','developerBoss','Y','Y','Y','Y','N','N','Y','N','N','N','N','N','N','N','N','N','Y','N','N','N');
INSERT IGNORE INTO `db` VALUES ('','bi','developerBoss','Y','Y','Y','Y','N','N','Y','N','N','N','N','N','N','N','N','N','Y','N','N','N');
INSERT IGNORE INTO `db` VALUES ('','sage','developerBoss','Y','Y','Y','Y','N','N','Y','N','N','N','N','N','N','N','N','N','Y','N','N','N');
@@ -502,7 +503,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','receipt','alexm@%','0000-
INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','grafana','visitUser','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','referenceRate','alexm@%','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','report','alexm@%','0000-00-00 00:00:00','Select','');
-INSERT IGNORE INTO `tables_priv` VALUES ('','cache','productionBoss','available','guillermo@10.5.1.2','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyerAssistant','producer','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','time','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','role','alexm@%','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','config__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
@@ -605,7 +606,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','project','jua
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','productionConfig','alexm@%','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','manager','productionConfig','alexm@%','0000-00-00 00:00:00','Update','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','creditInsurance','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
-INSERT IGNORE INTO `tables_priv` VALUES ('','cache','productionBoss','visible','guillermo@10.5.1.2','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','errorProduction__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','invoiceOut','alexm@%','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','coolerAssist','Tickets','alexm@%','0000-00-00 00:00:00','Update','');
@@ -792,7 +792,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hr','Movimientos','alexm@%
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','buy','alexm@%','0000-00-00 00:00:00','Update','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','itemMinimumQuantity','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','receipt','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Insert','');
-INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyerBoss','producer','alexm@%','0000-00-00 00:00:00','Update','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','link','alexm@%','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hr','link','alexm@%','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','delivery','vehicle','alexm@%','0000-00-00 00:00:00','Select','');
@@ -806,7 +805,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','edi','grafana','supplyResponse','ju
INSERT IGNORE INTO `tables_priv` VALUES ('','cache','customer','last_buy','alexm@%','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesAssistant','client','carlosap@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Update','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','invoiceInTax','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
-INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesAssistant','workerTeam','juan@10.5.1.2','0000-00-00 00:00:00','Select,Insert,Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesAssistant','workerTeam','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
INSERT IGNORE INTO `tables_priv` VALUES ('','postgresql','hr','profile_type','alexm@%','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','postgresql','hr','profile_media','alexm@%','0000-00-00 00:00:00','Select,Insert','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','recovery','alexm@%','0000-00-00 00:00:00','Select','');
@@ -836,7 +835,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','bi','salesPerson','tarifa_component
INSERT IGNORE INTO `tables_priv` VALUES ('','srt','employee','expeditionLog','alexm@%','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','bs','salesPerson','clientNewBorn','alexm@%','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','saleItemShelving__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
-INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesBoss','workerTeam','juan@10.5.1.2','0000-00-00 00:00:00','Delete','');
INSERT IGNORE INTO `tables_priv` VALUES ('','srt','employee','expedition','alexm@%','0000-00-00 00:00:00','Update','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','itemShelvingStock','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','saleParking__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
@@ -888,7 +886,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','ticketDms','alexm@%
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','ektEntryAssign','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','intrastat','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','supplierAgencyTerm','alexm@%','0000-00-00 00:00:00','Update','');
-INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','entryConfig','alexm@%','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','packager','franceExpressConfig','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','manager','ticketLog','juan@10.5.1.2','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','ticketCollection','alexm@%','0000-00-00 00:00:00','Delete','');
@@ -943,11 +940,10 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','volumeConfig','alex
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerBoss','ticketTrackingState','alexm@%','0000-00-00 00:00:00','Select,Insert,Update','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','warehouse','alexm@%','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','role','alexm@%','0000-00-00 00:00:00','Select','');
-INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workCenter','alexm@%','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','clientCredit','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','worker','alexm@%','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','workerAppTester','alexm@%','0000-00-00 00:00:00','Select','');
-INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','propertyGroup','alexm@%','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','propertyGroup','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','worker','alexm@%','0000-00-00 00:00:00','Update','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerBusinessType','alexm@%','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','workerDepartment','alexm@%','0000-00-00 00:00:00','Select','');
@@ -966,12 +962,11 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','workerMana','alexm@%',
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','workerMana','alexm@%','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','ticketPackaging','alexm@%','0000-00-00 00:00:00','Insert','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','ticketPackagingStartingStock','alexm@%','0000-00-00 00:00:00','Select','');
-INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','entryConfig','alexm@%','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','officeBoss','ticketPackagingStartingStock','alexm@%','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerRelatives','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','ticketPackagingStartingStock','alexm@%','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','supplierPackaging','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
-INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerDocument','alexm@%','0000-00-00 00:00:00','Select,Insert','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','supplierContact','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceCorrection','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ink','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','zone','alexm@%','0000-00-00 00:00:00','Select','');
@@ -1248,7 +1243,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','bs','deliveryAssistant','m3','alexm
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','ticketDms','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','time','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryAssistant','v_Articles_botanical','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
-INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','workCenter','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','inventoryConfig','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','workerDepartment','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','zoneEvent','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete','');
INSERT IGNORE INTO `tables_priv` VALUES ('','bi','deliveryAssistant','rotacion','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select','');
@@ -1390,7 +1385,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','entry','jenki
INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Cubos_Retorno','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','claimDestination','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','entryConfig','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
-INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','farmingDeliveryNote','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','farmingDeliveryNote','carlosap@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
INSERT IGNORE INTO `tables_priv` VALUES ('','sage','grafana','TiposIva','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','bs','buyer','waste','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','clientObservation','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
@@ -1421,13 +1416,10 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financialBoss','accountDetail'
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','accountDetail','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Update','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','maintenanceBoss','project','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','maintenanceBoss','machineDetail','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
-INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','antenna','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
-INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','bufferPool','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
-INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','enteringLog','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
-INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','expeditionLoading','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
-INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','failureLog','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
-INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','movingLog','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
-INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','sorterLog','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','workerActivityType','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyerSalesAssistant','route','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Update','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','workCenter','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyerSalesAssistant','Rutas','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Update','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','genericAllocation','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','businessReasonEnd','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buy_edi','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
@@ -1465,12 +1457,37 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryBoss','vehicleDms','gu
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryBoss','vehicleInvoiceIn','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryBoss','vehicleNotes','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','saleGroup','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
-INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','bufferLog','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','shelvingLog','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financialBoss','supplierAccount','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','tillSerial','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','stockBuyed','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','alertLevel','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','workerActivityType','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','priceDelta','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','parkingLog','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','travelLog','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','supplierContact','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerDms','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','itemLog','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','account','developer','user','juan@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','claimReason','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','claimResponsible','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','claimResult','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','claimRedelivery','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','producer','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','itemStateTag','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','material','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','saleUnit','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','origin','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','delivery','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','itemFarmingTag','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','itemWrappingTag','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','itemLanguageTag','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','itemStemTag','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','itemBaseTag','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','itemBreederTag','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','itemShelvingLog','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','');
+INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','itemTextureTag','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete','');
/*!40000 ALTER TABLE `tables_priv` ENABLE KEYS */;
/*!40000 ALTER TABLE `columns_priv` DISABLE KEYS */;
@@ -1850,7 +1867,7 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','claimManager','buy_getVolumeByE
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','buy_getVolumeByEntry','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','entry_moveNotPrinted','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','buy_getVolume','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
-INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','stockbuyedbyworker','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','stockBuyedByWorker','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','buy_getsplit','PROCEDURE','juan@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','subordinategetlist','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','buy_afterUpsert','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
@@ -1892,7 +1909,6 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','util','android','debugadd','PROCEDUR
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','copyComponentsFromSaleList','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','duaEntryValueUpdate','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','duaInvoiceInBooking','PROCEDURE','carlosap@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
-INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelvinglog_get','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','expedition_getstate','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','srt','production','expedition_scan','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','productionBoss','saleSplit','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
@@ -1903,7 +1919,7 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','util','grafana','firstdayofyear','FU
INSERT IGNORE INTO `procs_priv` VALUES ('','util','claimManager','dayend','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','util','employee','log_add','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','srt','employee','moving_between','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
-INSERT IGNORE INTO `procs_priv` VALUES ('','bi','financial','defaultersfromdate','PROCEDURE','juan@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','bi','financial','defaultersfromdate','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','getuser','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','hasanynegativebase','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','marketingBoss','hasanynegativebase','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00');
@@ -1998,7 +2014,7 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','logshow','PROCEDURE','alex
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyerBoss','supplierpackaging_reportsource','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','financialBoss','supplierexpenses','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','grafana','firstdayofweek','FUNCTION','juan@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
-INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','stockbuyed_add','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','stockBuyed_add','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','mail_insert','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','duaParcialMake','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','palletizerBoss','packingsite_startcollection','PROCEDURE','alexm@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00');
@@ -2072,13 +2088,12 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelving_addby
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemShelvingSale_addByCollection','PROCEDURE','carlosap@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelving_addlist','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelving_selfconsumption','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
-INSERT IGNORE INTO `procs_priv` VALUES ('','vn','cooler','item_getSimilar','PROCEDURE','guillermo@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','cooler','item_getSimilar','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelvingsale_add','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','collection_printsticker','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','deviceproductionuser_getworker','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','ticket_printlabelprevious','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','ticket_isoutclosurezone','FUNCTION','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
-INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','workermachinery_isregistered','FUNCTION','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','ticketstatetoday_setstate','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','device_checklogin','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','worker_getfromhasmistake','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
@@ -2086,7 +2101,7 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','sectorcollection_n
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','sectorcollection_get','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','setparking','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','shelvingparking_get','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
-INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','machine_getworkerplate','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','report_print','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','saletracking_addprevok','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','sectorcollectionsalegroup_add','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','saletracking_updateischecked','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
@@ -2095,7 +2110,7 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','travel_updatepacki
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','freelance_getinfo','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','company_getfiscaldata','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','expedition_getfromroute','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
-INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','machineworker_gethistorical','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','buy_getUltimate','FUNCTION','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemplacementsupplyaiming','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','expeditionstate_addbypallet','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','srt','production','expeditionloading_add','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
@@ -2116,20 +2131,18 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','srt','delivery','buffer_settypebynam
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','expedition_getstate','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','srt','delivery','expedition_scan','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_get','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
-INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelvinglog_get','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_add','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_getsaledate','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_filterbuyer','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_addbyclaim','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_addlist','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_selfconsumption','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
-INSERT IGNORE INTO `procs_priv` VALUES ('','vn','reviewer','item_getSimilar','PROCEDURE','guillermo@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','reviewer','item_getSimilar','PROCEDURE','guillermo@10.5.1.6','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelvingsale_add','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','collection_printsticker','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','deviceproductionuser_getworker','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','ticket_printlabelprevious','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','ticket_isoutclosurezone','FUNCTION','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
-INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','workermachinery_isregistered','FUNCTION','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','ticketstatetoday_setstate','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','device_checklogin','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','worker_getfromhasmistake','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
@@ -2137,7 +2150,7 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','sectorcollection_new
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','sectorcollection_get','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','setparking','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','shelvingparking_get','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
-INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','machine_getworkerplate','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','buy_getLastWithoutInventory','FUNCTION','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','saletracking_addprevok','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','sectorcollectionsalegroup_add','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','saletracking_updateischecked','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
@@ -2146,7 +2159,7 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','travel_updatepacking
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','freelance_getinfo','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','company_getfiscaldata','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','expedition_getfromroute','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
-INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','machineworker_gethistorical','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','zone_getPostalCode','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemplacementsupplyaiming','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','expeditionstate_addbypallet','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','srt','delivery','expeditionloading_add','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00');
@@ -2191,6 +2204,7 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','buy_recalcPricesByEn
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','entryEditor','buy_recalcPricesByBuy','PROCEDURE','jenkins@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','claimManager','buy_recalcPricesByBuy','PROCEDURE','jenkins@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','buy_recalcPricesByBuy','PROCEDURE','jenkins@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemShelvingSale_addBySaleGroup','PROCEDURE','alexm@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','ledger_nextTx','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','ledger_docompensation','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemShelvingSale_setQuantity','PROCEDURE','carlosap@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
@@ -2206,6 +2220,11 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','grafana-write','item_ValuateInv
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','guest','ticketCalculatePurge','PROCEDURE','jenkins@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','buy_getUltimate','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
INSERT IGNORE INTO `procs_priv` VALUES ('','vn','cooler','buy_getUltimate','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','bs','buyerBoss','waste_addSales','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','saletracking_sectorcollectionaddprevok','PROCEDURE','alexm@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','saleSplit','PROCEDURE','carlosap@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemShelvingSale_deleteAdded','PROCEDURE','guillermo@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
+INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','buy_getUltimate','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00');
/*!40000 ALTER TABLE `procs_priv` ENABLE KEYS */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
@@ -2230,9 +2249,10 @@ INSERT IGNORE INTO `global_priv` VALUES ('','assetManager','{\"access\":0,\"vers
INSERT IGNORE INTO `global_priv` VALUES ('','buyer','{\"access\": 0, \"version_id\": 101106, \"is_role\": true}');
INSERT IGNORE INTO `global_priv` VALUES ('','buyerAssistant','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
INSERT IGNORE INTO `global_priv` VALUES ('','buyerBoss','{\"access\": 0, \"version_id\": 101106, \"is_role\": true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','buyerSalesAssistant','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
INSERT IGNORE INTO `global_priv` VALUES ('','claimManager','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
INSERT IGNORE INTO `global_priv` VALUES ('','cooler','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
-INSERT IGNORE INTO `global_priv` VALUES ('','coolerAssist','{\"access\":0,\"version_id\":100707,\"is_role\":true}');
+INSERT IGNORE INTO `global_priv` VALUES ('','coolerAssist','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
INSERT IGNORE INTO `global_priv` VALUES ('','coolerBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
INSERT IGNORE INTO `global_priv` VALUES ('','customer','{\"access\": 0, \"max_questions\": 0, \"max_updates\": 30000, \"max_connections\": 300000, \"max_user_connections\": 400, \"max_statement_time\": 0.000000, \"is_role\": true,\"version_id\":100707}');
INSERT IGNORE INTO `global_priv` VALUES ('','delivery','{\"access\":0,\"version_id\":101106,\"is_role\":true}');
diff --git a/db/dump/.dump/structure.sql b/db/dump/.dump/structure.sql
index f9ad18c8f..a4ae460b1 100644
--- a/db/dump/.dump/structure.sql
+++ b/db/dump/.dump/structure.sql
@@ -75,26 +75,6 @@ SET character_set_client = utf8;
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) NOT NULL,
- `pid` varchar(255) NOT NULL,
- `user` varchar(255) NOT NULL,
- `host` varchar(255) NOT NULL,
- `rhost` varchar(255) NOT NULL,
- `time` varchar(255) NOT NULL,
- `summaryId` varchar(30) DEFAULT NULL,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Temporary table structure for view `emailUser`
--
@@ -186,23 +166,6 @@ CREATE TABLE `mailAliasAcl` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
---
--- Table structure for table `mailClientAccess__`
---
-
-DROP TABLE IF EXISTS `mailClientAccess__`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `mailClientAccess__` (
- `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
- `client` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL,
- `action` set('OK','REJECT') CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL DEFAULT 'REJECT',
- `description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
- PRIMARY KEY (`id`),
- UNIQUE KEY `mailFrom` (`client`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='@deprecated 2023-09-03';
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Table structure for table `mailConfig`
--
@@ -236,23 +199,6 @@ CREATE TABLE `mailForward` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Mail forwarding';
/*!40101 SET character_set_client = @saved_cs_client */;
---
--- Table structure for table `mailSenderAccess__`
---
-
-DROP TABLE IF EXISTS `mailSenderAccess__`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `mailSenderAccess__` (
- `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
- `sender` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL,
- `action` set('OK','REJECT') NOT NULL DEFAULT 'REJECT',
- `description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
- PRIMARY KEY (`id`),
- UNIQUE KEY `mailFrom` (`sender`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='@deprecated 2023-09-03';
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Temporary table structure for view `myRole`
--
@@ -280,8 +226,7 @@ SET character_set_client = utf8;
1 AS `email`,
1 AS `nickname`,
1 AS `lang`,
- 1 AS `role`,
- 1 AS `recoverPass` */;
+ 1 AS `role` */;
SET character_set_client = @saved_cs_client;
--
@@ -371,6 +316,7 @@ CREATE TABLE `roleLog` (
KEY `userFk` (`userFk`),
KEY `roleLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `roleLog_originFk` (`originFk`,`creationDate`),
+ KEY `roleLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `roleLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -449,15 +395,15 @@ CREATE TABLE `user` (
`role` int(10) unsigned NOT NULL DEFAULT 2,
`active` tinyint(1) NOT NULL DEFAULT 1,
`email` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
- `emailVerified` tinyint(1) DEFAULT NULL,
+ `emailVerified` tinyint(1) NOT NULL DEFAULT 0,
`verificationToken` varchar(512) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`lang` char(2) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`lastPassChange` datetime DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`updated` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`image` varchar(255) DEFAULT NULL,
- `recoverPass` tinyint(3) unsigned NOT NULL DEFAULT 1 COMMENT 'Deprecated',
- `sync` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'Deprecated',
+ `recoverPass__` tinyint(3) unsigned NOT NULL DEFAULT 1 COMMENT '@deprecated 2024-11-13',
+ `sync__` tinyint(4) NOT NULL DEFAULT 0 COMMENT '@deprecated 2024-11-13',
`hasGrant` tinyint(1) NOT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
`passExpired` date DEFAULT NULL,
@@ -515,6 +461,7 @@ CREATE TABLE `userLog` (
KEY `userFk` (`userFk`),
KEY `userLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `userLog_originFk` (`originFk`,`creationDate`),
+ KEY `userLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `userLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -2401,27 +2348,6 @@ CREATE TABLE `analisis_ventas_almacen_evolution` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
- `ventas` int(11) NOT NULL,
- `año` int(11) NOT NULL,
- `periodo` int(11) NOT NULL,
- `typeFk` smallint(5) unsigned DEFAULT NULL,
- UNIQUE KEY `familia` (`familia`,`periodo`),
- KEY `periodo` (`periodo`),
- KEY `analisis_ventas_familia_evolution_FK` (`typeFk`),
- CONSTRAINT `analisis_ventas_familia_evolution_FK` FOREIGN KEY (`typeFk`) REFERENCES `vn`.`itemType` (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #5196 Deprecated 2023-06-05';
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Table structure for table `analisis_ventas_provincia_evolution`
--
@@ -2643,54 +2569,6 @@ SET character_set_client = utf8;
1 AS `Consumo` */;
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=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #5744 Deprecated 2023-06-06';
-/*!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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
- `table_name` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
- `date_field` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
- `table_depending` varchar(15) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
- `execution_order` tinyint(3) unsigned NOT NULL,
- PRIMARY KEY (`schema_name`,`table_name`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #5744 Deprecated 2023-06-06';
-/*!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=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #5744 Deprecated 2023-06-06';
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Temporary table structure for view `rotacion`
--
@@ -2724,26 +2602,13 @@ 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__` varchar(9) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
- `Dia__` varchar(9) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
`Fecha` date NOT NULL,
- `Terceros__` int(11) DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
`Bultos` int(11) NOT NULL DEFAULT 0,
- `Matricula__` varchar(10) DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
- `Tipo__` varchar(1) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
- `year__` int(4) DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
- `month__` int(2) DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
- `warehouse_id__` smallint(5) unsigned DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
- `coste_bulto__` decimal(10,2) unsigned DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
`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,
- `m3__` decimal(10,1) unsigned DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
PRIMARY KEY (`id`),
- UNIQUE KEY `rutasBoard_Ruta` (`Id_Ruta`),
- KEY `rutasBoard_ix1` (`year__`),
- KEY `rutasBoard_ix2` (`month__`),
- KEY `rutasBoard_ix3` (`warehouse_id__`)
+ UNIQUE KEY `rutasBoard_Ruta` (`Id_Ruta`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Se usa en https://grafana.verdnatura.es/d/c089276b-5ab5-430f-aa76-e5d8e0e7fe2e/analisis-de-volumen-y-rendimiento-por-agencia?orgId=1';
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -2780,36 +2645,6 @@ SET character_set_client = utf8;
1 AS `margen` */;
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) NOT NULL,
- PRIMARY KEY (`Id_Premisa`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #5744 Deprecated 2023-06-06';
-/*!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 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #5744 Deprecated 2023-06-06\nAlmacena los valores de gasto por almacen';
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Dumping events for database 'bi'
--
@@ -3683,14 +3518,14 @@ BEGIN
bultos)
SELECT r.id,
r.agencyModeFk,
- r.created,
+ r.dated,
SUM(sv.volume / ebv.m3)
FROM vn.route r
JOIN vn.ticket t ON t.routeFk = r.id
LEFT JOIN vn.`zone` z ON z.id = t.zoneFk
JOIN vn.saleVolume sv ON sv.ticketFk = t.id
JOIN vn.expeditionBoxVol ebv ON ebv.code = 'transportBox'
- WHERE r.created BETWEEN vDatedFrom AND vDatedTo
+ WHERE r.dated BETWEEN vDatedFrom AND vDatedTo
AND z.isVolumetric
GROUP BY r.id;
@@ -3702,12 +3537,12 @@ BEGIN
Bultos)
SELECT r.id,
r.agencyModeFk,
- r.created,
+ r.dated,
SUM(t.packages)
FROM vn.route r
JOIN vn.ticket t ON t.routeFk = r.id
LEFT JOIN vn.`zone` z ON z.id = t.zoneFk
- WHERE r.created BETWEEN vDatedFrom AND vDatedTo
+ WHERE r.dated BETWEEN vDatedFrom AND vDatedTo
AND NOT z.isVolumetric
GROUP BY r.id
ON DUPLICATE KEY UPDATE Bultos = Bultos + VALUES(Bultos);
@@ -3724,7 +3559,7 @@ BEGIN
JOIN vn.component c ON c.id = sc.componentFk
JOIN vn.componentType ct ON ct.id = c.typeFk
WHERE ct.code = 'freight'
- AND r.created BETWEEN vDatedFrom AND vDatedTo
+ AND r.dated BETWEEN vDatedFrom AND vDatedTo
GROUP BY r.id
) sub ON sub.routeFk = r.Id_Ruta
SET r.practico = IFNULL(sub.totalPractice / r.Bultos, 0);
@@ -3741,7 +3576,7 @@ BEGIN
JOIN vn.address ad ON ad.id = t.addressFk
JOIN vn.client c ON c.id = ad.clientFk
LEFT JOIN vn.`zone` z ON z.id = t.zoneFk
- WHERE r.created BETWEEN vDatedFrom AND vDatedTo
+ WHERE r.dated BETWEEN vDatedFrom AND vDatedTo
AND NOT z.isVolumetric
GROUP BY t.routeFk
) sub ON r.Id_Ruta = sub.routeFk
@@ -3757,7 +3592,7 @@ BEGIN
JOIN vn.saleVolume sf ON sf.ticketFk = t.id
JOIN vn.client c ON c.id = t.clientFk
JOIN vn.`zone` z ON z.id = t.zoneFk
- WHERE r.created BETWEEN vDatedFrom AND vDatedTo
+ WHERE r.dated BETWEEN vDatedFrom AND vDatedTo
AND z.isVolumetric
GROUP BY t.routeFk
) sub ON r.Id_Ruta = sub.routeFk
@@ -3772,7 +3607,7 @@ BEGIN
JOIN vn.route r ON r.id = t.routeFk
JOIN vn.greuge g ON g.ticketFk = t.id
JOIN vn.greugeType gt ON gt.id = g.greugeTypeFk
- WHERE r.created BETWEEN vDatedFrom AND vDatedTo
+ WHERE r.dated BETWEEN vDatedFrom AND vDatedTo
AND gt.code = 'freightDifference'
GROUP BY t.routeFk
) sub ON r.Id_Ruta = sub.routeFk
@@ -3876,10 +3711,7 @@ DROP TABLE IF EXISTS `clientDied`;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientDied` (
`clientFk` int(11) NOT NULL DEFAULT 0,
- `clientName__` varchar(50) NOT NULL COMMENT '@deprecated 2023-10-15',
`lastInvoiced` date DEFAULT NULL,
- `workerCode__` varchar(3) NOT NULL COMMENT '@deprecated 2023-10-15',
- `Boss__` varchar(3) NOT NULL COMMENT '@deprecated 2023-10-15',
`warning` enum('first','second','third') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
PRIMARY KEY (`clientFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Clientes que no han comprado en los ultimos 3 meses, se actualiza con proceso nocturno el 3 de cada mes';
@@ -3920,24 +3752,6 @@ CREATE TABLE `clientNewBorn` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Listado de clientes que se consideran nuevos a efectos de cobrar la comision adicional del comercial';
/*!40101 SET character_set_client = @saved_cs_client */;
---
--- Table structure for table `compradores__`
---
-
-DROP TABLE IF EXISTS `compradores__`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `compradores__` (
- `Id_Trabajador` int(10) unsigned 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=utf8mb3 COLLATE=utf8mb3_unicode_ci;
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Table structure for table `compradores_evolution`
--
@@ -3980,7 +3794,7 @@ CREATE TABLE `defaulter` (
`created` date NOT NULL,
`amount` double NOT NULL DEFAULT 0,
`defaulterSinced` date DEFAULT NULL,
- `hasChanged` tinyint(1) DEFAULT NULL,
+ `hasChanged` tinyint(1) NOT NULL DEFAULT 0,
`frozened` date DEFAULT NULL,
PRIMARY KEY (`clientFk`,`created`),
KEY `client` (`clientFk`),
@@ -4292,7 +4106,6 @@ DROP TABLE IF EXISTS `salesByItemTypeDay`;
CREATE TABLE `salesByItemTypeDay` (
`itemTypeFk` smallint(5) unsigned NOT NULL,
`dated` date NOT NULL,
- `netSale__` int(11) NOT NULL DEFAULT 0 COMMENT '@deprecated 2023-08-31, Mismo valor que campo sale',
`stems` int(11) NOT NULL DEFAULT 0 COMMENT 'Número de tallos vendidos',
`references` int(11) NOT NULL DEFAULT 0 COMMENT 'Número de artículos distintos por tipo vendidos',
`trash` int(11) NOT NULL DEFAULT 0 COMMENT 'Tallos basura',
@@ -4347,31 +4160,6 @@ CREATE TABLE `salesByclientSalesPerson` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Ventas diarias por cliente y comercial';
/*!40101 SET character_set_client = @saved_cs_client */;
---
--- Table structure for table `salesMonthlySnapshot___`
---
-
-DROP TABLE IF EXISTS `salesMonthlySnapshot___`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `salesMonthlySnapshot___` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `salesPersonName` varchar(100) DEFAULT '',
- `teamName` varchar(100) DEFAULT NULL,
- `year` int(11) DEFAULT NULL,
- `month` int(11) DEFAULT NULL,
- `currentSale` decimal(10,3) DEFAULT NULL,
- `commissionSale` decimal(10,3) DEFAULT NULL,
- `individualPlus` decimal(10,3) DEFAULT NULL,
- `teamPlus` decimal(10,3) DEFAULT NULL,
- `teamScore` decimal(10,3) DEFAULT NULL,
- `newClientPlus` decimal(10,3) DEFAULT NULL,
- `newClientScore` decimal(10,3) DEFAULT NULL,
- `teamBossPlus` decimal(10,3) DEFAULT NULL,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='@deprecated 2022-11';
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Table structure for table `salesPersonEvolution`
--
@@ -4392,48 +4180,6 @@ CREATE TABLE `salesPersonEvolution` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Evolución Comerciales';
/*!40101 SET character_set_client = @saved_cs_client */;
---
--- Table structure for table `salesPerson__`
---
-
-DROP TABLE IF EXISTS `salesPerson__`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `salesPerson__` (
- `workerFk` int(10) unsigned NOT NULL,
- `year` int(4) NOT NULL,
- `month` int(2) NOT NULL,
- `amount` decimal(10,2) DEFAULT NULL,
- `commission` decimal(10,2) DEFAULT NULL,
- `leasedCommission` decimal(10,2) DEFAULT NULL COMMENT 'comision proveniente de clientes que han sido donados. Ver tabla Clientes_cedidos',
- `cededCommission` decimal(10,2) DEFAULT NULL COMMENT 'comision generada por los clientes que han sido donados. Ver tabla Clientes_cedidos',
- `newCommission` decimal(10,2) DEFAULT NULL,
- `leasedReplacement` decimal(10,2) DEFAULT NULL,
- `itemTypeBorrowed` decimal(10,2) DEFAULT NULL,
- `portfolioWeight` decimal(10,2) DEFAULT NULL COMMENT 'Pero de la cartera del comercial a fecha vendedores.updated',
- `updated` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
- PRIMARY KEY (`workerFk`,`year`,`month`),
- CONSTRAINT `salesPerson_FK` FOREIGN KEY (`workerFk`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='@deprecated 2022-11';
-/*!40101 SET character_set_client = @saved_cs_client */;
-
---
--- Table structure for table `vendedores_evolution__`
---
-
-DROP TABLE IF EXISTS `vendedores_evolution__`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `vendedores_evolution__` (
- `workerFk` int(10) unsigned 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=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='@deprecated 2022-11';
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Temporary table structure for view `ventas`
--
@@ -4490,8 +4236,11 @@ CREATE TABLE `waste` (
`itemFk` int(11) NOT NULL DEFAULT 0,
`saleTotal` decimal(10,2) DEFAULT NULL COMMENT 'Coste',
`saleWasteQuantity` decimal(10,2) DEFAULT NULL,
- `saleInternalWaste` decimal(10,2) DEFAULT NULL,
`saleExternalWaste` decimal(10,2) DEFAULT NULL,
+ `saleFaultWaste` decimal(10,2) DEFAULT NULL,
+ `saleContainerWaste` decimal(10,2) DEFAULT NULL,
+ `saleBreakWaste` decimal(10,2) DEFAULT NULL,
+ `saleOtherWaste` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`year`,`week`,`buyerFk`,`itemTypeFk`,`itemFk`),
KEY `waste_itemType_id` (`itemTypeFk`),
KEY `waste_item_id` (`itemFk`),
@@ -4915,25 +4664,27 @@ BLOCK1: BEGIN
DECLARE vShipped DATE;
DECLARE vPreviousShipped DATE;
DECLARE vDone boolean;
- DECLARE cur cursor for
-
- SELECT clientFk, firstShipped
- FROM bs.clientNewBorn;
+
+ DECLARE cur CURSOR FOR
+ SELECT clientFk, firstShipped
+ FROM bs.clientNewBorn;
DECLARE continue HANDLER FOR NOT FOUND SET vDone = TRUE;
SET vDone := FALSE;
DELETE FROM bs.clientNewBorn WHERE isModified = FALSE;
- INSERT INTO clientNewBorn(clientFk, firstShipped, lastShipped)
- SELECT c.id, MAX(t.shipped), MAX(t.shipped)
- FROM vn.client c
- JOIN vn.ticket t on t.clientFk = c.id
- LEFT JOIN clientNewBorn cb on cb.clientFk = c.id
- WHERE t.shipped BETWEEN TIMESTAMPADD(YEAR, -1, util.VN_CURDATE()) AND util.VN_CURDATE() AND cb.isModified is null
- GROUP BY c.id;
+ INSERT INTO clientNewBorn(clientFk, firstShipped, lastShipped)
+ SELECT c.id, DATE(MAX(t.shipped)), DATE(MAX(t.shipped))
+ FROM vn.client c
+ JOIN vn.ticket t ON t.clientFk = c.id
+ LEFT JOIN clientNewBorn cb ON cb.clientFk = c.id
+ WHERE t.shipped BETWEEN util.VN_CURDATE() - INTERVAL 1 YEAR
+ AND util.VN_CURDATE()
+ AND cb.isModified IS NULL
+ GROUP BY c.id;
+
OPEN cur;
-
LOOP1: LOOP
SET vDone := FALSE;
FETCH cur INTO vClientFk, vShipped;
@@ -5426,7 +5177,7 @@ BEGIN
CREATE OR REPLACE TEMPORARY TABLE tVisible
SELECT itemFk, SUM(visible) totalVisible
FROM vn.itemShelving ish
- JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.shelving sh ON sh.id = ish.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
JOIN vn.sector sc ON sc.id = p.sectorFk
WHERE sc.warehouseFk = vWarehouseFk
@@ -6509,10 +6260,24 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `waste_addSales`()
+CREATE DEFINER=`root`@`localhost` PROCEDURE `waste_addSales`(
+ vDateFrom DATE,
+ vDateTo DATE
+)
BEGIN
- DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL WEEKDAY(util.VN_CURDATE()) DAY;
- DECLARE vDateTo DATE DEFAULT vDateFrom + INTERVAL 6 DAY;
+/**
+ * Recalcula las mermas de un periodo.
+ *
+ * @param vDateFrom Fecha desde
+ * @param vDateTo Fecha hasta
+ */
+ IF vDateFrom IS NULL THEN
+ SET vDateFrom = util.VN_CURDATE() - INTERVAL WEEKDAY(util.VN_CURDATE()) DAY;
+ END IF;
+
+ IF vDateTo IS NULL THEN
+ SET vDateTo = vDateFrom + INTERVAL 6 DAY;
+ END IF;
CALL cache.last_buy_refresh(FALSE);
@@ -6524,16 +6289,32 @@ BEGIN
s.itemFk,
SUM((b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity),
SUM(IF(aw.`type`, s.quantity, 0)),
- SUM(
- IF(
- aw.`type` = 'internal',
+ SUM(IF(
+ aw.`type` = 'external',
(b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity,
0
)
- ),
- SUM(
- IF(
- aw.`type` = 'external',
+ ),
+ SUM(IF(
+ aw.`type` = 'fault',
+ (b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity,
+ 0
+ )
+ ),
+ SUM(IF(
+ aw.`type` = 'container',
+ (b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity,
+ 0
+ )
+ ),
+ SUM(IF(
+ aw.`type` = 'break',
+ (b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity,
+ 0
+ )
+ ),
+ SUM(IF(
+ aw.`type` = 'other',
(b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity,
0
)
@@ -6550,7 +6331,26 @@ BEGIN
JOIN vn.buy b ON b.id = lb.buy_id
WHERE t.shipped BETWEEN vDateFrom AND vDateTo
AND w.isManaged
- GROUP BY i.id;
+ GROUP BY YEAR(t.shipped), WEEK(t.shipped, 4), i.id;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `waste_addSalesLauncher` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `waste_addSalesLauncher`()
+BEGIN
+ CALL waste_addSales(NULL, NULL);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -7137,7 +6937,7 @@ proc: BEGIN
WHERE t.landed BETWEEN vInventoryDate AND vStartDate
AND t.warehouseInFk = vWarehouse
AND s.name != 'INVENTARIO'
- AND NOT e.isRaid
+ AND NOT t.isRaid
GROUP BY b.itemFk
) c
JOIN vn.item i ON i.id = c.itemFk
@@ -8016,7 +7816,6 @@ CREATE TABLE `expedition_PrintOut` (
`longName` varchar(30) DEFAULT NULL,
`shelvingFk` varchar(5) DEFAULT NULL,
`comments` varchar(100) DEFAULT NULL,
- `isChecked` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Indica si la expedición ha sido revisada por un revisor',
PRIMARY KEY (`expeditionFk`),
KEY `expedition_PrintOut_FK` (`printerFk`),
CONSTRAINT `expedition_PrintOut_FK` FOREIGN KEY (`printerFk`) REFERENCES `printer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
@@ -9347,27 +9146,6 @@ CREATE TABLE `warehouseFloramondo` (
--
-- Dumping events for database 'edi'
--
-/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
-/*!50106 DROP EVENT IF EXISTS `floramondo` */;
-DELIMITER ;;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
-/*!50003 SET character_set_client = utf8mb4 */ ;;
-/*!50003 SET character_set_results = utf8mb4 */ ;;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
-/*!50003 SET @saved_time_zone = @@time_zone */ ;;
-/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `floramondo` ON SCHEDULE EVERY 6 MINUTE STARTS '2022-01-28 09:52:45' ON COMPLETION NOT PRESERVE DISABLE DO CALL edi.floramondo_offerRefresh() */ ;;
-/*!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 'edi'
@@ -10085,541 +9863,6 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `floramondo_offerRefresh` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `floramondo_offerRefresh`()
-proc: BEGIN
- DECLARE vLanded DATETIME;
- DECLARE vDone INT DEFAULT FALSE;
- DECLARE vFreeId INT;
- DECLARE vSupplyResponseFk INT;
- DECLARE vLastInserted DATETIME;
- DECLARE vIsAuctionDay BOOLEAN;
- DECLARE vMaxNewItems INT DEFAULT 10000;
- DECLARE vStartingTime DATETIME;
- DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043';
- DECLARE vDayRange INT;
-
- DECLARE cur1 CURSOR FOR
- SELECT id
- FROM edi.item_free;
-
- DECLARE cur2 CURSOR FOR
- SELECT srId
- FROM itemToInsert;
-
- DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
- DECLARE EXIT HANDLER FOR SQLSTATE '45000'
- BEGIN
- ROLLBACK;
- RESIGNAL;
- END;
-
- DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
- BEGIN
- DO RELEASE_LOCK('edi.floramondo_offerRefresh');
- SET @isTriggerDisabled = FALSE;
- RESIGNAL;
- END;
-
- IF 'test' = (SELECT environment FROM util.config) THEN
- LEAVE proc;
- END IF;
-
- IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN
- LEAVE proc;
- END IF;
-
- SELECT dayRange INTO vDayRange
- FROM offerRefreshConfig;
-
- IF vDayRange IS NULL THEN
- CALL util.throw("Variable vDayRange not declared");
- END IF;
-
- SET vStartingTime = util.VN_NOW();
-
- TRUNCATE edi.offerList;
-
- INSERT INTO edi.offerList(supplier, total)
- SELECT v.name, COUNT(DISTINCT sr.ID) total
- FROM edi.supplyResponse sr
- JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
- WHERE sr.NumberOfUnits > 0
- AND sr.EmbalageCode != 999
- GROUP BY sr.vmpID;
-
- UPDATE edi.offerList o
- JOIN (SELECT v.name, COUNT(*) total
- FROM edi.supplyOffer sr
- JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
- GROUP BY sr.vmpID) sub ON o.supplier = sub.name
- SET o.`filter` = sub.total;
-
- -- Elimina de la lista de items libres aquellos que ya existen
- DELETE itf.*
- FROM edi.item_free itf
- JOIN vn.item i ON i.id = itf.id;
-
- CREATE OR REPLACE TEMPORARY TABLE tmp
- (INDEX (`Item_ArticleCode`))
- ENGINE = MEMORY
- SELECT t.*
- FROM (
- SELECT *
- FROM edi.supplyOffer
- ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC,
- NumberOfUnits DESC LIMIT 10000000000000000000) t
- GROUP BY t.srId;
-
- CREATE OR REPLACE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`),
- INDEX (`ef1`), INDEX (`ef2`), INDEX (`ef3`), INDEX (`ef4`),INDEX (`ef5`), INDEX (`ef6`),
- INDEX (`s1Value`), INDEX (`s2Value`), INDEX (`s3Value`), INDEX (`s4Value`),INDEX (`s5Value`), INDEX (`s6Value`))
- ENGINE = MEMORY
- SELECT so.*,
- ev1.type_description s1Value,
- ev2.type_description s2Value,
- ev3.type_description s3Value,
- ev4.type_description s4Value,
- ev5.type_description s5Value,
- ev6.type_description s6Value,
- eif1.feature ef1,
- eif2.feature ef2,
- eif3.feature ef3,
- eif4.feature ef4,
- eif5.feature ef5,
- eif6.feature ef6
- FROM tmp so
- LEFT JOIN edi.item_feature eif1 ON eif1.item_id = so.Item_ArticleCode
- AND eif1.presentation_order = 1
- AND eif1.expiry_date IS NULL
- LEFT JOIN edi.item_feature eif2 ON eif2.item_id = so.Item_ArticleCode
- AND eif2.presentation_order = 2
- AND eif2.expiry_date IS NULL
- LEFT JOIN edi.item_feature eif3 ON eif3.item_id = so.Item_ArticleCode
- AND eif3.presentation_order = 3
- AND eif3.expiry_date IS NULL
- LEFT JOIN edi.item_feature eif4 ON eif4.item_id = so.Item_ArticleCode
- AND eif4.presentation_order = 4
- AND eif4.expiry_date IS NULL
- LEFT JOIN edi.item_feature eif5 ON eif5.item_id = so.Item_ArticleCode
- AND eif5.presentation_order = 5
- AND eif5.expiry_date IS NULL
- LEFT JOIN edi.item_feature eif6 ON eif6.item_id = so.Item_ArticleCode
- AND eif6.presentation_order = 6
- AND eif6.expiry_date IS NULL
- LEFT JOIN edi.`value` ev1 ON ev1.type_id = eif1.feature
- AND so.s1 = ev1.type_value
- LEFT JOIN edi.`value` ev2 ON ev2.type_id = eif2.feature
- AND so.s2 = ev2.type_value
- LEFT JOIN edi.`value` ev3 ON ev3.type_id = eif3.feature
- AND so.s3 = ev3.type_value
- LEFT JOIN edi.`value` ev4 ON ev4.type_id = eif4.feature
- AND so.s4 = ev4.type_value
- LEFT JOIN edi.`value` ev5 ON ev5.type_id = eif5.feature
- AND so.s5 = ev5.type_value
- LEFT JOIN edi.`value` ev6 ON ev6.type_id = eif6.feature
- AND so.s6 = ev6.type_value
- ORDER BY Price;
-
- DROP TEMPORARY TABLE tmp;
-
- DELETE o
- FROM edi.offer o
- LEFT JOIN vn.tag t1 ON t1.ediTypeFk = o.ef1 AND t1.overwrite = 'size'
- LEFT JOIN vn.tag t2 ON t2.ediTypeFk = o.ef2 AND t2.overwrite = 'size'
- LEFT JOIN vn.tag t3 ON t3.ediTypeFk = o.ef3 AND t3.overwrite = 'size'
- LEFT JOIN vn.tag t4 ON t4.ediTypeFk = o.ef4 AND t4.overwrite = 'size'
- LEFT JOIN vn.tag t5 ON t5.ediTypeFk = o.ef5 AND t5.overwrite = 'size'
- LEFT JOIN vn.tag t6 ON t6.ediTypeFk = o.ef6 AND t6.overwrite = 'size'
- JOIN vn.floramondoConfig fc ON TRUE
- WHERE (t1.id IS NOT NULL AND CONVERT(s1Value, UNSIGNED) > fc.itemMaxSize)
- OR (t2.id IS NOT NULL AND CONVERT(s2Value, UNSIGNED) > fc.itemMaxSize)
- OR (t3.id IS NOT NULL AND CONVERT(s3Value, UNSIGNED) > fc.itemMaxSize)
- OR (t4.id IS NOT NULL AND CONVERT(s4Value, UNSIGNED) > fc.itemMaxSize)
- OR (t5.id IS NOT NULL AND CONVERT(s5Value, UNSIGNED) > fc.itemMaxSize)
- OR (t6.id IS NOT NULL AND CONVERT(s6Value, UNSIGNED) > fc.itemMaxSize);
-
- START TRANSACTION;
-
- -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos
- UPDATE IGNORE edi.offer o
- JOIN vn.item i
- ON i.name = o.product_name
- AND i.subname <=> o.company_name
- AND i.value5 <=> o.s1Value
- AND i.value6 <=> o.s2Value
- AND i.value7 <=> o.s3Value
- AND i.value8 <=> o.s4Value
- AND i.value9 <=> o.s5Value
- AND i.value10 <=> o.s6Value
- AND i.NumberOfItemsPerCask <=> o.NumberOfItemsPerCask
- AND i.EmbalageCode <=> o.EmbalageCode
- AND i.quality <=> o.Quality
- JOIN vn.itemType it ON it.id = i.typeFk
- LEFT JOIN vn.sale s ON s.itemFk = i.id
- LEFT JOIN vn.ticket t ON t.id = s.ticketFk
- AND t.shipped > (util.VN_CURDATE() - INTERVAL 1 WEEK)
- LEFT JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk
- LEFT JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID
- LEFT JOIN edi.putOrder po ON po.supplyResponseID = i.supplyResponseFk
- AND po.OrderTradeLineDateTime > (util.VN_CURDATE() - INTERVAL 1 WEEK)
- SET i.supplyResponseFk = o.srID
- WHERE (sr.ID IS NULL
- OR sr.NumberOfUnits = 0
- OR di.LatestOrderDateTime < util.VN_NOW()
- OR di.ID IS NULL)
- AND it.isInventory
- AND t.id IS NULL
- AND po.id IS NULL;
-
- CREATE OR REPLACE TEMPORARY TABLE itemToInsert
- ENGINE = MEMORY
- SELECT o.*, CAST(NULL AS DECIMAL(6,0)) itemFk
- FROM edi.offer o
- LEFT JOIN vn.item i ON i.supplyResponseFk = o.srId
- WHERE i.id IS NULL
- LIMIT vMaxNewItems;
-
- -- Reciclado de nº de item
- OPEN cur1;
- OPEN cur2;
-
- read_loop: LOOP
-
- FETCH cur2 INTO vSupplyResponseFk;
- FETCH cur1 INTO vFreeId;
-
- IF vDone THEN
- LEAVE read_loop;
- END IF;
-
- UPDATE itemToInsert
- SET itemFk = vFreeId
- WHERE srId = vSupplyResponseFk;
-
- END LOOP;
-
- CLOSE cur1;
- CLOSE cur2;
-
- -- Insertamos todos los items en Articles de la oferta
- INSERT INTO vn.item(id,
- `name`,
- longName,
- subName,
- expenseFk,
- typeFk,
- intrastatFk,
- originFk,
- supplyResponseFk,
- numberOfItemsPerCask,
- embalageCode,
- quality,
- isFloramondo)
- SELECT iti.itemFk,
- iti.product_name,
- iti.product_name,
- iti.company_name,
- iti.expenseFk,
- iti.itemTypeFk,
- iti.intrastatFk,
- iti.originFk,
- iti.`srId`,
- iti.NumberOfItemsPerCask,
- iti.EmbalageCode,
- iti.Quality,
- TRUE
- FROM itemToInsert iti;
-
- -- Inserta la foto de los articulos nuevos (prioridad alta)
- INSERT IGNORE INTO vn.itemImageQueue(itemFk, url)
- SELECT i.id, PictureReference
- FROM itemToInsert ii
- JOIN vn.item i ON i.supplyResponseFk = ii.srId
- WHERE PictureReference IS NOT NULL
- AND i.image IS NULL;
-
- INSERT INTO edi.`log`(tableName, fieldName,fieldValue)
- SELECT 'itemImageQueue','NumImagenesPtes', COUNT(*)
- FROM vn.itemImageQueue
- WHERE attempts = 0;
-
- -- Inserta si se añadiesen tags nuevos
- INSERT IGNORE INTO vn.tag (name, ediTypeFk)
- SELECT description, type_id FROM edi.type;
-
- -- Desabilita el trigger para recalcular los tags al final
- SET @isTriggerDisabled = TRUE;
-
- -- Inserta los tags sólo en los articulos nuevos
- INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT i.id, t.id , ii.product_name, 1
- FROM itemToInsert ii
- JOIN vn.tag t ON t.`name` = 'Producto'
- JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
- WHERE NOT ii.product_name IS NULL;
-
- INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT i.id, t.id , ii.Quality, 3
- FROM itemToInsert ii
- JOIN vn.tag t ON t.`name` = 'Calidad'
- JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
- WHERE NOT ii.Quality IS NULL;
-
- INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT i.id, t.id , ii.company_name, 4
- FROM itemToInsert ii
- JOIN vn.tag t ON t.`name` = 'Productor'
- JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
- WHERE NOT ii.company_name IS NULL;
-
- INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT i.id, t.id , s1Value, 5
- FROM itemToInsert ii
- JOIN vn.tag t ON t.ediTypeFk = ii.ef1
- JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
- WHERE NOT s1Value IS NULL;
-
- INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT i.id, t.id , s2Value, 6
- FROM itemToInsert ii
- JOIN vn.tag t ON t.ediTypeFk = ii.ef2
- JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
- WHERE NOT s2Value IS NULL;
-
- INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT i.id, t.id , s3Value, 7
- FROM itemToInsert ii
- JOIN vn.tag t ON t.ediTypeFk = ii.ef3
- JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
- WHERE NOT s3Value IS NULL;
-
- INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT i.id, t.id , s4Value, 8
- FROM itemToInsert ii
- JOIN vn.tag t ON t.ediTypeFk = ii.ef4
- JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
- WHERE NOT s4Value IS NULL;
-
- INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT i.id, t.id , s5Value, 9
- FROM itemToInsert ii
- JOIN vn.tag t ON t.ediTypeFk = ii.ef5
- JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
- WHERE NOT s5Value IS NULL;
-
- INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT i.id, t.id , s6Value, 10
- FROM itemToInsert ii
- JOIN vn.tag t ON t.ediTypeFk = ii.ef6
- JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
- WHERE NOT s6Value IS NULL;
-
- INSERT IGNORE INTO vn.itemTag(itemFk, tagFk, value, priority)
- SELECT i.id, t.id, IFNULL(ink.name, ik.color), 11
- FROM itemToInsert ii
- JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
- JOIN vn.tag t ON t.`name` = 'Color'
- LEFT JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode
- LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id
- AND tp.`description` = 'Hoofdkleur 1'
- LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value
- LEFT JOIN vn.itemInk ik ON ik.longName = i.longName
- WHERE ink.name IS NOT NULL
- OR ik.color IS NOT NULL;
-
- CREATE OR REPLACE TABLE tmp.item
- (PRIMARY KEY (id))
- SELECT i.id FROM vn.item i
- JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId`;
-
- CALL vn.item_refreshTags();
-
- DROP TABLE tmp.item;
-
- SELECT MIN(LatestDeliveryDateTime) INTO vLanded
- FROM edi.supplyResponse sr
- JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID
- JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID
- JOIN vn.floramondoConfig fc
- WHERE mp.isLatestOrderDateTimeRelevant
- AND di.LatestOrderDateTime > IF(
- fc.MaxLatestOrderHour > HOUR(util.VN_NOW()),
- util.VN_CURDATE(),
- util.VN_CURDATE() + INTERVAL 1 DAY);
-
- UPDATE vn.floramondoConfig
- SET nextLanded = vLanded
- WHERE vLanded IS NOT NULL;
-
- -- Elimina la oferta obsoleta
- UPDATE vn.buy b
- JOIN vn.entry e ON e.id = b.entryFk
- JOIN vn.travel tr ON tr.id = e.travelFk
- JOIN vn.agencyMode am ON am.id = tr.agencyModeFk
- JOIN vn.item i ON i.id = b.itemFk
- LEFT JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID
- LEFT JOIN edi.deliveryInformation di ON di.ID = b.deliveryFk
- SET b.quantity = 0
- WHERE (IFNULL(di.LatestOrderDateTime,util.VN_NOW()) <= util.VN_NOW()
- OR i.supplyResponseFk IS NULL
- OR sr.NumberOfUnits = 0)
- AND am.name = 'LOGIFLORA'
- AND e.isRaid;
-
- -- Localiza las entradas de cada almacen
- UPDATE edi.warehouseFloramondo
- SET entryFk = vn.entry_getForLogiflora(vLanded + INTERVAL travellingDays DAY, warehouseFk);
-
- IF vLanded IS NOT NULL THEN
- -- Actualiza la oferta existente
- UPDATE vn.buy b
- JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk
- JOIN vn.item i ON i.id = b.itemFk
- JOIN edi.offer o ON i.supplyResponseFk = o.`srId`
- SET b.quantity = o.NumberOfUnits * o.NumberOfItemsPerCask,
- b.buyingValue = o.price
- WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask
- OR b.buyingValue <> o.price);
-
- -- Inserta el resto
- SET vLastInserted := util.VN_NOW();
-
- -- Inserta la oferta
- INSERT INTO vn.buy (
- entryFk,
- itemFk,
- quantity,
- buyingValue,
- stickers,
- packing,
- `grouping`,
- groupingMode,
- packagingFk,
- deliveryFk)
- SELECT wf.entryFk,
- i.id,
- o.NumberOfUnits * o.NumberOfItemsPerCask quantity,
- o.Price,
- o.NumberOfUnits etiquetas,
- o.NumberOfItemsPerCask packing,
- GREATEST(1, IFNULL(o.MinimumQuantity,0)) * o.NumberOfItemsPerCask `grouping`,
- 'packing',
- o.embalageCode,
- o.diId
- FROM edi.offer o
- JOIN vn.item i ON i.supplyResponseFk = o.srId
- JOIN edi.warehouseFloramondo wf
- JOIN vn.packaging p ON p.id
- LIKE o.embalageCode
- LEFT JOIN vn.buy b ON b.itemFk = i.id
- AND b.entryFk = wf.entryFk
- WHERE b.id IS NULL; -- Quitar esta linea y mirar de crear los packages a tiempo REAL
-
- INSERT INTO vn.itemCost(
- itemFk,
- warehouseFk,
- cm3,
- cm3delivery)
- SELECT b.itemFk,
- wf.warehouseFk,
- @cm3 := vn.buy_getUnitVolume(b.id),
- IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3)
- FROM warehouseFloramondo wf
- JOIN vn.volumeConfig vc
- JOIN vn.buy b ON b.entryFk = wf.entryFk
- JOIN vn.item i ON i.id = b.itemFk
- LEFT JOIN vn.itemCost ic ON ic.itemFk = b.itemFk
- AND ic.warehouseFk = wf.warehouseFk
- WHERE (ic.cm3 IS NULL OR ic.cm3 = 0)
- ON DUPLICATE KEY UPDATE cm3 = @cm3, cm3delivery = IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3);
-
- CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc
- SELECT b.id
- FROM vn.buy b
- JOIN warehouseFloramondo wf ON wf.entryFk = b.entryFk
- WHERE b.created >= vLastInserted;
-
- CALL vn.buy_recalcPrices();
-
- UPDATE edi.offerList o
- JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total
- FROM vn.buy b
- JOIN vn.item i ON i.id = b.itemFk
- JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk
- JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
- JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk
- JOIN vn.warehouse w ON w.id = wf.warehouseFk
- WHERE w.name = 'VNH'
- AND b.quantity > 0
- GROUP BY sr.vmpID) sub ON o.supplier = sub.name
- SET o.vnh = sub.total;
-
- UPDATE edi.offerList o
- JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total
- FROM vn.buy b
- JOIN vn.item i ON i.id = b.itemFk
- JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk
- JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
- JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk
- JOIN vn.warehouse w ON w.id = wf.warehouseFk
- WHERE w.name = 'ALGEMESI'
- AND b.quantity > 0
- GROUP BY sr.vmpID) sub ON o.supplier = sub.name
- SET o.algemesi = sub.total;
- END IF;
-
- DROP TEMPORARY TABLE
- edi.offer,
- itemToInsert;
-
- SET @isTriggerDisabled = FALSE;
-
- COMMIT;
-
- -- Esto habria que pasarlo a procesos programados o trabajar con tags y dejar las familias
- UPDATE vn.item i
- SET typeFk = 121
- WHERE i.longName LIKE 'Rosa Garden %'
- AND typeFk = 17;
-
- UPDATE vn.item i
- SET typeFk = 156
- WHERE i.longName LIKE 'Rosa ec %'
- AND typeFk = 17;
-
- -- Refresca las fotos de los items existentes que mostramos (prioridad baja)
- INSERT IGNORE INTO vn.itemImageQueue(itemFk, url, priority)
- SELECT i.id, sr.PictureReference, 100
- FROM edi.supplyResponse sr
- JOIN vn.item i ON i.supplyResponseFk = sr.ID
- JOIN edi.supplyOffer so ON so.srId = sr.ID
- JOIN hedera.image i2 ON i2.name = i.image
- AND i2.collectionFk = 'catalog'
- WHERE i2.updated <= (UNIX_TIMESTAMP(util.VN_NOW()) - vDayRange)
- AND sr.NumberOfUnits;
-
- INSERT INTO edi.`log`
- SET tableName = 'floramondo_offerRefresh',
- fieldName = 'Tiempo de proceso',
- fieldValue = TIMEDIFF(util.VN_NOW(), vStartingTime);
-
- DO RELEASE_LOCK('edi.floramondo_offerRefresh');
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_freeAdd` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -12133,6 +11376,7 @@ CREATE TABLE `order` (
`tax` decimal(10,2) NOT NULL,
`total` decimal(10,2) NOT NULL,
`configured` datetime DEFAULT NULL,
+ `rowUpdated` datetime DEFAULT NULL COMMENT 'Timestamp for last updated record in orderRow table',
PRIMARY KEY (`id`),
KEY `address` (`address_id`),
KEY `delivery_method` (`delivery_method_id`),
@@ -12998,7 +12242,7 @@ BEGIN
JOIN vn.travel t ON t.id = e.travelFk
WHERE t.landed BETWEEN vDateInv AND vDate
AND t.warehouseInFk = vWarehouse
- AND NOT e.isRaid
+ AND NOT t.isRaid
UNION ALL
SELECT b.itemFk, -b.quantity
FROM vn.buy b
@@ -13006,7 +12250,7 @@ BEGIN
JOIN vn.travel t ON t.id = e.travelFk
WHERE t.shipped BETWEEN vDateInv AND util.VN_CURDATE()
AND t.warehouseOutFk = vWarehouse
- AND NOT e.isRaid
+ AND NOT t.isRaid
AND t.isDelivered
UNION ALL
SELECT m.itemFk, -m.quantity
@@ -13921,6 +13165,70 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `orderRow_updateOverstocking` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `orderRow_updateOverstocking`(vOrderFk INT)
+BEGIN
+/**
+* Set amount = 0 to avoid overbooking sales
+*
+* @param vOrderFk hedera.order.id
+*/
+ DECLARE vCalcFk INT;
+ DECLARE vDone BOOL;
+ DECLARE vWarehouseFk INT;
+
+ DECLARE cWarehouses CURSOR FOR
+ SELECT DISTINCT warehouseFk
+ FROM orderRow
+ WHERE orderFk = vOrderFk
+ AND shipment = util.VN_CURDATE();
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ OPEN cWarehouses;
+ checking: LOOP
+ SET vDone = FALSE;
+
+ FETCH cWarehouses INTO vWarehouseFk;
+
+ IF vDone THEN
+ LEAVE checking;
+ END IF;
+
+ CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, util.VN_CURDATE());
+
+ UPDATE orderRow r
+ JOIN `order` o ON o.id = r.orderFk
+ JOIN orderConfig oc
+ JOIN cache.available a ON a.calc_id = vCalcFk AND a.item_id = r.itemFk
+ SET r.amount = 0
+ WHERE ADDTIME(o.rowUpdated, oc.reserveTime) < util.VN_NOW()
+ AND a.available <= 0
+ AND r.warehouseFk = vWarehouseFk
+ AND r.orderFk = vOrderFk;
+ END LOOP;
+ CLOSE cWarehouses;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `order_addItem` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -14426,6 +13734,7 @@ BEGIN
* @param vUser The user identifier
*/
DECLARE vHasRows BOOL;
+ DECLARE vHas0Amount BOOL;
DECLARE vDone BOOL;
DECLARE vWarehouseFk INT;
DECLARE vShipment DATE;
@@ -14435,7 +13744,6 @@ BEGIN
DECLARE vItemFk INT;
DECLARE vConcept VARCHAR(30);
DECLARE vAmount INT;
- DECLARE vAvailable INT;
DECLARE vPrice DECIMAL(10,2);
DECLARE vSaleFk INT;
DECLARE vRowFk INT;
@@ -14445,7 +13753,6 @@ BEGIN
DECLARE vClientFk INT;
DECLARE vCompanyFk INT;
DECLARE vAgencyModeFk INT;
- DECLARE vCalcFk INT;
DECLARE vIsTaxDataChecked BOOL;
DECLARE vDates CURSOR FOR
@@ -14511,6 +13818,20 @@ BEGIN
SELECT employeeFk INTO vUserFk FROM orderConfig;
END IF;
+ CALL orderRow_updateOverstocking(vSelf);
+
+ -- Check if any product has a quantity of 0
+ SELECT EXISTS (
+ SELECT id
+ FROM orderRow
+ WHERE orderFk = vSelf
+ AND amount = 0
+ ) INTO vHas0Amount;
+
+ IF vHas0Amount THEN
+ CALL util.throw('Hay líneas vacías. Por favor, elimínelas');
+ END IF;
+
START TRANSACTION;
CALL order_checkEditable(vSelf);
@@ -14772,45 +14093,54 @@ BEGIN
* @param vOrder El identificador del pedido
* @return tmp.orderTax Bases imponibles, IVA y recargo de equivalencia
*/
+ -- No poner create or replace, ya que da problemas
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;
+ JOIN `order` o ON o.id = tmpOrder.orderFk;
- CALL vn.addressTaxArea;
+ CALL vn.addressTaxArea();
-- Calcula el IVA y el recargo desglosado.
-
- DROP TEMPORARY TABLE IF EXISTS tmp.orderTax;
- CREATE TEMPORARY TABLE tmp.orderTax
- (INDEX (orderFk))
+ CREATE OR REPLACE TEMPORARY TABLE tmp.orderTax
+ (PRIMARY KEY (orderFk, code, rate))
ENGINE = MEMORY
- SELECT o.id orderFk,
+ WITH orders AS (
+ SELECT tor.orderFk,
+ oro.amount * oro.price total,
+ s.countryFk,
+ ata.areaFk,
+ itc.taxClassFk
+ FROM hedera.orderRow oro
+ JOIN tmp.order tor ON tor.orderFk = oro.orderFk
+ JOIN hedera.`order` o ON o.id = tor.orderFk
+ JOIN vn.item i ON i.id = oro.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
+ HAVING total
+ )
+ SELECT o.orderFk,
tc.code,
- SUM(m.amount * m.price) taxableBase,
+ SUM(o.total) 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
+ FROM orders o
+ JOIN vn.bookingPlanner bp ON bp.countryFk = o.countryFk
+ AND bp.taxAreaFk = o.areaFk
+ AND bp.taxClassFk = o.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;
+ GROUP BY o.orderFk, pgc.code, pgc.rate
+ HAVING taxableBase
+ ORDER BY bp.priority;
+ -- No poner create or replace, ya que da problemas
DROP TEMPORARY TABLE IF EXISTS tmp.orderAmount;
CREATE TEMPORARY TABLE tmp.orderAmount
(INDEX (orderFk))
@@ -18173,7 +17503,7 @@ BEGIN
DECLARE vCursor CURSOR FOR
SELECT it.taxableBase,
- CAST((( it.taxableBase / 100) * t.PorcentajeIva) AS DECIMAL (10,2)),
+ CAST(SUM((( it.taxableBase / 100) * t.PorcentajeIva)) AS DECIMAL (10,2)),
t.PorcentajeIva,
it.transactionTypeSageFk,
it.taxTypeSageFk,
@@ -18186,7 +17516,8 @@ BEGIN
JOIN TiposTransacciones tt ON tt.CodigoTransaccion = it.transactionTypeSageFk
LEFT JOIN vn.dua d ON d.id = vInvoiceInFk
WHERE i.id = vInvoiceInFk
- AND d.id IS NULL;
+ AND d.id IS NULL
+ GROUP BY it.taxTypeSageFk;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
@@ -19047,6 +18378,7 @@ CREATE TABLE `ACLLog` (
KEY `logRateuserFk` (`userFk`),
KEY `ACLLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `ACLLog_originFk` (`originFk`,`creationDate`),
+ KEY `ACLLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `aclUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -19455,6 +18787,7 @@ CREATE TABLE `bufferLog` (
KEY `logBufferUserFk` (`userFk`),
KEY `bufferLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `bufferLog_originFk` (`originFk`,`creationDate`),
+ KEY `bufferLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `bufferUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -23404,12 +22737,11 @@ BEGIN
DROP TEMPORARY TABLE IF EXISTS tValues;
CREATE TEMPORARY TABLE tValues
ENGINE = MEMORY
- SELECT
- b.id buyFk,
+ SELECT b.id buyFk,
e.id entryFk,
t.id travelFk,
b.itemFk,
- e.isRaid,
+ t.isRaid,
ADDTIME(t.shipped,
IFNULL(t.shipmentHour, '00:00:00')) shipped,
t.warehouseOutFk,
@@ -23448,7 +22780,7 @@ BEGIN
itemFk,
TIMESTAMPADD(DAY, life, @dated),
quantity,
- IF(isIn, isReceived, isDelivered) AND !isRaid
+ IF(isIn, isReceived, isDelivered) AND NOT isRaid
FROM tValues
WHERE isIn OR !lessThanInventory;
@@ -23463,7 +22795,7 @@ BEGIN
itemFk,
created,
quantity,
- IF(isIn, isDelivered, isReceived) AND !isRaid
+ IF(isIn, isDelivered, isReceived) AND NOT isRaid
FROM tValues
WHERE !isIn OR !lessThanInventory;
@@ -24087,8 +23419,6 @@ DROP TABLE IF EXISTS `config`;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `config` (
`id` int(10) unsigned NOT NULL,
- `dbVersion` char(11) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci 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 utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT 'The current Database environment',
`lastDump` datetime DEFAULT NULL COMMENT 'Timestamp of the last data dump',
`mockUtcTime` datetime DEFAULT NULL,
@@ -24151,6 +23481,24 @@ SET character_set_client = utf8;
1 AS `error` */;
SET character_set_client = @saved_cs_client;
+--
+-- Table structure for table `logCleanMultiConfig`
+--
+
+DROP TABLE IF EXISTS `logCleanMultiConfig`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `logCleanMultiConfig` (
+ `schemaName` varchar(64) NOT NULL,
+ `tableName` varchar(64) NOT NULL,
+ `retentionDays` int(11) DEFAULT NULL,
+ `order` int(11) DEFAULT NULL,
+ `started` datetime DEFAULT NULL,
+ `finished` datetime DEFAULT NULL,
+ PRIMARY KEY (`schemaName`,`tableName`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `notification`
--
@@ -24297,7 +23645,25 @@ CREATE TABLE `versionLog` (
-- Dumping events for database 'util'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
-/*!50106 DROP EVENT IF EXISTS `slowLog_prune` */;
+/*!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 = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
+/*!50003 SET @saved_time_zone = @@time_zone */ ;;
+/*!50003 SET time_zone = 'SYSTEM' */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `log_clean` ON SCHEDULE EVERY 1 DAY STARTS '2024-07-09 00:30:00' ON COMPLETION PRESERVE ENABLE DO CALL util.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 `slowLog_prune` */;;
DELIMITER ;;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;;
@@ -25754,6 +25120,73 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `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_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`root`@`localhost` PROCEDURE `log_clean`()
+BEGIN
+/**
+ * Hace limpieza de los datos de las tablas log,
+ * dejando únicamente los días de retención configurados.
+ */
+ DECLARE vSchemaName VARCHAR(65);
+ DECLARE vSchemaNameQuoted VARCHAR(65);
+ DECLARE vTableName VARCHAR(65);
+ DECLARE vTableNameQuoted VARCHAR(65);
+ DECLARE vRetentionDays INT;
+ DECLARE vStarted DATETIME;
+ DECLARE vDated DATE;
+ DECLARE vDone BOOL;
+
+ DECLARE vQueue CURSOR FOR
+ SELECT schemaName, tableName, retentionDays
+ FROM logCleanMultiConfig
+ ORDER BY `order`;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ OPEN vQueue;
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH vQueue INTO vSchemaName, vTableName, vRetentionDays;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ IF vRetentionDays THEN
+ SET vStarted = VN_NOW();
+ SET vSchemaNameQuoted = quoteIdentifier(vSchemaName);
+ SET vTableNameQuoted = quoteIdentifier(vTableName);
+ SET vDated = VN_CURDATE() - INTERVAL vRetentionDays DAY;
+
+ EXECUTE IMMEDIATE CONCAT(
+ 'DELETE FROM ', vSchemaNameQuoted,
+ '.', vTableNameQuoted,
+ " WHERE creationDate < '", vDated, "'"
+ );
+
+ UPDATE logCleanMultiConfig
+ SET `started` = vStarted,
+ `finished` = VN_NOW()
+ WHERE schemaName = vSchemaName
+ AND tableName = vTableName;
+ END IF;
+ END LOOP;
+ CLOSE vQueue;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `log_cleanInstances` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -26459,10 +25892,11 @@ CREATE TABLE `address` (
`isActive` tinyint(4) NOT NULL DEFAULT 1,
`longitude` decimal(11,7) DEFAULT NULL COMMENT 'Indica la última longitud proporcionada por tabla delivery',
`latitude` decimal(11,7) DEFAULT NULL COMMENT 'Indica la última latitud proporcionada por tabla delivery',
- `isEqualizated` tinyint(1) DEFAULT NULL,
+ `isEqualizated` tinyint(1) NOT NULL DEFAULT 0,
`customsAgentFk` int(11) DEFAULT NULL,
`incotermsFk` varchar(3) DEFAULT NULL,
`isLogifloraAllowed` tinyint(4) NOT NULL DEFAULT 0,
+ `geoFk` int(11) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `Id_Agencia` (`agencyModeFk`),
@@ -26474,12 +25908,14 @@ CREATE TABLE `address` (
KEY `address_customsAgentFk_idx` (`customsAgentFk`),
KEY `address_incotermsFk_idx` (`incotermsFk`),
KEY `address_fk_editor` (`editorFk`),
+ KEY `address_zoneGeo_FK` (`geoFk`),
CONSTRAINT `address_customer_id` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE,
CONSTRAINT `address_customsAgentFk` FOREIGN KEY (`customsAgentFk`) REFERENCES `customsAgent` (`id`) ON UPDATE CASCADE,
CONSTRAINT `address_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
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,
- CONSTRAINT `address_incotermsFk` FOREIGN KEY (`incotermsFk`) REFERENCES `incoterms` (`code`) ON UPDATE CASCADE
+ CONSTRAINT `address_incotermsFk` FOREIGN KEY (`incotermsFk`) REFERENCES `incoterms` (`code`) ON UPDATE CASCADE,
+ CONSTRAINT `address_zoneGeo_FK` FOREIGN KEY (`geoFk`) REFERENCES `zoneGeo` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -26555,7 +25991,7 @@ DROP TABLE IF EXISTS `addressWaste`;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `addressWaste` (
`addressFk` int(11) NOT NULL,
- `type` enum('internal','external') NOT NULL,
+ `type` enum('external','fault','container','break','other') NOT NULL,
PRIMARY KEY (`addressFk`),
CONSTRAINT `addressShortage_FK` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
@@ -26572,17 +26008,14 @@ CREATE TABLE `agency` (
`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(25) NOT NULL,
`warehouseFk` smallint(5) unsigned DEFAULT NULL COMMENT 'A nulo si se puede enrutar desde todos los almacenes',
- `warehouseAliasFk__` smallint(5) unsigned DEFAULT NULL COMMENT '@deprecated 2024-01-23 refs #5167',
`isOwn` tinyint(1) NOT NULL DEFAULT 0,
`workCenterFk` int(11) DEFAULT NULL,
`isAnyVolumeAllowed` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Permite vender productos que tengan vn.itemType.IsUnconventionalSize = TRUE',
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `warehouse_id` (`warehouseFk`),
- KEY `agencias_alias_idx` (`warehouseAliasFk__`),
KEY `agency_ibfk_3_idx` (`workCenterFk`),
KEY `agency_user_FK` (`editorFk`),
- CONSTRAINT `agency_FK` FOREIGN KEY (`warehouseAliasFk__`) REFERENCES `warehouseAlias__` (`id`) ON UPDATE CASCADE,
CONSTRAINT `agency_ibfk_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
CONSTRAINT `agency_ibfk_3` FOREIGN KEY (`workCenterFk`) REFERENCES `workCenter` (`id`) ON UPDATE CASCADE,
CONSTRAINT `agency_user_FK` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
@@ -26646,6 +26079,7 @@ CREATE TABLE `agencyLog` (
KEY `logAgencyUserFk` (`userFk`),
KEY `agencyLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `agencyLog_originFk` (`originFk`,`creationDate`),
+ KEY `agencyLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `agencyOriginFk` FOREIGN KEY (`originFk`) REFERENCES `agency` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `agencyUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
@@ -26669,7 +26103,6 @@ CREATE TABLE `agencyMode` (
`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) 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 DEFAULT NULL COMMENT 'obsoleta',
@@ -27029,7 +26462,6 @@ CREATE TABLE `awbComponent` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`awbFk` smallint(11) unsigned DEFAULT NULL,
`supplierFk` int(11) NOT NULL,
- `dated__` date NOT NULL,
`typeFk` mediumint(3) unsigned DEFAULT NULL,
`awbRoleFk` tinyint(1) unsigned NOT NULL DEFAULT 1,
`awbUnitFk` varchar(10) DEFAULT NULL,
@@ -27388,30 +26820,6 @@ CREATE TABLE `bookingPlanner` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 */;
-/*!40101 SET character_set_client = utf8 */;
-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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
- `description` varchar(45) DEFAULT NULL,
- `isProtectedZone` tinyint(1) NOT NULL DEFAULT 0,
- `code` enum('importProhibited','phytosanitaryPassport','individualPassport') DEFAULT NULL,
- PRIMARY KEY (`id`),
- KEY `Id_Paises` (`countryFk__`),
- KEY `botanicExport_ibfk_2_idx` (`ediGenusFk`),
- KEY `botanicExport_ibfk_3_idx` (`ediSpecieFk`),
- CONSTRAINT `botanicExport___ibfk_1` FOREIGN KEY (`countryFk__`) REFERENCES `country` (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #4419 Deprecated 2023-07-20';
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Table structure for table `budget`
--
@@ -27661,7 +27069,6 @@ CREATE TABLE `buy` (
`packing` int(11) NOT NULL DEFAULT 1 CHECK (`packing` > 0),
`grouping` smallint(5) unsigned NOT NULL DEFAULT 1,
`groupingMode` enum('grouping','packing') DEFAULT NULL,
- `containerFk__` smallint(5) unsigned DEFAULT NULL,
`comissionValue` decimal(10,3) NOT NULL DEFAULT 0.000,
`packageValue` decimal(10,3) NOT NULL DEFAULT 0.000,
`location` varchar(5) DEFAULT NULL,
@@ -27686,7 +27093,6 @@ CREATE TABLE `buy` (
KEY `CompresId_Trabajador` (`workerFk`),
KEY `Id_Cubo` (`packagingFk`),
KEY `Id_Entrada` (`entryFk`),
- KEY `container_id` (`containerFk__`),
KEY `buy_edi_id` (`ektFk`),
KEY `itemFk_entryFk` (`itemFk`,`entryFk`),
KEY `buy_fk_4_idx` (`deliveryFk`),
@@ -27719,23 +27125,6 @@ CREATE TABLE `buyConfig` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
---
--- Table structure for table `buyMark`
---
-
-DROP TABLE IF EXISTS `buyMark`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `buyMark` (
- `id` int(11) NOT NULL,
- `comment` varchar(255) 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=utf8mb3 COLLATE=utf8mb3_unicode_ci;
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Temporary table structure for view `buyer`
--
@@ -27869,9 +27258,10 @@ DROP TABLE IF EXISTS `campaign`;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `campaign` (
`id` int(11) NOT NULL AUTO_INCREMENT,
- `code` enum('mothersDay','allSaints','valentinesDay') NOT NULL,
+ `code` enum('mothersDay','allSaints','valentinesDay','frenchMothersDay') NOT NULL,
`dated` datetime NOT NULL DEFAULT current_timestamp(),
`scopeDays` int(11) NOT NULL DEFAULT 15,
+ `previousDays` int(10) unsigned NOT NULL DEFAULT 30 COMMENT 'Días previos para calcular e insertar en la tabla itemCampaign',
PRIMARY KEY (`id`),
UNIQUE KEY `campaign_dated_uindex` (`dated`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
@@ -27923,9 +27313,8 @@ CREATE TABLE `chat` (
`senderFk` int(10) unsigned DEFAULT NULL,
`recipient` varchar(50) DEFAULT NULL,
`dated` datetime DEFAULT NULL,
- `checkUserStatus` tinyint(1) DEFAULT NULL,
+ `checkUserStatus` tinyint(1) NOT NULL DEFAULT 0,
`message` text DEFAULT NULL,
- `status__` tinyint(1) DEFAULT NULL,
`attempts` int(1) DEFAULT NULL,
`error` text DEFAULT NULL,
`status` enum('pending','sent','error','sending') NOT NULL DEFAULT 'pending',
@@ -27973,7 +27362,6 @@ CREATE TABLE `claim` (
`ticketFk` int(11) DEFAULT NULL,
`pickup` enum('agency','delivery') DEFAULT NULL,
`packages` smallint(10) unsigned DEFAULT 0 COMMENT 'packages received by the client',
- `rma__` varchar(100) DEFAULT NULL,
`responsabilityRate` decimal(3,2) GENERATED ALWAYS AS ((5 - `responsibility`) / 4) VIRTUAL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
@@ -28156,6 +27544,7 @@ CREATE TABLE `claimLog` (
KEY `userFk` (`userFk`),
KEY `claimLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `claimLog_claimLog` (`originFk`,`creationDate`),
+ KEY `claimLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `claimUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -28264,22 +27653,6 @@ CREATE TABLE `claimResult` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Consecuencias de los motivos';
/*!40101 SET character_set_client = @saved_cs_client */;
---
--- Table structure for table `claimRma__`
---
-
-DROP TABLE IF EXISTS `claimRma__`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `claimRma__` (
- `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
- `code` varchar(100) NOT NULL,
- `created` timestamp NOT NULL DEFAULT current_timestamp(),
- `workerFk` int(10) unsigned NOT NULL,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='kkeada el 2024-02-26 por Pablo';
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Table structure for table `claimState`
--
@@ -28334,7 +27707,7 @@ CREATE TABLE `client` (
`credit` decimal(10,2) unsigned NOT NULL DEFAULT 0.00,
`countryFk` mediumint(8) unsigned NOT NULL DEFAULT 1,
`isActive` tinyint(1) NOT NULL DEFAULT 1,
- `gestdocFk` int(11) DEFAULT NULL,
+ `gestdocFk__` int(11) DEFAULT NULL COMMENT '@deprecated 2024-10-17',
`quality` int(2) DEFAULT 11,
`payMethodFk` tinyint(3) unsigned NOT NULL DEFAULT 5,
`created` timestamp NULL DEFAULT current_timestamp(),
@@ -28346,7 +27719,6 @@ CREATE TABLE `client` (
`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 COMMENT '@deprecated 2024-02-20 refs #6784',
`creditInsurance` int(11) DEFAULT NULL,
`eypbc` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Email\\nYesterday\\nPurchases\\nBy\\nConsigna',
`hasToInvoiceByAddress` tinyint(1) DEFAULT 0,
@@ -28362,11 +27734,11 @@ CREATE TABLE `client` (
`transferorFk` int(11) DEFAULT NULL COMMENT 'Cliente que le ha transmitido la titularidad de la empresa',
`lastSalesPersonFk` int(10) unsigned DEFAULT NULL COMMENT 'ultimo comercial que tuvo, para el calculo del peso en los rankings de equipo',
`businessTypeFk` varchar(20) NOT NULL DEFAULT 'florist',
- `hasIncoterms__` tinyint(1) NOT NULL DEFAULT 0 COMMENT '@deprecated 2024-06-12 refs #7545 Received incoterms authorization from client',
`rating` int(10) unsigned DEFAULT NULL COMMENT 'información proporcionada por Informa',
`recommendedCredit` int(10) unsigned DEFAULT NULL COMMENT 'información proporcionada por Informa',
- `editorFk` int(10) unsigned DEFAULT NULL,
`hasDailyInvoice` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Indica si el cliente requiere facturación diaria por defecto se copiará lo que tenga country.hasDailyInvoice',
+ `geoFk` int(11) DEFAULT NULL,
+ `editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `IF` (`fi`),
KEY `Id_Trabajador` (`salesPersonFk`),
@@ -28378,7 +27750,6 @@ CREATE TABLE `client` (
KEY `default_address` (`defaultAddressFk`),
KEY `Telefono` (`phone`),
KEY `movil` (`mobile`),
- KEY `tipos_de_cliente_idx` (`clientTypeFk__`),
KEY `fk_Clientes_entity_idx` (`bankEntityFk`),
KEY `typeFk` (`typeFk`),
KEY `client_taxTypeSageFk_idx` (`taxTypeSageFk`),
@@ -28389,6 +27760,7 @@ CREATE TABLE `client` (
KEY `codpos` (`postcode`),
KEY `client_fk_editor` (`editorFk`),
KEY `client_isTaxDataChecked_IDX` (`isTaxDataChecked`) USING BTREE,
+ KEY `client_zoneGeo_FK` (`geoFk`),
CONSTRAINT `canal_nuevo_cliente` FOREIGN KEY (`contactChannelFk`) REFERENCES `contactChannel` (`id`) ON UPDATE CASCADE,
CONSTRAINT `client_FK` FOREIGN KEY (`businessTypeFk`) REFERENCES `businessType` (`code`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `client_FK_1` FOREIGN KEY (`bankEntityFk`) REFERENCES `bankEntity` (`id`) ON UPDATE CASCADE,
@@ -28402,6 +27774,7 @@ CREATE TABLE `client` (
CONSTRAINT `client_ibfk_5` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`) ON UPDATE CASCADE,
CONSTRAINT `client_taxTypeSageFk` FOREIGN KEY (`taxTypeSageFk`) REFERENCES `sage`.`TiposIva` (`CodigoIva`) ON UPDATE CASCADE,
CONSTRAINT `client_transactionTypeSageFk` FOREIGN KEY (`transactionTypeSageFk`) REFERENCES `sage`.`TiposTransacciones` (`CodigoTransaccion`) ON UPDATE CASCADE,
+ CONSTRAINT `client_zoneGeo_FK` FOREIGN KEY (`geoFk`) REFERENCES `zoneGeo` (`id`) ON UPDATE CASCADE,
CONSTRAINT `typeFk` FOREIGN KEY (`typeFk`) REFERENCES `clientType` (`code`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -28600,6 +27973,7 @@ CREATE TABLE `clientLog` (
KEY `userFk` (`userFk`),
KEY `clientLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `clientLog_clientLog` (`originFk`,`creationDate`),
+ KEY `clientLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `clientLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -28649,11 +28023,14 @@ CREATE TABLE `clientObservation` (
`text` text NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`editorFk` int(10) unsigned DEFAULT NULL,
+ `observationTypeFk` tinyint(3) unsigned NOT NULL DEFAULT 4,
PRIMARY KEY (`id`),
KEY `Id_Trabajador` (`workerFk`),
KEY `Id_Cliente` (`clientFk`),
KEY `clientObservation_created_IDX` (`created`) USING BTREE,
KEY `clientObservation_fk_editor` (`editorFk`),
+ KEY `clientObservationTypeFk` (`observationTypeFk`),
+ CONSTRAINT `clientObservationTypeFk` FOREIGN KEY (`observationTypeFk`) REFERENCES `observationType` (`id`),
CONSTRAINT `clientObservation_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
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
@@ -28798,7 +28175,6 @@ DROP TABLE IF EXISTS `clientType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientType` (
- `id__` int(11) NOT NULL COMMENT '@deprecated 2024-02-20 refs #6784',
`code` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`type` varchar(45) NOT NULL,
`isCreatedAsServed` tinyint(1) DEFAULT 0,
@@ -28852,7 +28228,6 @@ DROP TABLE IF EXISTS `cmr`;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cmr` (
`id` int(11) NOT NULL AUTO_INCREMENT,
- `ticketFk__` int(11) DEFAULT NULL COMMENT '@deprecated 2023-10-20 refs #6092',
`truckPlate` varchar(30) DEFAULT NULL,
`observations` varchar(255) DEFAULT NULL,
`senderInstruccions` varchar(255) DEFAULT NULL,
@@ -28869,14 +28244,12 @@ CREATE TABLE `cmr` (
`landed` datetime DEFAULT NULL COMMENT 'Hora de llegada a destino',
`ead` datetime DEFAULT NULL COMMENT 'Estimated Arriving Date',
PRIMARY KEY (`id`),
- KEY `cmr_fk1_idx` (`ticketFk__`),
KEY `cmr_fk2_idx` (`companyFk`),
KEY `cmr_fk3_idx` (`addressToFk`),
KEY `cm_fk4_idx` (`supplierFk`),
KEY `cmr_FK` (`addressFromFk`),
CONSTRAINT `cmrCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `cmr_FK` FOREIGN KEY (`addressFromFk`) REFERENCES `address` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `cmr_fk1` FOREIGN KEY (`ticketFk__`) REFERENCES `ticket` (`id`),
CONSTRAINT `cmr_fk3` FOREIGN KEY (`addressToFk`) REFERENCES `address` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `cmr_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
@@ -29017,7 +28390,7 @@ DROP TABLE IF EXISTS `collectionWagon`;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `collectionWagon` (
`collectionFk` int(11) NOT NULL,
- `wagonFk` varchar(6) NOT NULL,
+ `wagonFk` int(11) unsigned NOT NULL,
`position` int(11) unsigned NOT NULL,
PRIMARY KEY (`collectionFk`,`position`),
UNIQUE KEY `collectionWagon_unique` (`collectionFk`,`wagonFk`),
@@ -29036,7 +28409,7 @@ DROP TABLE IF EXISTS `collectionWagonTicket`;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `collectionWagonTicket` (
`ticketFk` int(11) NOT NULL,
- `wagonFk` varchar(6) NOT NULL,
+ `wagonFk` int(11) unsigned NOT NULL,
`trayFk` int(11) unsigned NOT NULL,
`side` set('L','R') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`rgb` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT 'Color de la balda',
@@ -29046,7 +28419,7 @@ CREATE TABLE `collectionWagonTicket` (
KEY `collectionWagonTicket_FK_1` (`wagonFk`),
CONSTRAINT `collectionWagonTicket_FK` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON UPDATE CASCADE,
CONSTRAINT `collectionWagonTicket_FK_1` FOREIGN KEY (`wagonFk`) REFERENCES `wagon` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `collectionWagonTicket_tray` FOREIGN KEY (`trayFk`) REFERENCES `wagonTypeTray` (`id`) ON UPDATE CASCADE
+ CONSTRAINT `collectionWagonTicket_tray` FOREIGN KEY (`trayFk`) REFERENCES `wagonTypeTray` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -29102,7 +28475,6 @@ CREATE TABLE `company` (
`stamp` longblob DEFAULT NULL,
`created` timestamp NOT NULL ON UPDATE current_timestamp(),
`clientFk` int(11) DEFAULT NULL,
- `sage200Company__` int(2) DEFAULT NULL COMMENT '@deprecated 06/03/2024',
`supplierAccountFk` mediumint(8) unsigned DEFAULT NULL COMMENT 'Cuenta por defecto para ingresos desde este pais',
`isDefaulter` tinyint(4) NOT NULL DEFAULT 0,
`companyGroupFk` int(11) NOT NULL DEFAULT 1 COMMENT 'usado para calcular los greuges ',
@@ -29534,22 +28906,6 @@ CREATE TABLE `conveyorType` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
---
--- Table structure for table `coolerPathDetail__`
---
-
-DROP TABLE IF EXISTS `coolerPathDetail__`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `coolerPathDetail__` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `coolerPathFk` int(11) NOT NULL DEFAULT 1,
- `hallway` varchar(3) NOT NULL,
- PRIMARY KEY (`coolerPathFk`,`hallway`),
- UNIQUE KEY `cooler_path_detail_id_UNIQUE` (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Table structure for table `corridor`
--
@@ -29579,7 +28935,6 @@ CREATE TABLE `country` (
`code` varchar(2) NOT NULL,
`viesCode` varchar(2) DEFAULT NULL,
`currencyFk` tinyint(3) unsigned NOT NULL DEFAULT 1,
- `politicalCountryFk__` mediumint(8) unsigned DEFAULT NULL COMMENT 'Pais Real(apaño por culpa del España Exento)',
`geoFk` int(11) DEFAULT NULL,
`hasDailyInvoice` tinyint(4) NOT NULL DEFAULT 0,
`isUeeMember` tinyint(4) NOT NULL DEFAULT 0,
@@ -29589,13 +28944,11 @@ CREATE TABLE `country` (
`isSocialNameUnique` tinyint(1) NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
UNIQUE KEY `country_unique` (`code`),
- KEY `Id_Paisreal` (`politicalCountryFk__`),
KEY `currency_id_fk_idx` (`currencyFk`),
KEY `country_Ix4` (`name`),
KEY `continent_id_fk_idx` (`continentFk`),
KEY `country_FK_1` (`geoFk`),
CONSTRAINT `continent_id_fk` FOREIGN KEY (`continentFk`) REFERENCES `continent` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
- CONSTRAINT `country_FK` FOREIGN KEY (`politicalCountryFk__`) REFERENCES `country` (`id`) ON UPDATE CASCADE,
CONSTRAINT `country_FK_1` FOREIGN KEY (`geoFk`) REFERENCES `zoneGeo` (`id`) ON UPDATE CASCADE,
CONSTRAINT `currency_id_fk` FOREIGN KEY (`currencyFk`) REFERENCES `currency` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
@@ -29699,15 +29052,12 @@ DROP TABLE IF EXISTS `creditInsurance`;
/*!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,
`creditClassificationFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
- KEY `CreditInsurance_Fk1_idx` (`creditClassification`),
KEY `creditInsurance_creditClassificationFk` (`creditClassificationFk`),
- CONSTRAINT `CreditInsurance_Fk1` FOREIGN KEY (`creditClassification`) REFERENCES `creditClassification` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `creditInsurance_creditClassificationFk` FOREIGN KEY (`creditClassificationFk`) REFERENCES `creditClassification` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Detalla los clientes que tienen seguro de credito';
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -29841,7 +29191,6 @@ CREATE TABLE `deliveryNote` (
`supervisorFk` int(10) unsigned NOT NULL,
`departmentFk` int(11) NOT NULL,
`invoiceInFk` mediumint(8) unsigned DEFAULT NULL,
- `farmingFk__` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_albaran_Proveedores_idx` (`supplierFk`),
KEY `fk_albaran_empresa1_idx` (`companyFk`),
@@ -29851,9 +29200,7 @@ CREATE TABLE `deliveryNote` (
KEY `fk_albaran_Trabajadores2_idx` (`supervisorFk`),
KEY `fk_albaran_department1_idx` (`departmentFk`),
KEY `fk_albaran_recibida_idx` (`invoiceInFk`),
- KEY `albaran_FK` (`farmingFk__`),
CONSTRAINT `albaranCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `albaran_FK` FOREIGN KEY (`farmingFk__`) REFERENCES `farming` (`id`),
CONSTRAINT `albaran_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE,
CONSTRAINT `fk_albaran_Trabajadores1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `fk_albaran_Trabajadores2` FOREIGN KEY (`supervisorFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
@@ -30130,6 +29477,7 @@ CREATE TABLE `deviceProductionLog` (
KEY `userFk` (`userFk`),
KEY `deviceProductionLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `deviceProductionLog_deviceProductionLog` (`originFk`,`creationDate`),
+ KEY `deviceProductionLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `deviceProductionUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -30268,7 +29616,6 @@ CREATE TABLE `dmsType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(45) NOT NULL,
`name` varchar(45) NOT NULL,
- `path__` varchar(255) NOT NULL COMMENT '@deprecated 2024-01-08 refs #6410',
`writeRoleFk` int(10) unsigned DEFAULT NULL,
`readRoleFk` int(10) unsigned DEFAULT NULL,
`monthToDelete` int(10) unsigned DEFAULT NULL COMMENT 'Meses en el pasado para ir borrando registros, dejar a null para no borrarlos nunca',
@@ -30327,6 +29674,10 @@ CREATE TABLE `docuwareConfig` (
`id` int(10) unsigned NOT NULL,
`url` varchar(75) DEFAULT NULL,
`cookie` varchar(1000) DEFAULT NULL,
+ `username` varchar(100) DEFAULT NULL,
+ `password` varchar(100) DEFAULT NULL,
+ `token` text DEFAULT NULL,
+ `expired` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `docuwareConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
@@ -30356,7 +29707,6 @@ DROP TABLE IF EXISTS `dua`;
CREATE TABLE `dua` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(45) DEFAULT NULL,
- `awbFk__` smallint(11) unsigned DEFAULT NULL COMMENT '@Deprecated refs #5871 01/10/2023',
`issued` date DEFAULT NULL,
`operated` date DEFAULT NULL,
`booked` date DEFAULT NULL,
@@ -30365,9 +29715,9 @@ CREATE TABLE `dua` (
`customsValue` decimal(10,2) DEFAULT NULL,
`companyFk` int(10) unsigned NOT NULL DEFAULT 442,
`ASIEN` double DEFAULT NULL,
+ `comment` text DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code_UNIQUE` (`code`),
- KEY `fk_awb_dua_awb_idx` (`awbFk__`),
KEY `fk_dua_gestdoc1_idx` (`gestdocFk`),
KEY `dua_fk4_idx` (`companyFk`),
CONSTRAINT `duaCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
@@ -30428,7 +29778,7 @@ CREATE TABLE `duaInvoiceIn` (
`duaFk` int(11) NOT NULL,
`invoiceInFk` mediumint(8) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
- UNIQUE KEY `duaFk_UNIQUE` (`duaFk`,`invoiceInFk`),
+ UNIQUE KEY `duaInvoiceIn_unique` (`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,
@@ -30610,7 +29960,7 @@ CREATE TABLE `entry` (
`isExcludedFromAvailable` tinyint(1) NOT NULL DEFAULT 0,
`isConfirmed` tinyint(1) NOT NULL DEFAULT 0,
`isOrdered` tinyint(1) NOT NULL DEFAULT 0,
- `isRaid` tinyint(1) NOT NULL DEFAULT 0,
+ `isRaid_` tinyint(1) NOT NULL DEFAULT 0 COMMENT '@deprecated 2024-11-05',
`commission` float DEFAULT 0,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`evaNotes` varchar(45) DEFAULT NULL,
@@ -30619,7 +29969,6 @@ CREATE TABLE `entry` (
`companyFk` int(10) unsigned NOT NULL DEFAULT 442,
`gestDocFk` int(11) DEFAULT NULL,
`invoiceInFk` mediumint(8) unsigned DEFAULT NULL,
- `isBlocked__` tinyint(4) NOT NULL DEFAULT 0 COMMENT '@deprecated 27/03/2024',
`loadPriority` int(11) DEFAULT NULL,
`kop` int(11) DEFAULT NULL,
`sub` mediumint(8) unsigned DEFAULT NULL,
@@ -30719,6 +30068,7 @@ CREATE TABLE `entryLog` (
KEY `entryLog_ibfk_2` (`userFk`),
KEY `entryLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `entryLog_originFk` (`originFk`,`creationDate`),
+ KEY `entryLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `entryLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -30777,17 +30127,17 @@ CREATE TABLE `entryType` (
/*!40101 SET character_set_client = @saved_cs_client */;
--
--- Table structure for table `entryVirtual`
+-- Table structure for table `entryVirtual__`
--
-DROP TABLE IF EXISTS `entryVirtual`;
+DROP TABLE IF EXISTS `entryVirtual__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `entryVirtual` (
+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=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='entradas que se van moviendo automaticamente al futuro';
+ CONSTRAINT `entryVirtual___ibfk_1` FOREIGN KEY (`entryFk`) REFERENCES `entry` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='@deprecated 2024-11-05';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -31014,7 +30364,6 @@ CREATE TABLE `expedition` (
`ticketFk` int(10) NOT NULL,
`freightItemFk` int(11) DEFAULT 1 COMMENT 'itemFk del artículo que nos va a facturar el proveedor de transporte.',
`created` timestamp NULL DEFAULT current_timestamp(),
- `itemFk__` int(11) DEFAULT NULL COMMENT 'Si es necesario el itemFk del cubo, se obtiene mediante packagingFk, join packing.itemFk',
`counter` smallint(5) unsigned NOT NULL,
`workerFk` int(10) unsigned DEFAULT NULL,
`externalId` varchar(20) DEFAULT NULL,
@@ -31255,6 +30604,7 @@ CREATE TABLE `expeditionState` (
`typeFk` int(11) NOT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`isScanned` tinyint(1) NOT NULL DEFAULT 0,
+ `scanOrder` int(11) DEFAULT NULL COMMENT 'Indica la posición al cargar la furgoneta',
PRIMARY KEY (`id`),
KEY `expeditionState_FK` (`expeditionFk`),
KEY `expeditionState_FK_1` (`typeFk`),
@@ -31588,29 +30938,6 @@ CREATE TABLE `floramondoConfig` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
---
--- Table structure for table `forecastedBalance__`
---
-
-DROP TABLE IF EXISTS `forecastedBalance__`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `forecastedBalance__` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `description` varchar(45) DEFAULT NULL,
- `amount` double NOT NULL DEFAULT 0,
- `dated` date NOT NULL,
- `accountingFk` int(11) DEFAULT NULL,
- `companyFk` int(10) unsigned NOT NULL DEFAULT 442,
- PRIMARY KEY (`id`),
- KEY `Fecha_indice` (`dated`),
- KEY `banco_prevision_idx` (`accountingFk`),
- KEY `empresa_prevision_idx` (`companyFk`),
- CONSTRAINT `Saldos_PrevisionCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `banco_prevision` FOREIGN KEY (`accountingFk`) REFERENCES `accounting` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='@deprecated 2024-05-21';
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Table structure for table `franceExpressConfig`
--
@@ -32317,6 +31644,7 @@ CREATE TABLE `invoiceInLog` (
KEY `userFk` (`userFk`),
KEY `invoiceInLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `invoiceInLog_originFk` (`originFk`,`creationDate`),
+ KEY `invoiceInLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `invoiceInLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -32649,14 +31977,12 @@ CREATE TABLE `item` (
`itemPackingTypeFk` varchar(1) DEFAULT NULL,
`packingOut` decimal(10,2) DEFAULT NULL COMMENT 'cantidad que cabe en una caja de verdnatura',
`genericFk` int(11) DEFAULT NULL COMMENT 'Item genérico',
- `packingShelve__` int(11) DEFAULT NULL COMMENT '@deprecated 2024-31-01',
`isLaid` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Indica si el producto se puede tumbar a efectos del transporte desde Holanda',
`lastUsed` datetime DEFAULT current_timestamp(),
`weightByPiece` int(10) unsigned DEFAULT NULL COMMENT 'peso por defecto para un articulo por tallo/unidad',
`editorFk` int(10) unsigned DEFAULT NULL,
`recycledPlastic` decimal(10,2) DEFAULT NULL,
`nonRecycledPlastic` decimal(10,2) DEFAULT NULL,
- `minQuantity__` int(10) unsigned DEFAULT NULL COMMENT '@deprecated 2024-07-11 refs #7704 Cantidad mínima para una línea de venta',
`isBoxPickingMode` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'FALSE: using item.packingOut TRUE: boxPicking using itemShelving.packing',
`photoMotivation` varchar(255) DEFAULT NULL,
`tag11` varchar(20) DEFAULT NULL,
@@ -32720,6 +32046,21 @@ CREATE TABLE `itemBarcode` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `itemBaseTag`
+--
+
+DROP TABLE IF EXISTS `itemBaseTag`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `itemBaseTag` (
+ `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
+ `name` varchar(50) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `name_UNIQUE` (`name`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `itemBotanical`
--
@@ -32756,6 +32097,42 @@ SET character_set_client = utf8;
1 AS `ediBotanic` */;
SET character_set_client = @saved_cs_client;
+--
+-- Table structure for table `itemBreederTag`
+--
+
+DROP TABLE IF EXISTS `itemBreederTag`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `itemBreederTag` (
+ `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
+ `name` varchar(50) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `name_UNIQUE` (`name`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `itemCampaign`
+--
+
+DROP TABLE IF EXISTS `itemCampaign`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `itemCampaign` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `dated` date NOT NULL,
+ `itemFk` int(11) NOT NULL,
+ `quantity` decimal(10,2) NOT NULL,
+ `total` decimal(10,2) NOT NULL,
+ `campaign` varchar(100) NOT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `itemCampaign_UNIQUE` (`dated`,`itemFk`),
+ KEY `itemCampaign_item_FK` (`itemFk`),
+ CONSTRAINT `itemCampaign_item_FK` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tallos confirmados por día en los días de más producción de una campaña. La tabla está pensada para que sea una foto.';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `itemCategory`
--
@@ -32857,6 +32234,7 @@ CREATE TABLE `itemConfig` (
`defaultPriority` int(11) NOT NULL DEFAULT 2,
`warehouseFk` smallint(6) unsigned DEFAULT NULL,
`downloadMaxAttempts` tinyint(3) DEFAULT NULL COMMENT 'Intentos máximos para que se borre',
+ `defaultPackingTypeFk` varchar(1) DEFAULT 'H',
PRIMARY KEY (`id`),
KEY `itemConfig_FK` (`defaultTag`),
CONSTRAINT `itemConfig_FK` FOREIGN KEY (`defaultTag`) REFERENCES `tag` (`id`),
@@ -32940,6 +32318,21 @@ CREATE TABLE `itemFamily` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `itemFarmingTag`
+--
+
+DROP TABLE IF EXISTS `itemFarmingTag`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `itemFarmingTag` (
+ `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
+ `name` varchar(50) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `name_UNIQUE` (`name`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `itemImageQueue`
--
@@ -32991,6 +32384,21 @@ CREATE TABLE `itemLabel` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `itemLanguageTag`
+--
+
+DROP TABLE IF EXISTS `itemLanguageTag`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `itemLanguageTag` (
+ `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
+ `name` varchar(50) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `name_UNIQUE` (`name`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `itemLog`
--
@@ -33015,6 +32423,7 @@ CREATE TABLE `itemLog` (
KEY `itemLogUserFk_idx` (`userFk`),
KEY `itemLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `itemLog_originFk` (`originFk`,`creationDate`),
+ KEY `itemLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `itemLogUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -33192,7 +32601,7 @@ DROP TABLE IF EXISTS `itemShelving`;
CREATE TABLE `itemShelving` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`itemFk` int(11) NOT NULL,
- `shelvingFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
+ `shelvingFk` int(11) NOT NULL,
`visible` int(11) NOT NULL DEFAULT 0,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`grouping` smallint(5) unsigned DEFAULT NULL,
@@ -33204,6 +32613,7 @@ CREATE TABLE `itemShelving` (
`editorFk` int(10) unsigned DEFAULT NULL,
`available` int(11) DEFAULT NULL,
`isSplit` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Este valor cambia al splitar un carro que se ha quedado en holanda',
+ `movingState` enum('selected','printed') DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `itemShelving_fk1_idx` (`itemFk`),
KEY `itemShelving_fk2_idx` (`shelvingFk`),
@@ -33212,8 +32622,8 @@ CREATE TABLE `itemShelving` (
KEY `itemShelvingBuy_FK` (`buyFk`),
CONSTRAINT `itemShelvingBuy_FK` FOREIGN KEY (`buyFk`) REFERENCES `buy` (`id`),
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
+ CONSTRAINT `itemShelving_fk3` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `itemShelving_shelving_FK` FOREIGN KEY (`shelvingFk`) REFERENCES `shelving` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 */;
@@ -33235,7 +32645,6 @@ SET character_set_client = utf8;
1 AS `concept`,
1 AS `size`,
1 AS `Estado`,
- 1 AS `sectorProdPriority`,
1 AS `available`,
1 AS `sectorFk`,
1 AS `matricula`,
@@ -33273,13 +32682,13 @@ SET character_set_client = utf8;
SET character_set_client = @saved_cs_client;
--
--- Table structure for table `itemShelvingLog`
+-- Table structure for table `itemShelvingLog__`
--
-DROP TABLE IF EXISTS `itemShelvingLog`;
+DROP TABLE IF EXISTS `itemShelvingLog__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `itemShelvingLog` (
+CREATE TABLE `itemShelvingLog__` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`itemShelvingFk` int(10) unsigned DEFAULT NULL,
`workerFk` int(11) DEFAULT NULL,
@@ -33297,7 +32706,7 @@ CREATE TABLE `itemShelvingLog` (
KEY `itemShelving_Log_FK` (`itemShelvingFk`),
KEY `itemShelvingLog_itemFk_IDX` (`itemFk`) USING BTREE,
KEY `itemShelvingLog_shelvingFk_IDX` (`shelvingFk`) USING BTREE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='@deprecated 2024-11-26';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -33472,6 +32881,36 @@ SET character_set_client = utf8;
1 AS `removed` */;
SET character_set_client = @saved_cs_client;
+--
+-- Table structure for table `itemStateTag`
+--
+
+DROP TABLE IF EXISTS `itemStateTag`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `itemStateTag` (
+ `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
+ `name` varchar(50) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `name_UNIQUE` (`name`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `itemStemTag`
+--
+
+DROP TABLE IF EXISTS `itemStemTag`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `itemStemTag` (
+ `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
+ `name` varchar(50) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `name_UNIQUE` (`name`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `itemTag`
--
@@ -33562,6 +33001,21 @@ SET character_set_client = utf8;
1 AS `taxClassFk` */;
SET character_set_client = @saved_cs_client;
+--
+-- Table structure for table `itemTextureTag`
+--
+
+DROP TABLE IF EXISTS `itemTextureTag`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `itemTextureTag` (
+ `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
+ `name` varchar(50) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `name_UNIQUE` (`name`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Temporary table structure for view `itemTicketOut`
--
@@ -33599,20 +33053,10 @@ CREATE TABLE `itemType` (
`workerFk` int(10) unsigned 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(),
- `transaction__` tinyint(4) NOT NULL DEFAULT 0,
`making` int(10) unsigned DEFAULT NULL COMMENT 'Son productos de confección propia',
- `location__` varchar(10) DEFAULT NULL,
`life` smallint(5) unsigned DEFAULT NULL,
- `maneuver__` double NOT NULL DEFAULT 0.21 COMMENT '@deprecated 2024-07-01 refs #7418',
- `target__` double NOT NULL DEFAULT 0.15 COMMENT '@deprecated 2024-07-01 refs #7418',
- `topMargin__` double NOT NULL DEFAULT 0.3 COMMENT '@deprecated 2024-07-01 refs #7418',
- `profit__` double NOT NULL DEFAULT 0.02 COMMENT '@deprecated 2024-07-01 refs #7418',
- `density__` double NOT NULL DEFAULT 167 COMMENT '@deprecated 2024-07-01 refs #7418 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,
`isPackaging` tinyint(1) NOT NULL DEFAULT 0,
- `hasComponents__` tinyint(1) NOT NULL DEFAULT 1,
- `warehouseFk__` smallint(6) unsigned NOT NULL DEFAULT 60,
- `compression__` decimal(5,2) DEFAULT 1.00,
`itemPackingTypeFk` varchar(1) DEFAULT NULL,
`temperatureFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`isUnconventionalSize` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'familia con productos cuyas medidas no son aptas para la cinta transportadora o paletizar',
@@ -33620,19 +33064,22 @@ CREATE TABLE `itemType` (
`maxRefs` int(10) unsigned DEFAULT NULL COMMENT 'Indica el número máximo de referencias',
`isMergeable` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'Articulos que al mergear los tickets se fusionara la linea',
`isFragile` tinyint(1) NOT NULL DEFAULT 0,
+ `editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `Tipo_UNIQUE` (`name`,`categoryFk`),
UNIQUE KEY `itemType_UN` (`code`),
KEY `Trabajador` (`workerFk`),
KEY `reino_id` (`categoryFk`),
KEY `Tipos_fk3_idx` (`making`),
- KEY `warehouseFk5_idx` (`warehouseFk__`),
KEY `temperatureFk` (`temperatureFk`),
+ KEY `itemType_user_FK` (`editorFk`),
+ KEY `itemType_itemPackingType_FK` (`itemPackingTypeFk`),
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 `temperatureFk` FOREIGN KEY (`temperatureFk`) REFERENCES `temperature` (`code`),
- CONSTRAINT `warehouseFk5` FOREIGN KEY (`warehouseFk__`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE
+ CONSTRAINT `itemType_itemPackingType_FK` FOREIGN KEY (`itemPackingTypeFk`) REFERENCES `itemPackingType` (`code`) ON UPDATE CASCADE,
+ CONSTRAINT `itemType_user_FK` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
+ CONSTRAINT `temperatureFk` FOREIGN KEY (`temperatureFk`) REFERENCES `temperature` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 */;
@@ -33664,6 +33111,35 @@ SET character_set_client = utf8;
1 AS `name` */;
SET character_set_client = @saved_cs_client;
+--
+-- Table structure for table `itemTypeLog`
+--
+
+DROP TABLE IF EXISTS `itemTypeLog`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `itemTypeLog` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `originFk` int(11) DEFAULT NULL,
+ `userFk` int(10) unsigned DEFAULT NULL,
+ `action` set('insert','update','delete') NOT NULL,
+ `creationDate` timestamp NULL DEFAULT current_timestamp(),
+ `description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
+ `changedModel` enum('ItemType') NOT NULL DEFAULT 'ItemType',
+ `oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
+ `newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
+ `changedModelId` int(11) NOT NULL,
+ `changedModelValue` varchar(45) DEFAULT NULL,
+ `summaryId` varchar(30) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `itemTypeLogUserFk_idx` (`userFk`),
+ KEY `itemTypeLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
+ KEY `itemTypeLog_originFk` (`originFk`,`creationDate`),
+ KEY `itemTypeLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
+ CONSTRAINT `itemTypeLogUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `itemTypeRestriction`
--
@@ -33704,6 +33180,36 @@ CREATE TABLE `itemTypeTag` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `itemVatRateTag`
+--
+
+DROP TABLE IF EXISTS `itemVatRateTag`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `itemVatRateTag` (
+ `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
+ `name` varchar(50) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `name_UNIQUE` (`name`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `itemWrappingTag`
+--
+
+DROP TABLE IF EXISTS `itemWrappingTag`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `itemWrappingTag` (
+ `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
+ `name` varchar(50) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `name_UNIQUE` (`name`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Temporary table structure for view `item_Free_Id`
--
@@ -33839,9 +33345,7 @@ DROP TABLE IF EXISTS `ledgerConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ledgerConfig` (
- `lastBookEntry__` int(11) NOT NULL COMMENT '@deprecated 2024-05-28 refs #7400 Modificar contador asientos contables',
- `maxTolerance` decimal(10,2) NOT NULL,
- PRIMARY KEY (`lastBookEntry__`)
+ `maxTolerance` decimal(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -33960,13 +33464,28 @@ CREATE TABLE `machineDms` (
/*!40101 SET character_set_client = @saved_cs_client */;
--
--- Table structure for table `machineWorker`
+-- Table structure for table `machineWorkerConfig__`
--
-DROP TABLE IF EXISTS `machineWorker`;
+DROP TABLE IF EXISTS `machineWorkerConfig__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `machineWorker` (
+CREATE TABLE `machineWorkerConfig__` (
+ `id` int(10) unsigned NOT NULL,
+ `maxHours` smallint(5) unsigned NOT NULL COMMENT 'Indicates how many hours a user record is reviewed to update or insert',
+ PRIMARY KEY (`id`),
+ CONSTRAINT `machineWorkerConfig_check` CHECK (`id` = 1)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='@deprecated 2024-10-23 not used';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `machineWorker__`
+--
+
+DROP TABLE IF EXISTS `machineWorker__`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `machineWorker__` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`workerFk` int(10) unsigned NOT NULL,
`machineFk` int(11) NOT NULL,
@@ -33977,22 +33496,7 @@ CREATE TABLE `machineWorker` (
KEY `machineWorker_FK` (`workerFk`),
CONSTRAINT `machineWorker_FK` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `machineWorker_FK_1` FOREIGN KEY (`machineFk`) REFERENCES `machine` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Registros horarios de vehículos de almacén por empleado';
-/*!40101 SET character_set_client = @saved_cs_client */;
-
---
--- Table structure for table `machineWorkerConfig`
---
-
-DROP TABLE IF EXISTS `machineWorkerConfig`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `machineWorkerConfig` (
- `id` int(10) unsigned NOT NULL,
- `maxHours` smallint(5) unsigned NOT NULL COMMENT 'Indicates how many hours a user record is reviewed to update or insert',
- PRIMARY KEY (`id`),
- CONSTRAINT `machineWorkerConfig_check` CHECK (`id` = 1)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='@deprecated 2024-10-23 not used';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -34558,6 +34062,7 @@ CREATE TABLE `operator` (
`volumeLimit` decimal(10,6) DEFAULT 0.500000 COMMENT 'Límite de volumen en una colección para la asignación de pedidos',
`sizeLimit` int(10) unsigned DEFAULT NULL COMMENT 'Límite de altura en una colección para la asignación de pedidos',
`isOnReservationMode` tinyint(1) NOT NULL DEFAULT 0,
+ `machineFk` int(11) DEFAULT NULL,
PRIMARY KEY (`workerFk`),
KEY `operator_FK` (`workerFk`),
KEY `operator_FK_1` (`trainFk`),
@@ -34565,11 +34070,13 @@ CREATE TABLE `operator` (
KEY `operator_FK_3` (`warehouseFk`),
KEY `operator_FK_5` (`labelerFk`),
KEY `operator_FK_4` (`sectorFk`),
+ KEY `operator_machine_FK` (`machineFk`),
CONSTRAINT `operator_FK` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `operator_FK_1` FOREIGN KEY (`trainFk`) REFERENCES `train` (`id`) ON UPDATE CASCADE,
CONSTRAINT `operator_FK_2` FOREIGN KEY (`itemPackingTypeFk`) REFERENCES `itemPackingType` (`code`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `operator_FK_3` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT `operator_FK_4` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON UPDATE CASCADE
+ CONSTRAINT `operator_FK_4` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `operator_machine_FK` FOREIGN KEY (`machineFk`) REFERENCES `machine` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -34791,6 +34298,7 @@ CREATE TABLE `packaging` (
`isTrolley` tinyint(1) NOT NULL DEFAULT 0,
`isPallet` tinyint(1) NOT NULL DEFAULT 0,
`isPlantTray` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'The container is a plant tray. Used to restrict the picking of full plant trays, to make previous picking.',
+ `isActive` tinyint(1) DEFAULT 1,
PRIMARY KEY (`id`),
KEY `packaging_fk1` (`itemFk`),
KEY `packaging_fk2_idx` (`freightItemFk`),
@@ -34984,6 +34492,7 @@ CREATE TABLE `packingSiteDeviceLog` (
KEY `userFk` (`userFk`),
KEY `packingSiteDeviceLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `packingSiteDeviceLog_packingSiteDeviceLog` (`originFk`,`creationDate`),
+ KEY `packingSiteDeviceLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `packingSiteDeviceLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -35065,7 +34574,7 @@ CREATE TABLE `parking` (
PRIMARY KEY (`id`),
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,
+ CONSTRAINT `parking_fk1` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON UPDATE CASCADE,
CONSTRAINT `chkParkingCodeFormat` CHECK (char_length(`code`) > 4 and `code` regexp '^[^ ]+-[^ ]+$')
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla con los parkings del altillo';
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -35094,6 +34603,7 @@ CREATE TABLE `parkingLog` (
KEY `logParkinguserFk` (`userFk`),
KEY `parkingLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `parkingLog_originFk` (`originFk`,`creationDate`),
+ KEY `parkingLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `parkingOriginFk` FOREIGN KEY (`originFk`) REFERENCES `parking` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `parkingUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
@@ -35267,15 +34777,7 @@ DROP TABLE IF EXISTS `payrollWorkCenter`;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payrollWorkCenter` (
`workCenterFkA3` int(11) NOT NULL COMMENT 'Columna que hace referencia a A3.',
- `Centro__` varchar(255) NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
- `nss_cotizacion__` varchar(15) NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
- `domicilio__` varchar(255) NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
- `poblacion__` varchar(45) NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
- `cp__` varchar(5) NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
- `empresa_id__` int(10) NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
- `companyFkA3` int(11) DEFAULT NULL COMMENT 'Columna que hace referencia a A3.',
- PRIMARY KEY (`workCenterFkA3`,`empresa_id__`),
- KEY `payroll_centros_ix1` (`empresa_id__`)
+ `companyFkA3` int(11) DEFAULT NULL COMMENT 'Columna que hace referencia a A3.'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -35288,17 +34790,10 @@ DROP TABLE IF EXISTS `payrollWorker`;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payrollWorker` (
`workerFkA3` int(11) NOT NULL COMMENT 'Columna que hace referencia a A3.',
- `nss__` varchar(23) NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
- `codpuesto__` int(10) NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
`companyFkA3` int(10) NOT NULL COMMENT 'Columna que hace referencia a A3.',
- `codcontrato__` int(10) NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
- `FAntiguedad__` date NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
`grupotarifa` int(10) NOT NULL,
- `codcategoria__` int(10) NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
- `ContratoTemporal__` tinyint(1) NOT NULL DEFAULT 0 COMMENT '@Deprecated refs #6738 15/03/2024',
`workerFk` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`workerFkA3`,`companyFkA3`),
- KEY `sajvgfh_idx` (`codpuesto__`),
KEY `payroll_employee_workerFk_idx` (`workerFk`),
CONSTRAINT `payroll_employee_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
@@ -35655,6 +35150,45 @@ CREATE TABLE `ppePlan` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Plan de amortizacion para la tabla ppe';
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `priceDelta`
+--
+
+DROP TABLE IF EXISTS `priceDelta`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `priceDelta` (
+ `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
+ `itemTypeFk` smallint(5) unsigned NOT NULL,
+ `minSize` int(10) unsigned DEFAULT NULL COMMENT 'Minimum item.size',
+ `maxSize` int(10) unsigned DEFAULT NULL COMMENT 'Maximum item.size',
+ `inkFk` varchar(3) DEFAULT NULL,
+ `originFk` tinyint(2) unsigned DEFAULT NULL,
+ `producerFk` mediumint(3) unsigned DEFAULT NULL,
+ `fromDated` date DEFAULT NULL,
+ `toDated` date DEFAULT NULL,
+ `absIncreasing` decimal(10,3) DEFAULT NULL COMMENT 'Absolute increasing of final price',
+ `ratIncreasing` int(11) DEFAULT NULL COMMENT 'Increasing ratio for the cost price',
+ `warehouseFk` smallint(6) unsigned NOT NULL,
+ `created` timestamp NOT NULL DEFAULT current_timestamp(),
+ `editorFk` int(10) unsigned DEFAULT NULL,
+ `zoneGeoFk` int(11) DEFAULT NULL COMMENT 'Application area for the bonus component',
+ PRIMARY KEY (`id`),
+ KEY `priceDelta_itemType_FK` (`itemTypeFk`),
+ KEY `priceDelta_ink_FK` (`inkFk`),
+ KEY `priceDelta_producer_FK` (`producerFk`),
+ KEY `priceDelta_warehouse_FK` (`warehouseFk`),
+ KEY `priceDelta_worker_FK` (`editorFk`),
+ KEY `priceDelta_zoneGeo_FK` (`zoneGeoFk`),
+ CONSTRAINT `priceDelta_ink_FK` FOREIGN KEY (`inkFk`) REFERENCES `ink` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `priceDelta_itemType_FK` FOREIGN KEY (`itemTypeFk`) REFERENCES `itemType` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `priceDelta_producer_FK` FOREIGN KEY (`producerFk`) REFERENCES `producer` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `priceDelta_warehouse_FK` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `priceDelta_worker_FK` FOREIGN KEY (`editorFk`) REFERENCES `worker` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT `priceDelta_zoneGeo_FK` FOREIGN KEY (`zoneGeoFk`) REFERENCES `zoneGeo` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Defines the increasing o decreasing for ranges of items';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `priceFixed`
--
@@ -35870,8 +35404,8 @@ CREATE TABLE `productionConfig` (
`sectorToCode` varchar(15) DEFAULT NULL COMMENT 'Sector destino que se revisa ítems más nuevos al parkinear',
`orderMode` enum('Location','Age') NOT NULL DEFAULT 'Location',
`editorFk` int(10) unsigned DEFAULT NULL,
- `hasNewLabelMrwMethod` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'column to activate the new mrw integration',
`minPlantTrayLength` int(11) NOT NULL DEFAULT 53 COMMENT 'minimum length for plant tray restriction. Avoid to make collection of the ticket with this kind of item',
+ `itemOrderReviewHours` int(11) DEFAULT 24 COMMENT 'Horas que no se tienen en cuenta para comprobar orden en el almacén, null para desactivar revisión',
PRIMARY KEY (`id`),
KEY `productionConfig_FK` (`shortageAddressFk`),
KEY `productionConfig_FK_1` (`clientSelfConsumptionFk`),
@@ -35913,6 +35447,7 @@ CREATE TABLE `productionConfigLog` (
KEY `productionConfigLog_userFk` (`userFk`),
KEY `productionConfigLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `productionConfigLog_originFk` (`originFk`,`creationDate`),
+ KEY `productionConfigLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `productionConfigUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -36359,6 +35894,7 @@ CREATE TABLE `rateLog` (
KEY `logRateuserFk` (`userFk`),
KEY `rateLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `rateLog_originFk` (`originFk`,`creationDate`),
+ KEY `rateLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `rateUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -36694,7 +36230,7 @@ CREATE TABLE `route` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`workerFk` int(10) unsigned DEFAULT NULL,
`firstEditorFk` int(10) unsigned DEFAULT NULL,
- `created` date NOT NULL,
+ `created` timestamp NOT NULL DEFAULT current_timestamp(),
`vehicleFk` int(10) unsigned DEFAULT NULL,
`agencyModeFk` int(11) DEFAULT NULL,
`time` datetime DEFAULT NULL,
@@ -36713,6 +36249,7 @@ CREATE TABLE `route` (
`beachFk` int(11) DEFAULT NULL,
`commissionWorkCenterFk` int(11) DEFAULT NULL COMMENT 'WorkerCenter que gestiona la ruta',
`editorFk` int(10) unsigned DEFAULT NULL,
+ `dated` date NOT NULL,
PRIMARY KEY (`id`),
KEY `Id_Agencia` (`agencyModeFk`),
KEY `Fecha` (`created`),
@@ -36772,10 +36309,14 @@ CREATE TABLE `routeCommission` (
`cat4m3` decimal(5,2) DEFAULT NULL,
`cat5m3` decimal(5,2) DEFAULT NULL,
`freelanceYearlyM3` decimal(5,2) DEFAULT NULL,
+ `countryFk` mediumint(8) unsigned DEFAULT NULL,
+ `isKmTruckRate` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `routeCommission_routeFk_idx` (`routeFk`),
KEY `routeCommission_workCenterFk_idx` (`workCenterFk`),
KEY `routeCommission_firstEditorFk` (`firstEditorFk`),
+ KEY `routeCommission_country_FK` (`countryFk`),
+ CONSTRAINT `routeCommission_country_FK` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE,
CONSTRAINT `routeCommission_routeFk` FOREIGN KEY (`routeFk`) REFERENCES `route` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `routeCommission_workCenterFk` FOREIGN KEY (`workCenterFk`) REFERENCES `workCenter` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
@@ -36877,21 +36418,6 @@ CREATE TABLE `routeDefaultAgencyMode` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
---
--- Table structure for table `routeLoadWorker__`
---
-
-DROP TABLE IF EXISTS `routeLoadWorker__`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `routeLoadWorker__` (
- `routeFk` int(10) unsigned NOT NULL,
- `workerFk` int(10) unsigned NOT NULL,
- PRIMARY KEY (`routeFk`,`workerFk`),
- KEY `frmWorker_idx` (`workerFk`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Table deprecated on 26/04/23';
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Table structure for table `routeLog`
--
@@ -36916,6 +36442,7 @@ CREATE TABLE `routeLog` (
KEY `userFk` (`userFk`),
KEY `routeLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `routeLog_originFk` (`originFk`,`creationDate`),
+ KEY `routeLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `routeLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -36965,24 +36492,6 @@ CREATE TABLE `routeRecalc` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_bin COMMENT='Queue of changed volume to recalc route volumen';
/*!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 */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `routeUserPercentage__` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `workerFk` int(10) unsigned 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 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Temporary table structure for view `routesControl`
--
@@ -37054,7 +36563,7 @@ CREATE TABLE `sale` (
`ticketFk` int(11) NOT NULL,
`concept` varchar(50) DEFAULT NULL,
`quantity` decimal(10,2) NOT NULL DEFAULT 0.00,
- `originalQuantity` double(9,1) DEFAULT NULL COMMENT 'Se utiliza para notificar a través de rocket los cambios de quantity',
+ `originalQuantity` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Se utiliza para notificar a través de rocket los cambios de quantity',
`price` decimal(10,2) NOT NULL DEFAULT 0.00,
`discount` tinyint(2) unsigned NOT NULL DEFAULT 0,
`priceFixed` decimal(10,2) NOT NULL DEFAULT 0.00,
@@ -37247,6 +36756,7 @@ CREATE TABLE `saleGroupLog` (
KEY `saleGroupUserFk` (`userFk`),
KEY `saleGroupLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `saleGroupLog_originFk` (`originFk`,`creationDate`),
+ KEY `saleGroupLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `saleGroupLogUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -37369,7 +36879,6 @@ CREATE TABLE `saleTracking` (
`created` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`originalQuantity` double DEFAULT NULL,
`workerFk` int(10) unsigned NOT NULL,
- `actionFk__` int(11) DEFAULT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`stateFk` tinyint(3) unsigned NOT NULL,
`isScanned` tinyint(1) DEFAULT NULL COMMENT 'TRUE: se ha escaneado. FALSE: escrito a mano. NULL:demás casos',
@@ -37378,11 +36887,9 @@ CREATE TABLE `saleTracking` (
KEY `Id_Movimiento` (`saleFk`),
KEY `fgnStateFk_idx` (`stateFk`),
KEY `saleTracking_idx5` (`created`),
- KEY `saleTracking_fk2_idx` (`actionFk__`),
KEY `saleTracking_FK_2` (`workerFk`),
CONSTRAINT `fgnStateFk` FOREIGN KEY (`stateFk`) REFERENCES `state` (`id`) ON UPDATE CASCADE,
CONSTRAINT `saleTracking_FK` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT `saleTracking_FK_1` FOREIGN KEY (`actionFk__`) REFERENCES `ticketTrackingState__` (`id`) ON UPDATE CASCADE,
CONSTRAINT `saleTracking_FK_2` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -37601,6 +37108,36 @@ CREATE TABLE `sample` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `saySimpleConfig`
+--
+
+DROP TABLE IF EXISTS `saySimpleConfig`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `saySimpleConfig` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `url` varchar(255) NOT NULL,
+ `defaultChannel` varchar(128) DEFAULT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `saySimpleCountry`
+--
+
+DROP TABLE IF EXISTS `saySimpleCountry`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `saySimpleCountry` (
+ `countryFk` mediumint(8) unsigned NOT NULL,
+ `channel` varchar(128) DEFAULT NULL,
+ PRIMARY KEY (`countryFk`),
+ CONSTRAINT `saySimpleCountry_FK` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `scanner`
--
@@ -37683,6 +37220,7 @@ CREATE TABLE `sector` (
`isReserve` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Sectores de reserva, como Albenfruit o Fuentes',
`backupPrinterFk` int(10) unsigned DEFAULT NULL,
`typeFk` int(10) unsigned NOT NULL DEFAULT 1,
+ `isOnReservationMode` tinyint(1) DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY `code_UNIQUE` (`code`),
KEY `sector_fk1_idx` (`warehouseFk`),
@@ -37929,7 +37467,7 @@ CREATE TABLE `shelvingLog` (
`action` set('insert','update','delete','select') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
- `changedModel` enum('Shelving') NOT NULL DEFAULT 'Shelving',
+ `changedModel` enum('Shelving','ItemShelving') NOT NULL DEFAULT 'Shelving',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
@@ -37939,6 +37477,7 @@ CREATE TABLE `shelvingLog` (
KEY `userFk` (`userFk`),
KEY `shelvingLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `shelvingLog_originFk` (`originFk`,`creationDate`),
+ KEY `shelvingLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `shelvingLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -38003,23 +37542,6 @@ CREATE TABLE `siiTypeInvoiceOut` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tipo de Factura Emitidas en el suministro de inmediato';
/*!40101 SET character_set_client = @saved_cs_client */;
---
--- Table structure for table `silexACL__`
---
-
-DROP TABLE IF EXISTS `silexACL__`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `silexACL__` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `module` varchar(50) NOT NULL,
- `method` varchar(50) NOT NULL,
- `role` varchar(20) NOT NULL,
- PRIMARY KEY (`id`),
- UNIQUE KEY `module_UNIQUE` (`module`,`method`) USING BTREE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='@deprecated 2024-08-05 refs #7820';
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Table structure for table `sinister`
--
@@ -38348,7 +37870,6 @@ CREATE TABLE `state` (
`order` tinyint(3) unsigned DEFAULT NULL,
`alertLevel` int(11) NOT NULL DEFAULT 0,
`code` varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
- `sectorProdPriority` tinyint(3) DEFAULT NULL,
`nextStateFk` tinyint(3) unsigned 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,
@@ -38385,6 +37906,25 @@ CREATE TABLE `stateI18n` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `stockBought`
+--
+
+DROP TABLE IF EXISTS `stockBought`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `stockBought` (
+ `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
+ `workerFk` int(10) unsigned NOT NULL,
+ `bought` decimal(10,2) NOT NULL COMMENT 'purchase volume in m3 for the day',
+ `reserve` decimal(10,2) DEFAULT NULL COMMENT 'reserved volume in m3 for the day',
+ `dated` date NOT NULL DEFAULT current_timestamp(),
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `stockBought_unique` (`workerFk`,`dated`),
+ CONSTRAINT `stockBought_worker_FK` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `stockBuyed`
--
@@ -38404,7 +37944,7 @@ CREATE TABLE `stockBuyed` (
PRIMARY KEY (`id`),
KEY `stockBuyed_user_idx` (`userFk`),
CONSTRAINT `stockBuyedUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='@deprecated 2024-10-01 rename and refactor to stockBought';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -38439,7 +37979,6 @@ CREATE TABLE `supplier` (
`countryFk` mediumint(8) unsigned DEFAULT NULL,
`nif` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`isOfficial` tinyint(1) NOT NULL DEFAULT 1,
- `isFarmer__` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'refs #7345 @deprecated 2024-05-10 - Utilizar withholdingSageFk',
`retAccount` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`phone` varchar(16) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`commission` float NOT NULL DEFAULT 0,
@@ -38463,6 +38002,8 @@ CREATE TABLE `supplier` (
`isPayMethodChecked` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'Se ha validado la forma de pago',
`isVies` tinyint(4) NOT NULL DEFAULT 0,
`stamp` longblob DEFAULT NULL,
+ `companySize` enum('small','medium','big') DEFAULT NULL,
+ `geoFk` int(11) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `cuenta` (`account`),
@@ -38478,6 +38019,7 @@ CREATE TABLE `supplier` (
KEY `suppplier_supplierActivityFk` (`supplierActivityFk`),
KEY `supplier_workerFk` (`workerFk`),
KEY `supplier_fk_editor` (`editorFk`),
+ KEY `supplier_zoneGeo_FK` (`geoFk`),
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,
@@ -38487,6 +38029,7 @@ CREATE TABLE `supplier` (
CONSTRAINT `supplier_transactionFk` FOREIGN KEY (`transactionTypeSageFk`) REFERENCES `sage`.`TiposTransacciones` (`CodigoTransaccion`) ON UPDATE CASCADE,
CONSTRAINT `supplier_withholdingFk` FOREIGN KEY (`withholdingSageFk`) REFERENCES `sage`.`TiposRetencion` (`CodigoRetencion`) ON UPDATE CASCADE,
CONSTRAINT `supplier_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `supplier_zoneGeo_FK` FOREIGN KEY (`geoFk`) REFERENCES `zoneGeo` (`id`) ON UPDATE CASCADE,
CONSTRAINT `suppplier_supplierActivityFk` FOREIGN KEY (`supplierActivityFk`) REFERENCES `supplierActivity` (`code`) ON UPDATE CASCADE,
CONSTRAINT `supplierAccountTooShort` CHECK (octet_length(`account`) = 10)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
@@ -38506,7 +38049,6 @@ CREATE TABLE `supplierAccount` (
`office` varchar(4) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`DC` varchar(2) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`number` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
- `description__` varchar(45) DEFAULT NULL COMMENT '@deprecated 2023-03-23',
`bankEntityFk` int(10) unsigned DEFAULT NULL,
`accountingFk` int(11) DEFAULT NULL,
`beneficiary` varchar(50) DEFAULT NULL,
@@ -38720,6 +38262,7 @@ CREATE TABLE `supplierLog` (
KEY `supplierLog_ibfk_2` (`userFk`),
KEY `supplierLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `supplierLog_originFk` (`originFk`,`creationDate`),
+ KEY `supplierLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `supplierLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -39046,7 +38589,22 @@ CREATE TABLE `ticket` (
CONSTRAINT `ticket_ibfk_8` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`),
CONSTRAINT `ticket_ibfk_9` FOREIGN KEY (`routeFk`) REFERENCES `route` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `ticket_invoiceOut_FK` FOREIGN KEY (`refFk`) REFERENCES `invoiceOut` (`ref`) ON UPDATE CASCADE,
- CONSTRAINT `tickets_zone_fk` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON UPDATE CASCADE
+ CONSTRAINT `tickets_zone_fk` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `ticketCanAdvanceConfig`
+--
+
+DROP TABLE IF EXISTS `ticketCanAdvanceConfig`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `ticketCanAdvanceConfig` (
+ `id` int(10) unsigned NOT NULL,
+ `destinationOrder` int(11) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ CONSTRAINT `ticketCanAdvanceConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -39095,10 +38653,12 @@ CREATE TABLE `ticketConfig` (
`packingDelay` int(11) DEFAULT 1 COMMENT 'Horas que marcará el retraso respecto hora de cierre web del ticket',
`daysForWarningClaim` int(11) NOT NULL DEFAULT 2 COMMENT 'dias restantes hasta que salte el aviso de reclamación fuera de plazo',
`defaultAttenderFk` int(10) unsigned DEFAULT NULL,
+ `closureDaysAgo` int(11) NOT NULL DEFAULT 2 COMMENT 'Number of days to look back for ticket closure',
PRIMARY KEY (`id`),
KEY `ticketConfig_worker_FK` (`defaultAttenderFk`),
CONSTRAINT `ticketConfig_worker_FK` FOREIGN KEY (`defaultAttenderFk`) REFERENCES `worker` (`id`),
- CONSTRAINT `ticketConfig_check` CHECK (`id` = 1)
+ CONSTRAINT `ticketConfig_check` CHECK (`id` = 1),
+ CONSTRAINT `closureDaysAgo_check` CHECK (`closureDaysAgo` > 0)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -39462,7 +39022,6 @@ CREATE TABLE `ticketRequest` (
`ordered` datetime DEFAULT NULL,
`shipped` datetime DEFAULT NULL,
`salesPersonCode` varchar(3) DEFAULT NULL,
- `buyerCode__` varchar(3) NOT NULL COMMENT '@deprecated 2024-04-23 refs #6731 field not used',
`quantity` int(11) DEFAULT NULL,
`price` double DEFAULT NULL,
`itemFk` double DEFAULT NULL,
@@ -39481,7 +39040,6 @@ CREATE TABLE `ticketRequest` (
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`),
@@ -39541,23 +39099,6 @@ CREATE TABLE `ticketServiceType` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='Lista de los posibles servicios a elegir';
/*!40101 SET character_set_client = @saved_cs_client */;
---
--- Table structure for table `ticketSms__`
---
-
-DROP TABLE IF EXISTS `ticketSms__`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `ticketSms__` (
- `smsFk` mediumint(8) unsigned NOT NULL,
- `ticketFk` int(11) DEFAULT NULL,
- PRIMARY KEY (`smsFk`),
- KEY `ticketSms_FK_1` (`ticketFk`),
- CONSTRAINT `ticketSms_FK` FOREIGN KEY (`smsFk`) REFERENCES `sms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT `ticketSms_FK_1` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Temporary table structure for view `ticketState`
--
@@ -39631,20 +39172,6 @@ CREATE TABLE `ticketTracking` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
---
--- Table structure for table `ticketTrackingState__`
---
-
-DROP TABLE IF EXISTS `ticketTrackingState__`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `ticketTrackingState__` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `action` varchar(15) NOT NULL,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Table structure for table `ticketTrolley`
--
@@ -39994,7 +39521,6 @@ CREATE TABLE `travel` (
`landingHour` time DEFAULT NULL,
`warehouseInFk` smallint(6) unsigned DEFAULT NULL,
`warehouseOutFk` smallint(6) unsigned DEFAULT NULL,
- `agencyFk__` smallint(5) unsigned NOT NULL COMMENT '@deprecated 2024-10-01 refs #6604',
`ref` varchar(20) DEFAULT NULL,
`isDelivered` tinyint(1) NOT NULL DEFAULT 0,
`isReceived` tinyint(1) NOT NULL DEFAULT 0,
@@ -40007,9 +39533,10 @@ CREATE TABLE `travel` (
`clonedFrom` int(11) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
`awbFk` smallint(11) unsigned DEFAULT NULL,
+ `daysInForward` int(10) unsigned DEFAULT NULL COMMENT 'Cuando es una redada, indica el número de días que se añadirán a la fecha de hoy para establecer el landed. NULL si no es una redada',
+ `isRaid` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Redada',
PRIMARY KEY (`id`),
UNIQUE KEY `shipment_1` (`shipped`,`landed`,`warehouseInFk`,`warehouseOutFk`,`agencyModeFk`,`ref`),
- KEY `agency_id` (`agencyFk__`),
KEY `shipment` (`shipped`),
KEY `landing` (`landed`),
KEY `warehouse_landing` (`warehouseInFk`,`landed`),
@@ -40132,6 +39659,7 @@ CREATE TABLE `travelLog` (
KEY `userFk` (`userFk`),
KEY `travelLog_changedModel` (`changedModel`,`changedModelId`,`originFk`),
KEY `travelLog_originFk` (`originFk`,`creationDate`),
+ KEY `travelLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `travelLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -40169,6 +39697,8 @@ CREATE TABLE `travelThermograph` (
`result` varchar(45) DEFAULT NULL,
`dmsFk` int(11) DEFAULT NULL,
`temperatureFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT 'cool' COMMENT 'En la versión de Agosto de Salix se empezará a usar este campo y se actualizaran los anteriores mirando temperature.',
+ `maxTemperature` decimal(5,2) DEFAULT NULL,
+ `minTemperature` decimal(5,2) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `thermograph_fk_idx` (`thermographFk`),
@@ -40177,7 +39707,7 @@ CREATE TABLE `travelThermograph` (
KEY `warehouse_id` (`warehouseFk`),
KEY `travelThermographTemperatureFgn` (`temperatureFk`),
KEY `travelThermograph_fk_editor` (`editorFk`),
- CONSTRAINT `travelThermographDmsFgn` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `travelThermographDmsFgn` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `travelThermographTemperatureFgn` FOREIGN KEY (`temperatureFk`) REFERENCES `temperature` (`code`),
CONSTRAINT `travelThermographThermographFgn` FOREIGN KEY (`thermographFk`) REFERENCES `thermograph` (`id`) ON UPDATE CASCADE,
CONSTRAINT `travelThermographTravelFgn` FOREIGN KEY (`travelFk`) REFERENCES `travel` (`id`),
@@ -40226,6 +39756,7 @@ CREATE TABLE `userLog` (
PRIMARY KEY (`id`),
KEY `originFk` (`originFk`),
KEY `userFk` (`userFk`),
+ KEY `userLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `userLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -40549,7 +40080,7 @@ DROP TABLE IF EXISTS `wagon`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wagon` (
- `id` varchar(6) NOT NULL COMMENT '26 letras de alfabeto inglés',
+ `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '26 letras de alfabeto inglés',
`volume` int(11) NOT NULL DEFAULT 150 COMMENT 'Volumen en litros',
`plate` varchar(10) NOT NULL COMMENT 'Matrícula',
`typeFk` int(11) unsigned NOT NULL,
@@ -40574,7 +40105,11 @@ CREATE TABLE `wagonConfig` (
`maxWagonHeight` int(11) unsigned DEFAULT 200,
`minHeightBetweenTrays` int(11) unsigned DEFAULT 50,
`maxTrays` int(11) unsigned DEFAULT 6,
+ `defaultHeight` int(10) unsigned DEFAULT 0 COMMENT 'Default height in cm for a base tray',
+ `defaultTrayColorFk` int(11) unsigned DEFAULT NULL COMMENT 'Default color for a base tray',
PRIMARY KEY (`id`),
+ KEY `wagonConfig_wagonTypeColor_FK` (`defaultTrayColorFk`),
+ CONSTRAINT `wagonConfig_wagonTypeColor_FK` FOREIGN KEY (`defaultTrayColorFk`) REFERENCES `wagonTypeColor` (`id`),
CONSTRAINT `wagonConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -40621,15 +40156,15 @@ DROP TABLE IF EXISTS `wagonTypeTray`;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wagonTypeTray` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
- `typeFk` int(11) unsigned DEFAULT NULL,
- `height` int(11) unsigned NOT NULL,
- `colorFk` int(11) unsigned DEFAULT NULL,
+ `wagonTypeFk` int(11) unsigned DEFAULT NULL,
+ `height` int(11) unsigned DEFAULT NULL,
+ `wagonTypeColorFk` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
- UNIQUE KEY `typeFk` (`typeFk`,`height`),
- KEY `wagonTypeTray_color` (`colorFk`),
- CONSTRAINT `wagonTypeTray_color` FOREIGN KEY (`colorFk`) REFERENCES `wagonTypeColor` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `wagonTypeTray_type` FOREIGN KEY (`typeFk`) REFERENCES `wagonType` (`id`) ON UPDATE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
+ KEY `wagonTypeTray_wagonType_FK` (`wagonTypeFk`),
+ KEY `wagonTypeTray_wagonTypeColor_FK` (`wagonTypeColorFk`),
+ CONSTRAINT `wagonTypeTray_wagonTypeColor_FK` FOREIGN KEY (`wagonTypeColorFk`) REFERENCES `wagonTypeColor` (`id`),
+ CONSTRAINT `wagonTypeTray_wagonType_FK` FOREIGN KEY (`wagonTypeFk`) REFERENCES `wagonType` (`id`) ON DELETE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -40645,7 +40180,7 @@ CREATE TABLE `wagonVolumetry` (
`lines` int(10) unsigned NOT NULL DEFAULT 1,
`liters` int(10) unsigned NOT NULL DEFAULT 0,
`height` int(10) unsigned NOT NULL DEFAULT 20,
- `wagonFk` varchar(6) NOT NULL,
+ `wagonFk` int(11) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `wagonVolumetry_FK_1` (`wagonFk`),
CONSTRAINT `wagonVolumetry_FK_1` FOREIGN KEY (`wagonFk`) REFERENCES `wagon` (`id`) ON UPDATE CASCADE
@@ -40680,7 +40215,6 @@ CREATE TABLE `warehouse` (
`hasDms` tinyint(1) NOT NULL DEFAULT 0,
`pickUpAgencyModeFk` int(11) DEFAULT NULL,
`isBuyerToBeEmailed` tinyint(2) NOT NULL DEFAULT 0,
- `aliasFk__` smallint(5) unsigned DEFAULT NULL COMMENT '@deprecated 2024-01-23 refs #5167',
`labelReport` int(11) DEFAULT NULL,
`hasUbications` tinyint(1) NOT NULL DEFAULT 1,
`hasProduction` tinyint(1) NOT NULL DEFAULT 0,
@@ -40689,37 +40223,20 @@ CREATE TABLE `warehouse` (
`isLogiflora` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Este almacén acepta productos de Logiflora',
`isBionic` tinyint(1) NOT NULL DEFAULT 1,
`isHalt` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Almacén en el que descargan nuestros troncales',
- `isOrigin` tinyint(1) DEFAULT NULL,
- `isDestiny` tinyint(1) DEFAULT NULL,
+ `isOrigin` tinyint(1) NOT NULL DEFAULT 0,
+ `isDestiny` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`),
KEY `Id_Paises` (`countryFk`),
KEY `isComparativeIdx` (`isComparative`),
- KEY `warehouse_ibfk_1_idx` (`aliasFk__`),
KEY `warehouse_FK` (`addressFk`),
KEY `warehouse_FK_1` (`pickUpAgencyModeFk`),
CONSTRAINT `warehouse_FK` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `warehouse_FK_1` FOREIGN KEY (`pickUpAgencyModeFk`) REFERENCES `agencyMode` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `warehouse_ibfk_1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`),
- CONSTRAINT `warehouse_ibfk_2` FOREIGN KEY (`aliasFk__`) REFERENCES `warehouseAlias__` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
+ CONSTRAINT `warehouse_ibfk_1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
---
--- Table structure for table `warehouseAlias__`
---
-
-DROP TABLE IF EXISTS `warehouseAlias__`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `warehouseAlias__` (
- `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
- `name` varchar(15) NOT NULL,
- PRIMARY KEY (`id`),
- UNIQUE KEY `name_UNIQUE` (`name`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='@deprecated 2024-01-23 refs #5167';
-/*!40101 SET character_set_client = @saved_cs_client */;
-
--
-- Table structure for table `warehousePickup`
--
@@ -40759,6 +40276,27 @@ CREATE TABLE `workCenter` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `workCenterCommission`
+--
+
+DROP TABLE IF EXISTS `workCenterCommission`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `workCenterCommission` (
+ `workCenterFk` int(11) NOT NULL,
+ `deliveryManAdjustment` decimal(4,2) DEFAULT NULL COMMENT 'Número de trabajadores para equilibrar los repartidores de diferentes centros.\n Utilizado en repartidores de grafana',
+ `distributionM3Category1` decimal(5,2) DEFAULT NULL,
+ `distributionM3Category2` decimal(5,2) DEFAULT NULL,
+ `distributionCat4M3` decimal(5,2) DEFAULT NULL COMMENT 'Comisión por gestión de la distribución Cat IV',
+ `distributionCat5M3` decimal(5,2) DEFAULT NULL COMMENT 'Comisión por gestión de la distribución Cat V',
+ `deliveryM3Cat4` decimal(5,2) DEFAULT NULL,
+ `deliveryM3Cat5` decimal(5,2) DEFAULT NULL,
+ PRIMARY KEY (`workCenterFk`),
+ CONSTRAINT `workCenterCommission_workCenterFk` FOREIGN KEY (`workCenterFk`) REFERENCES `workCenter` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `workCenterHoliday`
--
@@ -40795,9 +40333,7 @@ CREATE TABLE `worker` (
`hasMachineryAuthorized` tinyint(2) DEFAULT 0,
`seniority` date DEFAULT NULL,
`isTodayRelative` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Para el F11. Calcula los problemas de visiblidad en funcion del dia actual',
- `isF11Allowed` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Usuario autorizado para abrir el F11',
`maritalStatus` enum('S','M') NOT NULL,
- `labelerFk__` tinyint(3) unsigned DEFAULT NULL COMMENT '@deprecated 2023-06-26',
`originCountryFk` mediumint(8) unsigned DEFAULT NULL COMMENT 'País de origen',
`educationLevelFk` smallint(6) DEFAULT NULL,
`SSN` varchar(15) DEFAULT NULL,
@@ -40815,7 +40351,6 @@ CREATE TABLE `worker` (
UNIQUE KEY `worker_business` (`businessFk`),
KEY `sub` (`sub`),
KEY `boss_idx` (`bossFk`),
- KEY `worker_FK` (`labelerFk__`),
KEY `worker_FK_2` (`educationLevelFk`),
KEY `worker_FK_1` (`originCountryFk`),
KEY `worker_fk_editor` (`editorFk`),
@@ -41030,32 +40565,37 @@ CREATE TABLE `workerDistributionCategory` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`workerFk` int(10) unsigned NOT NULL,
`category` int(11) NOT NULL,
+ `countryFk` mediumint(8) unsigned DEFAULT NULL,
+ `isKmTruckRate` tinyint(1) DEFAULT NULL,
+ `commissionSplitWorkers` int(10) unsigned NOT NULL DEFAULT 1 COMMENT 'Número de enrutadores entr los que se reparte la comsión',
PRIMARY KEY (`id`),
KEY `workerDistributionCategory_workerFk_idx` (`workerFk`),
+ KEY `workerDistributionCategory_country_FK` (`countryFk`),
+ CONSTRAINT `workerDistributionCategory_country_FK` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE,
CONSTRAINT `workerDistributionCategory_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
--- Table structure for table `workerDocument`
+-- Table structure for table `workerDms`
--
-DROP TABLE IF EXISTS `workerDocument`;
+DROP TABLE IF EXISTS `workerDms`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `workerDocument` (
+CREATE TABLE `workerDms` (
`id` int(11) NOT NULL AUTO_INCREMENT,
- `worker` int(10) unsigned DEFAULT NULL,
- `document` int(11) DEFAULT NULL,
+ `workerFk` int(10) unsigned DEFAULT NULL,
+ `dmsFk` int(11) DEFAULT NULL,
`isReadableByWorker` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Indica si el empleado tiene permiso para acceder al documento',
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
- KEY `workerDocument_ibfk_1` (`worker`),
- KEY `workerDocument_ibfk_2` (`document`),
+ KEY `workerDocument_ibfk_1` (`workerFk`),
+ KEY `workerDocument_ibfk_2` (`dmsFk`),
KEY `workerDocument_fk_editor` (`editorFk`),
- CONSTRAINT `workerDocument_FK` FOREIGN KEY (`worker`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `workerDocument_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
- CONSTRAINT `workerDocument_ibfk_2` FOREIGN KEY (`document`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+ CONSTRAINT `workerDms_ibfk_2` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `workerDocument_FK` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `workerDocument_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -41219,6 +40759,7 @@ CREATE TABLE `workerLog` (
KEY `userFk_idx` (`userFk`),
KEY `workerLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `workerLog_originFk` (`originFk`,`creationDate`),
+ KEY `workerLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `userFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -41343,9 +40884,7 @@ CREATE TABLE `workerRelatives` (
`updated` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
KEY `workerRelatives_disabilityGradeFk` (`disabilityGradeFk`),
- KEY `workerRelatives_workerFk` (`workerFk`),
- CONSTRAINT `workerRelatives_disabilityGradeFk` FOREIGN KEY (`disabilityGradeFk`) REFERENCES `disabilityGrade` (`id`) ON UPDATE CASCADE,
- CONSTRAINT `workerRelatives_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `workerIrpf` (`workerFk`) ON DELETE CASCADE ON UPDATE CASCADE
+ KEY `workerRelatives_workerFk` (`workerFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Modelo 145 IRPF apartado 2 y 3';
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -41565,13 +41104,13 @@ CREATE TABLE `workerTimeControlMail` (
/*!40101 SET character_set_client = @saved_cs_client */;
--
--- Table structure for table `workerTimeControlParams`
+-- Table structure for table `workerTimeControlParams__`
--
-DROP TABLE IF EXISTS `workerTimeControlParams`;
+DROP TABLE IF EXISTS `workerTimeControlParams__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `workerTimeControlParams` (
+CREATE TABLE `workerTimeControlParams__` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`dayBreak` int(11) NOT NULL,
`weekBreak` int(11) NOT NULL,
@@ -41587,7 +41126,7 @@ CREATE TABLE `workerTimeControlParams` (
`mailErrorFolder` varchar(45) NOT NULL,
`mailUser` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_bin COMMENT='All values in seconds';
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_bin COMMENT='@deprecated 2024-11-19';
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -41721,9 +41260,10 @@ CREATE TABLE `zone` (
`isVolumetric` tinyint(1) NOT NULL DEFAULT 0,
`inflation` decimal(5,2) NOT NULL DEFAULT 1.00,
`m3Max` decimal(10,2) unsigned DEFAULT NULL,
- `itemMaxSize` int(11) DEFAULT NULL COMMENT 'tamaño maximo de los articulos que esa ruta puede transportar',
+ `itemMaxSize` int(11) DEFAULT NULL COMMENT 'Altura maxima de los articulos que esa agencia puede transportar',
`code` varchar(45) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
+ `itemMaxLength` int(11) DEFAULT NULL COMMENT 'Longitud maxima para articulos acostados que esa agencia puede transportar',
PRIMARY KEY (`id`),
KEY `fk_zone_2_idx` (`agencyModeFk`),
KEY `zone_name_idx` (`name`),
@@ -41942,7 +41482,7 @@ CREATE TABLE `zoneIncluded` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`zoneFk` int(11) NOT NULL,
`geoFk` int(11) NOT NULL,
- `isIncluded` tinyint(1) DEFAULT NULL,
+ `isIncluded` tinyint(1) NOT NULL DEFAULT 0,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_zone_geo` (`zoneFk`,`geoFk`),
@@ -41997,6 +41537,7 @@ CREATE TABLE `zoneLog` (
KEY `userFk` (`userFk`),
KEY `zoneLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `zoneLog_originFk` (`originFk`,`creationDate`),
+ KEY `zoneLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
CONSTRAINT `zoneLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -42195,6 +41736,24 @@ DELIMITER ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
/*!50003 SET character_set_results = @saved_cs_results */ ;;
/*!50003 SET collation_connection = @saved_col_connection */ ;;
+/*!50106 DROP EVENT IF EXISTS `itemCampaig_add` */;;
+DELIMITER ;;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
+/*!50003 SET character_set_client = utf8mb4 */ ;;
+/*!50003 SET character_set_results = utf8mb4 */ ;;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
+/*!50003 SET @saved_time_zone = @@time_zone */ ;;
+/*!50003 SET time_zone = 'SYSTEM' */ ;;
+/*!50106 CREATE*/ /*!50117 DEFINER=`vn`@`localhost`*/ /*!50106 EVENT `itemCampaig_add` ON SCHEDULE EVERY 1 DAY STARTS '2024-10-18 03:00:00' ON COMPLETION PRESERVE ENABLE DO CALL itemCampaign_add() */ ;;
+/*!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 `itemImageQueue_check` */;;
DELIMITER ;;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;;
@@ -42346,24 +41905,6 @@ END */ ;;
/*!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 = utf8mb4 */ ;;
-/*!50003 SET character_set_results = utf8mb4 */ ;;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
-/*!50003 SET @saved_time_zone = @@time_zone */ ;;
-/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`vn`@`localhost`*/ /*!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 */ ;;
/*!50106 DROP EVENT IF EXISTS `route_doRecalc` */;;
DELIMITER ;;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;;
@@ -42394,7 +41935,7 @@ DELIMITER ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
-/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `travel_setDelivered` ON SCHEDULE EVERY 1 DAY STARTS '2024-07-12 00:10:00' ON COMPLETION PRESERVE ENABLE DO BEGIN
+/*!50106 CREATE*/ /*!50117 DEFINER=`vn`@`localhost`*/ /*!50106 EVENT `travel_setDelivered` ON SCHEDULE EVERY 1 DAY STARTS '2024-07-12 00:10:00' ON COMPLETION PRESERVE ENABLE DO BEGIN
UPDATE travel t
SET t.isDelivered = TRUE
WHERE t.shipped < util.VN_CURDATE();
@@ -42566,9 +42107,12 @@ BEGIN
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
+ JOIN postCode p ON p.townFk = t.id
+ AND (p.code = a.postalCode OR a.postalCode IS NULL)
+ JOIN zoneGeo zg ON zg.id = p.geoFk
WHERE a.id = vSelf
- ORDER BY (a.city SOUNDS LIKE t.`name`) DESC
+ ORDER BY (a.city SOUNDS LIKE t.name) DESC,
+ (p.code = a.postalCode) DESC
LIMIT 1;
RETURN vGeoFk;
@@ -42643,6 +42187,91 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `buy_getLastWithoutInventory` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`vn`@`localhost` FUNCTION `buy_getLastWithoutInventory`(vItemFk INT,
+ vWarehouseFk INT
+) RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+/**
+ * Retorna la última compra que no sea inventario.
+ *
+ * @param vItemFk Id del artículo
+ * @param vWarehouseFk Id del almacén
+ * @return Id de compra
+ */
+ DECLARE vBuyFk INT;
+
+ SELECT b.id INTO vBuyFk
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE e.id <> (SELECT defaultEntry FROM entryConfig)
+ AND e.supplierFk <> (SELECT supplierFk FROM inventoryConfig)
+ AND e.typeFk <> 'inventory'
+ AND b.itemFk = vItemFk
+ AND (t.warehouseInFk = vWarehouseFk OR t.warehouseInFk IS NULL)
+ ORDER BY ABS(DATEDIFF(util.VN_CURDATE(), t.landed)), e.created DESC
+ LIMIT 1;
+
+ RETURN vBuyFk;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `buy_getUltimate` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`vn`@`localhost` FUNCTION `buy_getUltimate`(vItemFk INT,
+ vWarehouseFk INT,
+ vDated DATE
+) RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+/**
+ * Calcula las últimas compras realizadas hasta una fecha.
+ *
+ * @param vItemFk Id del artículo
+ * @param vWarehouseFk Id del almacén
+ * @param vDated Compras hasta fecha
+ * @return Id de compra
+ */
+ DECLARE vBuyFk INT;
+
+ CALL buy_getUltimate(vItemFk, vWarehouseFk, vDated);
+
+ SELECT buyFk INTO vBuyFk
+ FROM tmp.buyUltimate;
+
+ DROP TEMPORARY TABLE IF EXISTS
+ tmp.buyUltimate,
+ tmp.buyUltimateFromInterval;
+
+ RETURN vBuyFk;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `buy_getUnitVolume` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -43018,6 +42647,45 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `client_getGeo` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`vn`@`localhost` FUNCTION `client_getGeo`(vSelf INT) RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+/**
+ * Returns the geo for the passed client.
+ *
+ * @param vSelf The address id
+ * @return The geo id
+ */
+ DECLARE vGeoFk INT;
+
+ SELECT p.geoFk INTO vGeoFk
+ FROM client c
+ JOIN town t ON t.provinceFk = c.provinceFk
+ JOIN postCode p ON p.townFk = t.id
+ AND (p.code = c.postcode OR c.postcode IS NULL)
+ JOIN zoneGeo zg ON zg.id = p.geoFk
+ WHERE c.id = vSelf
+ ORDER BY (c.city SOUNDS LIKE t.name) DESC,
+ (p.code = c.postcode) DESC
+ LIMIT 1;
+
+ RETURN vGeoFk;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `client_getSalesPerson` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -43567,58 +43235,51 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`vn`@`localhost` FUNCTION `entry_getCommission`(vTravelFk INT,
- vCurrencyFk INT,
- vSupplierFk INT
+ vCurrencyFk INT,
+ vSupplierFk INT
) RETURNS int(11)
READS SQL DATA
BEGIN
- DECLARE vCommission INT;
- DECLARE vCurrentCommission INT;
- DECLARE vIsCurrencyUsd INT;
- DECLARE vLastEntryFk INT;
-
- SELECT count(*) INTO vIsCurrencyUsd
- FROM currency c
- WHERE c.code = 'USD' AND id = vCurrencyFk;
-
- IF NOT vIsCurrencyUsd THEN
-
- SELECT e.id INTO vLastEntryFk
- FROM vn.entry e
- JOIN vn.travel tr ON tr.id = e.travelFk
- WHERE e.supplierFk = vSupplierFk
- ORDER BY tr.landed DESC
- LIMIT 1;
-
- IF vLastEntryFk THEN
-
- SELECT commission INTO vCurrentCommission
- FROM vn.entry
- WHERE id = vLastEntryFk;
-
- ELSE
-
- SELECT commission INTO vCurrentCommission
- FROM supplier s
- WHERE s.id = vSupplierFk;
-
- END IF;
-
- RETURN vCurrentCommission;
-
- ELSE
+ DECLARE vCommission INT;
+ DECLARE vCurrentCommission INT;
+ DECLARE vIsNotEUR INT;
+ DECLARE vLastEntryFk INT;
+ SELECT count(*) INTO vIsNotEUR
+ FROM currency c
+ WHERE c.code <> 'EUR' AND id = vCurrencyFk;
+
+ IF vIsNotEUR THEN
SELECT ROUND(-100 * (1 - (1 / r.value))) INTO vCommission
FROM travel t
LEFT JOIN referenceCurrent r ON r.currencyFk = vCurrencyFk AND r.`dated` <= t.shipped
WHERE t.id = vTravelFk
ORDER BY r.`dated` DESC
LIMIT 1;
-
+
RETURN IFNULL(vCommission, 0);
-
- END IF;
-
+ ELSE
+ SELECT e.id INTO vLastEntryFk
+ FROM `entry` e
+ JOIN travel tr ON tr.id = e.travelFk
+ WHERE e.supplierFk = vSupplierFk
+ ORDER BY tr.landed DESC
+ LIMIT 1;
+
+ IF vLastEntryFk THEN
+ SELECT commission INTO vCurrentCommission
+ FROM `entry`
+ WHERE id = vLastEntryFk;
+
+ ELSE
+ SELECT commission INTO vCurrentCommission
+ FROM supplier s
+ WHERE s.id = vSupplierFk;
+
+ END IF;
+
+ RETURN vCurrentCommission;
+ END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -43658,81 +43319,6 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP FUNCTION IF EXISTS `entry_getForLogiflora` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` FUNCTION `entry_getForLogiflora`(vLanded DATE, vWarehouseFk INT) RETURNS int(11)
- READS SQL DATA
-BEGIN
-
- /**
- * Devuelve una entrada para Logiflora. Si no existe la crea.
- *
- * @param vLanded Fecha de llegada al almacén
- * @param vWarehouseFk Identificador de vn.warehouse
- */
-
- DECLARE vTravelFk INT;
- DECLARE vEntryFk INT;
- DECLARE previousEntryFk INT;
-
- SET vTravelFk = vn.travel_getForLogiflora(vLanded, vWarehouseFk);
-
- IF vLanded THEN
-
- SELECT IFNULL(MAX(id),0) INTO vEntryFk
- FROM vn.entry
- WHERE travelFk = vTravelFk
- AND isRaid;
-
- IF NOT vEntryFk THEN
-
- INSERT INTO vn.entry(travelFk, supplierFk, commission, companyFk, currencyFk, isRaid)
- SELECT vTravelFk, s.id, 4, c.id, cu.id, TRUE
- FROM vn.supplier s
- JOIN vn.company c ON c.code = 'VNL'
- JOIN vn.currency cu ON cu.code = 'EUR'
- WHERE s.name = 'KONINKLIJE COOPERATIEVE BLOEMENVEILING FLORAHOLLAN';
-
- SELECT MAX(id) INTO vEntryFk
- FROM vn.entry
- WHERE travelFk = vTravelFk;
-
- END IF;
-
- END IF;
-
- SELECT entryFk INTO previousEntryFk
- FROM edi.warehouseFloramondo wf
- WHERE wf.warehouseFk = vWarehouseFk;
-
- IF IFNULL(previousEntryFk,0) != vEntryFk THEN
-
- UPDATE buy b
- SET b.printedStickers = 0
- WHERE entryFk = previousEntryFk;
-
- DELETE FROM buy WHERE entryFk = previousEntryFk;
-
- DELETE FROM entry WHERE id = previousEntryFk;
-
- END IF;
-
- RETURN vEntryFk;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `entry_isIntrastat` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -44323,7 +43909,7 @@ BEGIN
SELECT count(*) INTO vItemCount
FROM vn.sale s
JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk
- JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.shelving sh ON sh.id = ish.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
WHERE s.ticketFk = vTicketFk
AND p.sectorFk = vSectorFk;
@@ -44773,7 +44359,7 @@ BEGIN
SELECT count(*) INTO vItemCount
FROM vn.sale s
JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk
- JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.shelving sh ON sh.id = ish.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
WHERE s.ticketFk = vTicketFk
AND p.sectorFk = vSectorFk;
@@ -45084,26 +44670,6 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP FUNCTION IF EXISTS `MIDNIGHT` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` 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 */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `orderTotalVolume` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -45275,7 +44841,7 @@ BEGIN
JOIN cache.zoneAgencyFriendship zf ON zf.agencyModeFk = r.agencyModeFk
WHERE friendship >= vSignificativeFriendship
AND zf.zoneFk = vZoneFk
- AND r.created = vLanded
+ AND r.dated = vLanded
ORDER BY friendship;
-- Se eliminan aquellas que superan el volumen máximo
@@ -45308,47 +44874,6 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP FUNCTION IF EXISTS `routeProposal_` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` FUNCTION `routeProposal_`(vTicketFk INT) RETURNS int(11)
- READS SQL DATA
-BEGIN
-
- DECLARE vRouteFk INT;
- DECLARE vAddressFk INT;
- DECLARE vShipped DATETIME;
-
- SELECT addressFk, date(shipped) INTO vAddressFk, vShipped
- FROM vn.ticket
- WHERE id = vTicketFk;
-
- SELECT routeFk INTO vRouteFk
- FROM
- (SELECT t.routeFk, sum(af.friendship) friendshipSum
- FROM vn.ticket t
- JOIN cache.addressFriendship af ON af.addressFk2 = t.addressFk AND af.addressFk1 = vAddressFk
- WHERE t.shipped BETWEEN vShipped and MIDNIGHT(vShipped)
- AND t.routeFk
- GROUP BY routeFk
- ORDER BY friendshipSum DESC
- ) sub
- LIMIT 1;
-
- RETURN 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 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `routeProposal_beta` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -45382,7 +44907,7 @@ BEGIN
JOIN cache.zoneAgencyFriendship zf ON zf.agencyModeFk = r.agencyModeFk
WHERE friendship >= vSignificativeFriendship
AND zf.zoneFk = vZoneFk
- AND r.created = vLanded
+ AND r.dated = vLanded
ORDER BY friendship;
-- Se eliminan aquellas que superan el volumen máximo
@@ -45532,6 +45057,47 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP FUNCTION IF EXISTS `supplier_getGeo` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`vn`@`localhost` FUNCTION `supplier_getGeo`(vSelf INT) RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+/**
+ * Returns the geo for the passed supplier.
+ *
+ * @param vSelf The address id
+ * @return The geo id
+ */
+ DECLARE vGeoFk INT;
+
+ SELECT p.geoFk INTO vGeoFk
+ FROM supplier s
+ JOIN town t ON t.provinceFk = s.provinceFk
+ JOIN postCode p ON p.townFk = t.id
+ AND (p.code = s.postCode OR s.postCode IS NULL)
+ LEFT JOIN supplierAddress sad ON sad.supplierFk = s.id
+ JOIN zoneGeo zg ON zg.id = p.geoFk
+ WHERE s.id = vSelf
+ ORDER BY (s.city SOUNDS LIKE t.name) DESC,
+ (p.code = s.postCode) DESC,
+ (p.code = sad.postalCode) DESC
+ LIMIT 1;
+
+ RETURN vGeoFk;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `testCIF` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -46419,82 +45985,6 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP FUNCTION IF EXISTS `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_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` FUNCTION `timeWorkerControl_getDirection`(vUserFk INT, vTimed DATETIME) RETURNS varchar(6) CHARSET utf8mb3 COLLATE utf8mb3_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 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `time_getSalesYear` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -46512,69 +46002,6 @@ FROM `time`
WHERE `month` = vMonth AND `year` = vYear
LIMIT 1;
RETURN vSalesYear;
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP FUNCTION IF EXISTS `travel_getForLogiflora` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` FUNCTION `travel_getForLogiflora`(vLanded DATE, vWarehouseFk INT) RETURNS int(11)
- READS SQL DATA
-BEGIN
-
- /**
- * Devuelve un número de travel para compras de Logiflora a partir de la fecha de llegada y del almacén.
- * Si no existe lo genera.
- *
- * @param vLanded Fecha de llegada al almacén
- * @param vWarehouseFk Identificador de vn.warehouse
- */
-
- DECLARE vTravelFk INT;
-
- IF vLanded THEN
-
- SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk
- FROM vn.travel tr
- JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk
- JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk
- JOIN vn.agencyMode am ON am.id = tr.agencyModeFk
- WHERE wIn.id = vWarehouseFk
- AND wOut.name = 'Holanda'
- AND am.name = 'LOGIFLORA'
- AND landed = vLanded;
-
- IF NOT vTravelFk THEN
-
- INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyModeFk)
- SELECT vLanded, util.VN_CURDATE(), vWarehouseFk, wOut.id, am.id
- FROM vn.warehouse wOut
- JOIN vn.agencyMode am ON am.name = 'LOGIFLORA'
- WHERE wOut.name = 'Holanda';
-
- SELECT MAX(tr.id) INTO vTravelFk
- FROM vn.travel tr
- JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk
- JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk
- WHERE wIn.id = vWarehouseFk
- AND wOut.name = 'Holanda'
- AND landed = vLanded;
- END IF;
-
- END IF;
-
- RETURN vTravelFk;
-
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -46704,40 +46131,6 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP FUNCTION IF EXISTS `workerMachinery_isRegistered` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` FUNCTION `workerMachinery_isRegistered`(vWorkerFk VARCHAR(10)) RETURNS tinyint(1)
- READS SQL DATA
-BEGIN
-/**
- * Comprueba si existen registros en las últimas horas (maxHours de machineWorkerConfig) del trabajador vWorkerFk y si tiene a nulo la hora outTimed (indica la hora que deja el vehículo)
- *
- * @param vWorkerFk id del trabajador
- * @return Devuelve TRUE/FALSE en caso de que haya o no registros
- */
- IF (SELECT COUNT(*)
- FROM machineWorker m
- WHERE m.workerFk = vWorkerFk
- AND m.inTimed >= TIMESTAMPADD(HOUR , -(SELECT maxHours from machineWorkerConfig), util.VN_NOW()) AND ISNULL(m.outTimed))
- THEN
- RETURN TRUE;
- ELSE
- RETURN FALSE;
- END IF;
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `workerNigthlyHours_calculate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -47028,7 +46421,7 @@ BEGIN
AND vWarehouseFk IN (tr.warehouseInFk, 0)
AND b.itemFk = vItemFk
AND NOT e.isExcludedFromAvailable
- AND NOT e.isRaid
+ AND NOT tr.isRaid
UNION ALL
SELECT tr.shipped,
NULL,
@@ -47047,7 +46440,7 @@ BEGIN
AND s.id <> (SELECT supplierFk FROM inventoryConfig)
AND b.itemFk = vItemFk
AND NOT e.isExcludedFromAvailable
- AND NOT e.isRaid
+ AND NOT tr.isRaid
UNION ALL
SELECT t.shipped,
NULL,
@@ -47070,7 +46463,7 @@ BEGIN
FROM tHistoricalPast
WHERE `date` < vDate;
- SELECT p1.*, NULL v_virtual
+ SELECT p1.*, NULL v_virtual
FROM (
SELECT vDate `date`,
vCalculatedInventory input,
@@ -47085,7 +46478,7 @@ BEGIN
FROM tHistoricalPast
WHERE `date` >= vDate
) p1;
-
+
DROP TEMPORARY TABLE tHistoricalPast;
END ;;
DELIMITER ;
@@ -47639,7 +47032,7 @@ CREATE DEFINER=`vn`@`localhost` PROCEDURE `available_traslate`(
vWarehouseShipment INT)
proc: BEGIN
/**
- * Calcular la disponibilidad dependiendo del almacen
+ * Calcular la disponibilidad dependiendo del almacen
* de origen y destino según la fecha.
*
* @param vWarehouseLanding Almacén de llegada
@@ -47676,10 +47069,10 @@ proc: BEGIN
WHERE t.landed BETWEEN vDatedInventory AND vDatedFrom
AND t.warehouseInFk = vWarehouseLanding
AND NOT e.isExcludedFromAvailable
- AND NOT e.isRaid
+ AND NOT t.isRaid
GROUP BY c.itemFk;
- -- Tabla con el ultimo dia de last_buy para cada producto
+ -- Tabla con el ultimo dia de last_buy para cada producto
-- que hace un replace de la anterior.
CALL buy_getUltimate (NULL, vWarehouseShipment, util.VN_CURDATE());
@@ -47691,7 +47084,7 @@ proc: BEGIN
JOIN travel tr ON tr.id = e.travelFk
LEFT JOIN tItemRange i ON t.itemFk = i.itemFk
WHERE t.warehouseFk = vWarehouseShipment
- AND NOT e.isRaid
+ AND NOT tr.isRaid
ON DUPLICATE KEY UPDATE tItemRange.dated = GREATEST(tItemRange.dated,
tr.landed);
@@ -47728,7 +47121,7 @@ proc: BEGIN
JOIN tItemRangeLive ir ON ir.itemFk = b.itemFk
WHERE NOT e.isExcludedFromAvailable
AND b.quantity <> 0
- AND NOT e.isRaid
+ AND NOT t.isRaid
AND t.warehouseInFk = vWarehouseLanding
AND t.landed >= vDatedFrom
AND (ir.dated IS NULL OR t.landed <= ir.dated)
@@ -48720,9 +48113,9 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getUltimate`(
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `buy_getUltimate`(
vItemFk INT,
- vWarehouseFk SMALLINT,
+ vWarehouseFk INT,
vDated DATE
)
BEGIN
@@ -48780,7 +48173,7 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getUltimateFromInterval`(
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `buy_getUltimateFromInterval`(
vItemFk INT,
vWarehouseFk SMALLINT,
vStarted DATE,
@@ -48994,39 +48387,6 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `buy_getVolumeByAgency` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `buy_getVolumeByAgency`(vDated DATE, vAgencyFk INT)
-BEGIN
-
- DROP TEMPORARY TABLE IF EXISTS tmp.buy;
- CREATE TEMPORARY TABLE tmp.buy (buyFk INT NOT NULL, PRIMARY KEY (buyFk)) ENGINE = MEMORY;
-
- INSERT INTO tmp.buy
- SELECT b.id
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- WHERE t.landed = vDated
- AND t.agencyModeFk IN (0, vAgencyFk);
-
- CALL buy_getVolume();
- DROP TEMPORARY TABLE tmp.buy;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_getVolumeByEntry` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -49533,7 +48893,10 @@ BEGIN
AND a.available > 0
AND (sub.itemAllowed OR NOT it.isFloramondo OR anr.available > 0)
AND (ag.isAnyVolumeAllowed OR NOT itt.isUnconventionalSize)
- AND (itc.isReclining OR it.`size` IS NULL OR it.`size` < z.itemMaxSize OR z.itemMaxSize IS NULL)
+ AND (it.`size` IS NULL
+ OR IF(itc.isReclining,
+ it.size <= z.itemMaxLength OR z.itemMaxLength IS NULL,
+ it.size <= z.itemMaxSize OR z.itemMaxSize IS NULL))
AND cit.id IS NULL
AND zit.id IS NULL
AND ait.id IS NULL;
@@ -49633,7 +48996,7 @@ CREATE DEFINER=`vn`@`localhost` PROCEDURE `catalog_componentCalculate`(
)
BEGIN
/**
- * Calcula los componentes de los articulos de tmp.ticketLot
+ * Calcula los componentes de los articulos de la tabla tmp.ticketLot
*
* @param vZoneFk para calcular el transporte
* @param vAddressFk Consignatario
@@ -49651,18 +49014,41 @@ BEGIN
FROM address
WHERE id = vAddressFk;
- CREATE OR REPLACE TEMPORARY TABLE tSpecialPrice
+ CREATE OR REPLACE TEMPORARY TABLE tPriceDelta
(INDEX (itemFk))
- ENGINE = MEMORY
- SELECT * FROM (
+ ENGINE = MEMORY
+ SELECT i.id itemFk,
+ SUM(IFNULL(pd.absIncreasing,0)) absIncreasing,
+ SUM(IFNULL(pd.ratIncreasing,0)) ratIncreasing,
+ pd.warehouseFk
+ FROM item i
+ JOIN priceDelta pd
+ ON pd.itemTypeFk = i.typeFk
+ AND (pd.minSize IS NULL OR pd.minSize <= i.`size`)
+ AND (pd.maxSize IS NULL OR pd.maxSize >= i.`size`)
+ AND (pd.inkFk IS NULL OR pd.inkFk = i.inkFk)
+ AND (pd.originFk IS NULL OR pd.originFk = i.originFk)
+ AND (pd.producerFk IS NULL OR pd.producerFk = i.producerFk)
+ AND (pd.warehouseFk IS NULL OR pd.warehouseFk = vWarehouseFk)
+ LEFT JOIN zoneGeo zg ON zg.id = pd.zoneGeoFk
+ LEFT JOIN zoneGeo zg2 ON zg2.id = address_getGeo(vAddressFk)
+ WHERE (pd.fromDated IS NULL OR pd.fromDated <= vShipped)
+ AND (pd.toDated IS NULL OR pd.toDated >= vShipped)
+ AND (pd.zoneGeoFk IS NULL OR zg2.lft BETWEEN zg.lft AND zg.rgt)
+ GROUP BY itemFk;
+
+ CREATE OR REPLACE TEMPORARY TABLE tSpecialPrice
+ (INDEX (itemFk))
+ ENGINE = MEMORY
+ SELECT * FROM (
SELECT *
- FROM specialPrice
- WHERE (clientFk = vClientFk OR clientFk IS NULL)
- AND started <= vShipped
- AND (ended >= vShipped OR ended IS NULL)
- ORDER BY (clientFk = vClientFk) DESC, id DESC
- LIMIT 10000000000000000000) t
- GROUP BY itemFk;
+ FROM specialPrice
+ WHERE (clientFk = vClientFk OR clientFk IS NULL)
+ AND started <= vShipped
+ AND (ended >= vShipped OR ended IS NULL)
+ ORDER BY (clientFk = vClientFk) DESC, id DESC
+ LIMIT 10000000000000000000) t
+ GROUP BY itemFk;
CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentCalculate
(PRIMARY KEY (itemFk, warehouseFk))
@@ -49734,6 +49120,19 @@ BEGIN
JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tc.itemFk AND tcc.warehouseFk = tc.warehouseFk
GROUP BY tc.itemFk, warehouseFk;
+ -- Bonus del comprador a un rango de productos
+ INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
+ SELECT
+ tcb.warehouseFk,
+ tcb.itemFk,
+ c.id,
+ IFNULL(tcb.base * tpd.ratIncreasing / 100,0) + IFNULL(tpd.absIncreasing,0)
+ FROM tmp.ticketComponentBase tcb
+ JOIN component c ON c.code = 'bonus'
+ JOIN tPriceDelta tpd
+ ON tpd.itemFk = tcb.itemFk
+ AND tpd.warehouseFk = tcb.warehouseFk;
+
-- RECOBRO
INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
SELECT tcb.warehouseFk, tcb.itemFk, c2.id,
@@ -49929,7 +49328,8 @@ BEGIN
tmp.ticketComponentBase,
tmp.ticketComponentRate,
tmp.ticketComponentCopy,
- tSpecialPrice;
+ tPriceDelta,
+ tSpecialPrice;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -50235,6 +49635,13 @@ BEGIN
DELETE FROM messageInbox WHERE sendDate < v2Months;
DELETE FROM messageInbox WHERE sendDate < v2Months;
DELETE FROM workerTimeControl WHERE timed < v4Years;
+ DELETE FROM itemShelvingSale
+ WHERE itemShelvingFk IN (
+ SELECT id
+ FROM itemShelving
+ WHERE created < util.VN_CURDATE()
+ AND visible = 0
+ );
DELETE FROM itemShelving WHERE created < util.VN_CURDATE() AND visible = 0;
DELETE FROM ticketDown WHERE created < util.yesterday();
DELETE IGNORE FROM expedition WHERE created < v26Months;
@@ -50261,17 +49668,11 @@ BEGIN
AND ts.id IS NULL;
DELETE FROM claim WHERE ticketCreated < v4Years;
-- Robert ubicacion anterior de travelLog comentario para debug
- DELETE FROM zoneEvent WHERE `type` = 'day' AND dated < v3Months;
- 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 <= v2Months;
+ DELETE FROM zoneEvent WHERE dated < v2Months OR ended < v2Months;
DELETE b FROM buy b
JOIN entryConfig e ON e.defaultEntry = b.entryFk
WHERE b.created < v2Months;
- DELETE FROM stockBuyed WHERE creationDate < v2Months;
+ DELETE FROM stockBought WHERE dated < v2Months;
DELETE FROM printQueue WHERE statusCode = 'printed' AND created < v2Months;
-- Equipos duplicados
DELETE w.*
@@ -50478,7 +49879,7 @@ BEGIN
JOIN agencyMode am ON am.id = tr.agencyModeFk
WHERE NOT b.quantity
AND am.code = 'logiflora'
- AND e.isRaid;
+ AND tr.daysInForward;
START TRANSACTION;
@@ -50535,27 +49936,6 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `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 = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `clearShelvingList`(vShelvingFk VARCHAR(8))
-BEGIN
- UPDATE vn.itemShelving
- SET visible = 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 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `clientDebtSpray` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -51234,22 +50614,19 @@ BEGIN
DECLARE vIsTaxDataChecked TINYINT(1);
DECLARE vHasCoreVnl BOOLEAN;
DECLARE vMandateTypeFk INT;
- DECLARE vHasDailyInvoice BOOLEAN;
SELECT cc.defaultPayMethodFk,
cc.defaultDueDay,
cc.defaultCredit,
cc.defaultIsTaxDataChecked,
cc.defaultHasCoreVnl,
- cc.defaultMandateTypeFk,
- c.hasDailyInvoice
+ cc.defaultMandateTypeFk
INTO vPayMethodFk,
vDueDay,
vDefaultCredit,
vIsTaxDataChecked,
vHasCoreVnl,
- vMandateTypeFk,
- vHasDailyInvoice
+ vMandateTypeFk
FROM clientConfig cc
LEFT JOIN province p ON p.id = vProvinceFk
LEFT JOIN country c ON c.id = p.countryFk;
@@ -51270,8 +50647,7 @@ BEGIN
credit = vDefaultCredit,
isTaxDataChecked = vIsTaxDataChecked,
hasCoreVnl = vHasCoreVnl,
- isEqualizated = FALSE,
- hasDailyInvoice = vHasDailyInvoice
+ isEqualizated = FALSE
ON duplicate KEY UPDATE
payMethodFk = vPayMethodFk,
dueDay = vDueDay,
@@ -51788,24 +51164,20 @@ BEGIN
SELECT ts.saleFk,
ts.itemFk,
CAST(0 AS DECIMAL(10,0)) saleOrder,
- IF(ish.visible > 0 OR iss.id, 1, 100000) *
- IFNULL(p2.pickingOrder, p.pickingOrder) `order`,
- TO_SECONDS(IF(iss.id,
- iss.created - INTERVAL vCurrentYear YEAR,
- ish.created - INTERVAL YEAR(ish.created) YEAR)) priority,
+ (IF(ish.visible > 0 OR iss.id, 1, 100000) *
+ COALESCE(p2.pickingOrder, p.pickingOrder)) `order`,
+ TO_SECONDS(COALESCE(iss.created, ish.created)) - TO_SECONDS(MAKEDATE(IFNULL(YEAR(iss.created), YEAR(ish.created)), 1)) priority,
CONCAT(
- IF(iss.id,
- CONCAT('< ', IFNULL(wk.`code`, '---'),' > '),
- ''),
- p.`code`) COLLATE utf8_general_ci placement,
+ IF(iss.id, CONCAT('< ', COALESCE(wk.`code`, '---'),' > '), ''),
+ p.`code`
+ ) COLLATE utf8_general_ci placement,
sh.priority shelvingPriority,
sh.code COLLATE utf8_general_ci shelving,
ish.created,
ish.visible,
- IFNULL(
- IF(st.code = 'previousByPacking', ish.packing, g.`grouping`),
- 1) `grouping`,
- st.code = 'previousPrepared' isPreviousPrepared,
+ COALESCE(
+ IF(st.code = 'previousByPacking', ish.packing, g.`grouping`),1) `grouping`,
+ (st.code = 'previousPrepared') isPreviousPrepared,
iss.id itemShelvingSaleFk,
ts.ticketFk,
iss.id,
@@ -51813,27 +51185,28 @@ BEGIN
iss.userFk,
ts.quantity
FROM tSale ts
- LEFT JOIN (SELECT DISTINCT saleFk
- FROM saleTracking st
- JOIN state s ON s.id = st.stateFk
- WHERE st.isChecked
- AND s.semaphore = 1) st ON st.saleFk = ts.saleFk
+ LEFT JOIN (SELECT st.saleFk
+ FROM saleTracking st
+ JOIN state s ON s.id = st.stateFk
+ WHERE st.isChecked
+ AND s.semaphore = 1
+ GROUP BY st.saleFk) st ON st.saleFk = ts.saleFk
JOIN itemShelving ish ON ish.itemFk = ts.itemFk
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN sector sc ON sc.id = p.sectorFk
JOIN sectorType st ON st.id = sc.typeFk
JOIN warehouse w ON w.id = sc.warehouseFk
LEFT JOIN tGrouping g ON g.itemFk = ts.itemFk
LEFT JOIN itemShelvingSale iss ON iss.saleFk = ts.saleFk
- AND iss.itemShelvingFk = ish.id
+ AND iss.itemShelvingFk = ish.id
LEFT JOIN worker wk ON wk.id = iss.userFk
LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = ts.saleFk
LEFT JOIN saleGroup sg ON sg.id = sgd.saleGroupFk
LEFT JOIN parking p2 ON p2.id = sg.parkingFk
WHERE w.id = vWarehouseFk
- AND NOT sc.isHideForPickers
- HAVING (iss.id AND st.saleFk) OR salePreviousPrepared IS NULL;
+ AND NOT sc.isHideForPickers
+ AND ((iss.id AND st.saleFk) OR st.saleFk IS NULL);
CREATE OR REPLACE TEMPORARY TABLE tSalePlacementList2
(INDEX(saleFk), INDEX(olderPriority))
@@ -52007,23 +51380,23 @@ BEGIN
WHERE t.id = vTicketFk;
CALL cache.available_refresh(
- vCacheAvailableFk,
+ vCacheAvailableFk,
FALSE,
- vWarehouseFk,
+ vWarehouseFk,
util.VN_CURDATE());
SELECT available INTO vAvailable
FROM cache.available
- WHERE calc_id = vCacheAvailableFk
+ WHERE calc_id = vCacheAvailableFk
AND item_id = vItemFk;
-
+
IF vAvailable < vQuantity THEN
SET vHasThrow = TRUE;
ELSE
SELECT `name`,
- CONCAT(getUser(), ' ', DATE_FORMAT(util.VN_NOW(), '%H:%i'), ' ', name)
+ CONCAT(getUser(), ' ', DATE_FORMAT(util.VN_NOW(), '%H:%i'), ' ', name)
INTO vItemName, vConcept
- FROM item
+ FROM item
WHERE id = vItemFk;
START TRANSACTION;
@@ -52039,7 +51412,7 @@ BEGIN
CALL sale_calculateComponent(vSaleFk, NULL);
CALL itemShelvingSale_addBySale(vSaleFk, vSectorFk);
-
+
IF NOT EXISTS (SELECT TRUE FROM itemShelvingSale WHERE saleFk = vSaleFk LIMIT 1) THEN
SET vHasThrow = TRUE;
END IF;
@@ -52048,13 +51421,13 @@ BEGIN
IF vHasThrow THEN
CALL util.throw("There is no available for the selected item");
END IF;
-
+
IF vSaleGroupFk THEN
INSERT INTO saleGroupDetail
SET saleFk = vSaleFk,
saleGroupFk = vSaleGroupFk;
END IF;
-
+
COMMIT;
END ;;
DELIMITER ;
@@ -52076,7 +51449,7 @@ CREATE DEFINER=`vn`@`localhost` PROCEDURE `collection_assign`(
vUserFk INT,
OUT vCollectionFk INT
)
-BEGIN
+BEGIN
/**
* Comprueba si existen colecciones libres que se ajustan
* al perfil del usuario y le asigna la más antigua.
@@ -52118,6 +51491,12 @@ BEGIN
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-- Si hay colecciones sin terminar, sale del proceso
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
CALL collection_get(vUserFk);
SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, pc.maxNotAssignedCollectionLifeTime
@@ -52191,9 +51570,19 @@ BEGIN
IF vCollectionFk IS NULL THEN
CALL collection_new(vUserFk, vCollectionFk);
- UPDATE `collection`
- SET workerFk = vUserFk
- WHERE id = vCollectionFk;
+ START TRANSACTION;
+
+ SELECT workerFk INTO vCollectionWorker
+ FROM `collection`
+ WHERE id = vCollectionFk FOR UPDATE;
+
+ IF vCollectionWorker IS NULL THEN
+ UPDATE `collection`
+ SET workerFk = vUserFk
+ WHERE id = vCollectionFk;
+ END IF;
+
+ COMMIT;
END IF;
END ;;
DELIMITER ;
@@ -52268,101 +51657,140 @@ CREATE DEFINER=`vn`@`localhost` PROCEDURE `collection_getAssigned`(
)
BEGIN
/**
- * Comprueba si existen colecciones libres que se ajustan al perfil del usuario
- * y le asigna la más antigua.
- * Añade un registro al semillero de colecciones y hace la reserva para la colección
- *
+ * Comprueba si existen colecciones libres que se ajustan
+ * al perfil del usuario y le asigna la más antigua.
+ * Añade un registro al semillero de colecciones.
+ *
* @param vUserFk Id de usuario
* @param vCollectionFk Id de colección
*/
DECLARE vHasTooMuchCollections BOOL;
- DECLARE vItemPackingTypeFk VARCHAR(1);
- DECLARE vWarehouseFk INT;
- DECLARE vLockName VARCHAR(215);
- DECLARE vLockTime INT DEFAULT 30;
+ DECLARE vDone BOOL DEFAULT FALSE;
+ DECLARE vCollectionWorker INT;
+ DECLARE vMaxNotAssignedCollectionLifeTime TIME;
+
+ DECLARE vCollections CURSOR FOR
+ WITH collections AS (
+ SELECT tc.collectionFk,
+ SUM(sv.volume) volume,
+ c.saleTotalCount,
+ c.itemPackingTypeFk,
+ c.trainFk,
+ c.warehouseFk,
+ c.wagons
+ FROM vn.ticketCollection tc
+ JOIN vn.collection c ON c.id = tc.collectionFk
+ JOIN vn.saleVolume sv ON sv.ticketFk = tc.ticketFk
+ WHERE c.workerFk IS NULL
+ AND sv.shipped >= util.VN_CURDATE()
+ GROUP BY tc.collectionFk
+ ) SELECT c.collectionFk
+ FROM collections c
+ JOIN vn.operator o
+ WHERE o.workerFk = vUserFk
+ AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL)
+ AND (c.itemPackingTypeFk = o.itemPackingTypeFk OR o.itemPackingTypeFk IS NULL)
+ AND o.numberOfWagons = c.wagons
+ AND o.trainFk = c.trainFk
+ AND o.warehouseFk = c.warehouseFk;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+ -- Si hay colecciones sin terminar, sale del proceso
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
- IF vLockName IS NOT NULL THEN
- DO RELEASE_LOCK(vLockName);
- END IF;
-
+ ROLLBACK;
RESIGNAL;
END;
- -- Si hay colecciones sin terminar, sale del proceso
CALL collection_get(vUserFk);
- SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0,
- pc.collection_assign_lockname
- INTO vHasTooMuchCollections,
- vLockName
- FROM tmp.collection c
- JOIN productionConfig pc;
+ SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, pc.maxNotAssignedCollectionLifeTime
+ INTO vHasTooMuchCollections, vMaxNotAssignedCollectionLifeTime
+ FROM productionConfig pc
+ LEFT JOIN tmp.collection ON TRUE;
DROP TEMPORARY TABLE tmp.collection;
IF vHasTooMuchCollections THEN
- CALL util.throw('There are pending collections');
- END IF;
-
- SELECT warehouseFk, itemPackingTypeFk
- INTO vWarehouseFk, vItemPackingTypeFk
- FROM operator
- WHERE workerFk = vUserFk;
-
- SET vLockName = CONCAT_WS('/',
- vLockName,
- vWarehouseFk,
- vItemPackingTypeFk
- );
-
- IF NOT GET_LOCK(vLockName, vLockTime) THEN
- CALL util.throw(CONCAT('Cannot get lock: ', vLockName));
+ CALL util.throw('Hay colecciones pendientes');
END IF;
-- Se eliminan las colecciones sin asignar que estan obsoletas
- INSERT INTO ticketTracking(stateFk, ticketFk)
- SELECT s.id, tc.ticketFk
- FROM collection c
- JOIN ticketCollection tc ON tc.collectionFk = c.id
- JOIN state s ON s.code = 'PRINTED_AUTO'
- JOIN productionConfig pc
- WHERE c.workerFk IS NULL
- AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime;
- DELETE c
- FROM collection c
- JOIN productionConfig pc
- WHERE c.workerFk IS NULL
- AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime;
+ INSERT INTO ticketTracking(stateFk, ticketFk)
+ SELECT s.id, tc.ticketFk
+ FROM `collection` c
+ JOIN ticketCollection tc ON tc.collectionFk = c.id
+ JOIN `state` s ON s.code = 'PRINTED_AUTO'
+ WHERE c.workerFk IS NULL
+ AND TIMEDIFF(util.VN_NOW(), c.created) > vMaxNotAssignedCollectionLifeTime;
+
+ DELETE FROM `collection`
+ WHERE workerFk IS NULL
+ AND TIMEDIFF(util.VN_NOW(), created) > vMaxNotAssignedCollectionLifeTime;
-- Se añade registro al semillero
- INSERT INTO collectionHotbed
- SET userFk = vUserFk;
+
+ INSERT INTO collectionHotbed(userFk) VALUES(vUserFk);
-- Comprueba si hay colecciones disponibles que se ajustan a su configuracion
- SELECT MIN(c.id) INTO vCollectionFk
- FROM collection c
- JOIN operator o ON (o.itemPackingTypeFk = c.itemPackingTypeFk
- OR c.itemPackingTypeFk IS NULL)
- AND o.numberOfWagons = c.wagons
- AND o.trainFk = c.trainFk
- AND o.warehouseFk = c.warehouseFk
- AND c.workerFk IS NULL
- WHERE o.workerFk = vUserFk;
+
+ OPEN vCollections;
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH vCollections INTO vCollectionFk;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ BEGIN
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ SET vCollectionFk = NULL;
+ RESIGNAL;
+ END;
+
+ START TRANSACTION;
+
+ SELECT workerFk INTO vCollectionWorker
+ FROM `collection`
+ WHERE id = vCollectionFk FOR UPDATE;
+
+ IF vCollectionWorker IS NULL THEN
+ UPDATE `collection`
+ SET workerFk = vUserFk
+ WHERE id = vCollectionFk;
+
+ COMMIT;
+ LEAVE l;
+ END IF;
+
+ ROLLBACK;
+ END;
+ END LOOP;
+ CLOSE vCollections;
IF vCollectionFk IS NULL THEN
CALL collection_new(vUserFk, vCollectionFk);
+
+ START TRANSACTION;
+
+ SELECT workerFk INTO vCollectionWorker
+ FROM `collection`
+ WHERE id = vCollectionFk FOR UPDATE;
+
+ IF vCollectionWorker IS NULL THEN
+ UPDATE `collection`
+ SET workerFk = vUserFk
+ WHERE id = vCollectionFk;
+ END IF;
+
+ COMMIT;
END IF;
-
- UPDATE collection
- SET workerFk = vUserFk
- WHERE id = vCollectionFk;
-
CALL itemShelvingSale_addByCollection(vCollectionFk);
-
- DO RELEASE_LOCK(vLockName);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -52401,9 +51829,8 @@ BEGIN
SELECT tob.ticketFk, tob.description
FROM vn.ticketObservation tob
JOIN vn.ticketCollection tc ON tc.ticketFk = tob.ticketFk
- LEFT JOIN vn.observationType ot ON ot.id = tob.observationTypeFk
- WHERE ot.`code` = 'itemPicker'
- AND tc.collectionFk = vParamFk
+ JOIN vn.observationType ot ON ot.id = tob.observationTypeFk AND ot.`code` = 'itemPicker'
+ WHERE tc.collectionFk = vParamFk OR tc.ticketFk = vParamFk
)
SELECT t.id ticketFk,
IF(!(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`,
@@ -52411,7 +51838,9 @@ BEGIN
t.warehouseFk,
w.id salesPersonFk,
IFNULL(ob.description,'') observaciones,
- cc.rgb
+ cc.rgb,
+ p.code parkingCode,
+ IF (ps.ticketFk, TRUE, FALSE) isAdvanced
FROM vn.ticket t
LEFT JOIN vn.ticketCollection tc ON t.id = tc.ticketFk
LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk
@@ -52423,17 +51852,22 @@ BEGIN
LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk
LEFT JOIN vn.client c ON c.id = t.clientFk
LEFT JOIN vn.worker w ON w.id = c.salesPersonFk
- LEFT JOIN observation ob ON ob.ticketFk = t.id
+ LEFT JOIN observation ob ON ob.ticketFk = t.id
+ LEFT JOIN vn.ticketParking tp ON tp.ticketFk = t.id
+ LEFT JOIN vn.parking p ON tp.parkingFk = p.id
+ LEFT JOIN vn.packingSiteAdvanced ps ON ps.ticketFk = t.id
WHERE t.id = vParamFk
AND t.shipped >= vYesterday
- UNION ALL
+ UNION
SELECT t.id ticketFk,
IF(NOT(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`,
am.name agencyName,
t.warehouseFk,
w.id salesPersonFk,
ob.description,
- IF(NOT (vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb`
+ IF(NOT (vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb`,
+ p.code parkingCode,
+ IF (ps.ticketFk, TRUE, FALSE) isAdvanced
FROM vn.ticket t
JOIN vn.ticketCollection tc ON t.id = tc.ticketFk
LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk
@@ -52445,16 +51879,21 @@ BEGIN
LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk
LEFT JOIN vn.client c ON c.id = t.clientFk
LEFT JOIN vn.worker w ON w.id = c.salesPersonFk
- LEFT JOIN observation ob ON ob.ticketFk = t.id
+ LEFT JOIN observation ob ON ob.ticketFk = t.id
+ LEFT JOIN vn.ticketParking tp ON tp.ticketFk = t.id
+ LEFT JOIN vn.parking p ON tp.parkingFk = p.id
+ LEFT JOIN vn.packingSiteAdvanced ps ON ps.ticketFk = t.id
WHERE tc.collectionFk = vParamFk
- UNION ALL
+ UNION
SELECT sg.ticketFk,
NULL `level`,
am.name agencyName,
t.warehouseFk,
c.salesPersonFk,
ob.description,
- NULL `rgb`
+ NULL `rgb`,
+ p.code parkingCode,
+ IF (ps.ticketFk, TRUE, FALSE) isAdvanced
FROM vn.sectorCollection sc
JOIN vn.sectorCollectionSaleGroup ss ON ss.sectorCollectionFk = sc.id
JOIN vn.saleGroup sg ON sg.id = ss.saleGroupFk
@@ -52462,9 +51901,13 @@ BEGIN
LEFT JOIN vn.zone z ON z.id = t.zoneFk
LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk
LEFT JOIN observation ob ON ob.ticketFk = t.id
- LEFT JOIN vn.client c ON c.id = t.clientFk
+ LEFT JOIN vn.client c ON c.id = t.clientFk
+ LEFT JOIN vn.ticketParking tp ON tp.ticketFk = t.id
+ LEFT JOIN vn.parking p ON tp.parkingFk = p.id
+ LEFT JOIN vn.packingSiteAdvanced ps ON ps.ticketFk = t.id
WHERE sc.id = vParamFk
- AND t.shipped >= vYesterday;
+ AND t.shipped >= vYesterday
+ GROUP BY ticketFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -52591,7 +52034,7 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_mergeSales`(vCollectionFk INT)
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `collection_mergeSales`(vCollectionFk INT)
BEGIN
DECLARE vDone BOOL;
DECLARE vTicketFk INT;
@@ -52633,7 +52076,10 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `collection_new`(vUserFk INT, OUT vCollectionFk INT)
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `collection_new`(
+ vUserFk INT,
+ OUT vCollectionFk INT
+)
BEGIN
/**
* Genera colecciones de tickets sin asignar trabajador.
@@ -52646,30 +52092,29 @@ BEGIN
DECLARE vLinesLimit INT;
DECLARE vTicketLines INT;
DECLARE vVolumeLimit DECIMAL;
- DECLARE vTicketVolume DECIMAL;
DECLARE vSizeLimit INT;
+ DECLARE vTicketVolume DECIMAL;
DECLARE vMaxTickets INT;
- DECLARE vStateFk VARCHAR(45);
+ DECLARE vStateCode VARCHAR(45);
DECLARE vFirstTicketFk INT;
- DECLARE vHour INT;
- DECLARE vMinute INT;
DECLARE vWorkerCode VARCHAR(3);
- DECLARE vWagonCounter INT DEFAULT 0;
+ DECLARE vWagonCounter INT DEFAULT 1;
DECLARE vTicketFk INT;
DECLARE vItemPackingTypeFk VARCHAR(1);
- DECLARE vHasAssignedTickets BOOLEAN;
+ DECLARE vHasAssignedTickets BOOL;
DECLARE vHasUniqueCollectionTime BOOL;
- DECLARE vDone INT DEFAULT FALSE;
- DECLARE vLockName VARCHAR(215);
- DECLARE vLockTime INT DEFAULT 30;
+ DECLARE vHeight INT;
+ DECLARE vVolume INT;
+ DECLARE vLiters INT;
+ DECLARE vLines INT;
+ DECLARE vTotalLines INT DEFAULT 0;
+ DECLARE vTotalVolume INT DEFAULT 0;
DECLARE vFreeWagonFk INT;
- DECLARE vErrorNumber INT;
- DECLARE vErrorMsg TEXT;
+ DECLARE vDone INT DEFAULT FALSE;
- DECLARE c1 CURSOR FOR
+ DECLARE vTickets CURSOR FOR
SELECT ticketFk, `lines`, m3
FROM tmp.productionBuffer
- WHERE ticketFk <> vFirstTicketFk
ORDER BY HH,
mm,
productionOrder DESC,
@@ -52682,26 +52127,6 @@ BEGIN
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
- DECLARE EXIT HANDLER FOR SQLEXCEPTION
- BEGIN
- GET DIAGNOSTICS CONDITION 1
- vErrorNumber = MYSQL_ERRNO,
- vErrorMsg = MESSAGE_TEXT;
-
- CALL util.debugAdd('collection_new', JSON_OBJECT(
- 'errorNumber', vErrorNumber,
- 'errorMsg', vErrorMsg,
- 'lockName', vLockName,
- 'userFk', vUserFk,
- 'ticketFk', vTicketFk
- )); -- Tmp
-
- IF vLockName IS NOT NULL THEN
- DO RELEASE_LOCK(vLockName);
- END IF;
- RESIGNAL;
- END;
-
SELECT pc.ticketTrolleyMax * o.numberOfWagons,
pc.hasUniqueCollectionTime,
w.code,
@@ -52712,36 +52137,26 @@ BEGIN
o.trainFk,
o.linesLimit,
o.volumeLimit,
- o.sizeLimit,
- pc.collection_new_lockname
+ o.sizeLimit
INTO vMaxTickets,
- vHasUniqueCollectionTime,
- vWorkerCode,
- vWarehouseFk,
- vItemPackingTypeFk,
- vStateFk,
- vWagons,
- vTrainFk,
- vLinesLimit,
- vVolumeLimit,
- vSizeLimit,
- vLockName
- FROM productionConfig pc
- JOIN worker w ON w.id = vUserFk
+ vHasUniqueCollectionTime,
+ vWorkerCode,
+ vWarehouseFk,
+ vItemPackingTypeFk,
+ vStateCode,
+ vWagons,
+ vTrainFk,
+ vLinesLimit,
+ vVolumeLimit,
+ vSizeLimit
+ FROM worker w
+ JOIN operator o ON o.workerFk = w.id
JOIN state st ON st.`code` = 'ON_PREPARATION'
- JOIN operator o ON o.workerFk = vUserFk;
-
- SET vLockName = CONCAT_WS('/',
- vLockName,
- vWarehouseFk,
- vItemPackingTypeFk
- );
-
- IF NOT GET_LOCK(vLockName, vLockTime) THEN
- CALL util.throw(CONCAT('Cannot get lock: ', vLockName));
- END IF;
+ JOIN productionConfig pc
+ WHERE w.id = vUserFk;
-- Se prepara el tren, con tantos vagones como sea necesario.
+
CREATE OR REPLACE TEMPORARY TABLE tTrain
(wagon INT,
shelve INT,
@@ -52752,63 +52167,62 @@ BEGIN
PRIMARY KEY(wagon, shelve))
ENGINE = MEMORY;
- WHILE vWagons > vWagonCounter DO
- SET vWagonCounter = vWagonCounter + 1;
-
- INSERT INTO tTrain(wagon, shelve, liters, `lines`, height)
- SELECT vWagonCounter, cv.`level` , cv.liters , cv.`lines` , cv.height
- FROM collectionVolumetry cv
- WHERE cv.trainFk = vTrainFk
+ INSERT INTO tTrain (wagon, shelve, liters, `lines`, height)
+ WITH RECURSIVE wagonSequence AS (
+ SELECT vWagonCounter wagon
+ UNION ALL
+ SELECT wagon + 1 wagon
+ FROM wagonSequence
+ WHERE wagon < vWagonCounter + vWagons -1
+ )
+ SELECT ws.wagon, cv.`level`, cv.liters, cv.`lines`, cv.height
+ FROM wagonSequence ws
+ JOIN vn.collectionVolumetry cv ON cv.trainFk = vTrainFk
AND cv.itemPackingTypeFk = vItemPackingTypeFk;
- END WHILE;
-- Esto desaparecerá cuando tengamos la table cache.ticket
+
CALL productionControl(vWarehouseFk, 0);
ALTER TABLE tmp.productionBuffer
ADD COLUMN liters INT,
ADD COLUMN height INT;
- -- Se obtiene nº de colección.
- INSERT INTO collection
- SET itemPackingTypeFk = vItemPackingTypeFk,
- trainFk = vTrainFk,
- wagons = vWagons,
- warehouseFk = vWarehouseFk;
-
- SELECT LAST_INSERT_ID() INTO vCollectionFk;
-
-- Los tickets de recogida en Algemesí sólo se sacan si están asignados.
-- Los pedidos con riesgo no se sacan aunque se asignen.
- DELETE pb.*
+
+ DELETE pb
FROM tmp.productionBuffer pb
JOIN state s ON s.id = pb.state
WHERE (pb.agency = 'REC_ALGEMESI'
AND s.code <> 'PICKER_DESIGNED')
OR pb.problem LIKE '%RIESGO%';
- -- Comprobamos si hay tickets asignados. En ese caso, nos centramos
- -- exclusivamente en esos tickets y los sacamos independientemente
- -- de problemas o tamaños
- SELECT COUNT(*) INTO vHasAssignedTickets
- FROM tmp.productionBuffer pb
- JOIN state s ON s.id = pb.state
- WHERE s.code = 'PICKER_DESIGNED'
- AND pb.workerCode = vWorkerCode;
+ -- Si hay tickets asignados, nos centramos exclusivamente en esos tickets
+ -- y los sacamos independientemente de problemas o tamaños
+
+ SELECT EXISTS (
+ SELECT TRUE
+ FROM tmp.productionBuffer pb
+ JOIN state s ON s.id = pb.state
+ WHERE (s.code = 'PICKER_DESIGNED'
+ AND pb.workerCode = vWorkerCode)
+ OR s.code = 'LAST_CALL'
+ ) INTO vHasAssignedTickets;
-- Se dejan en la tabla tmp.productionBuffer sólo aquellos tickets adecuados
+
IF vHasAssignedTickets THEN
- DELETE pb.*
+ DELETE pb
FROM tmp.productionBuffer pb
JOIN state s ON s.id = pb.state
- WHERE s.code <> 'PICKER_DESIGNED'
- OR pb.workerCode <> vWorkerCode;
+ WHERE (s.code <> 'PICKER_DESIGNED'
+ OR pb.workerCode <> vWorkerCode)
+ AND s.code <> 'LAST_CALL';
ELSE
- DELETE pb.*
+ DELETE pb
FROM tmp.productionBuffer pb
JOIN state s ON s.id = pb.state
- JOIN agencyMode am ON am.id = pb.agencyModeFk
- JOIN agency a ON a.id = am.agencyFk
LEFT JOIN (
SELECT pb.ticketFk, MAX(i.`size`) maxSize
FROM tmp.productionBuffer pb
@@ -52819,7 +52233,7 @@ BEGIN
) sub ON sub.ticketFk = pb.ticketFk
JOIN productionConfig pc
WHERE pb.shipped <> util.VN_CURDATE()
- OR (pb.ubicacion IS NULL AND a.isOwn)
+ OR pb.ubicacion IS NULL
OR (NOT s.isPreparable AND NOT s.isPrintable)
OR pb.collectionH IS NOT NULL
OR pb.collectionV IS NOT NULL
@@ -52827,26 +52241,25 @@ BEGIN
OR (NOT pb.H AND pb.V > 0 AND vItemPackingTypeFk = 'H')
OR (NOT pb.V AND vItemPackingTypeFk = 'V')
OR (pc.isPreviousPreparationRequired AND pb.previousWithoutParking)
- OR LENGTH(pb.problem) > 0
+ OR LENGTH(pb.problem)
OR pb.lines > vLinesLimit
OR pb.m3 > vVolumeLimit
OR sub.maxSize > vSizeLimit
OR pb.hasPlantTray;
END IF;
- -- Es importante que el primer ticket se coja en todos los casos
- SELECT ticketFk,
- HH,
- mm,
- `lines`,
- m3
- INTO vFirstTicketFk,
- vHour,
- vMinute,
- vTicketLines,
- vTicketVolume
+ -- Hay que excluir aquellos que no tengan la misma hora de preparacion, si procede
+
+ IF vHasUniqueCollectionTime THEN
+ DELETE pb
+ FROM tmp.productionBuffer pb
+ JOIN tmp.productionBuffer pb2 ON pb2.ticketFk = vFirstTicketFk
+ AND (pb.HH <> pb2.HH OR pb.mm <> pb2.mm);
+ END IF;
+
+ SELECT ticketFk INTO vFirstTicketFk
FROM tmp.productionBuffer
- ORDER BY HH,
+ ORDER BY HH,
mm,
productionOrder DESC,
m3 DESC,
@@ -52856,44 +52269,37 @@ BEGIN
ticketFk
LIMIT 1;
- -- Hay que excluir aquellos que no tengan la misma hora de preparacion, si procede
- IF vHasUniqueCollectionTime THEN
- DELETE FROM tmp.productionBuffer
- WHERE HH <> vHour
- OR mm <> vMinute;
- END IF;
-
- SET vTicketFk = vFirstTicketFk;
- SET @lines = 0;
- SET @volume = 0;
-
- OPEN c1;
- read_loop: LOOP
+ OPEN vTickets;
+ l: LOOP
SET vDone = FALSE;
+ FETCH vTickets INTO vTicketFk, vTicketLines, vTicketVolume;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
-- Buscamos un ticket que cumpla con los requisitos en el listado
- IF ((vTicketLines + @lines) <= vLinesLimit OR vLinesLimit IS NULL)
- AND ((vTicketVolume + @volume) <= vVolumeLimit OR vVolumeLimit IS NULL) THEN
+
+ IF (vLinesLimit IS NULL OR (vTotalLines + vTicketLines) <= vLinesLimit)
+ AND (vVolumeLimit IS NULL OR (vTotalVolume + vTicketVolume) <= vVolumeLimit) THEN
CALL ticket_splitItemPackingType(vTicketFk, vItemPackingTypeFk);
DROP TEMPORARY TABLE tmp.ticketIPT;
+ SELECT COUNT(*), SUM(litros), MAX(i.`size`), SUM(sv.volume)
+ INTO vLines, vLiters, vHeight, vVolume
+ FROM saleVolume sv
+ JOIN sale s ON s.id = sv.saleFk
+ JOIN item i ON i.id = s.itemFk
+ WHERE sv.ticketFk = vTicketFk;
+
+ SET vTotalVolume = vTotalVolume + vVolume,
+ vTotalLines = vTotalLines + vLines;
+
UPDATE tmp.productionBuffer pb
- JOIN (
- SELECT SUM(litros) liters,
- @lines:= COUNT(*) + @lines,
- COUNT(*) `lines`,
- MAX(i.`size`) height,
- @volume := SUM(sv.volume) + @volume,
- SUM(sv.volume) volume
- FROM saleVolume sv
- JOIN sale s ON s.id = sv.saleFk
- JOIN item i ON i.id = s.itemFk
- WHERE sv.ticketFk = vTicketFk
- ) sub
- SET pb.liters = sub.liters,
- pb.`lines` = sub.`lines`,
- pb.height = sub.height
+ SET pb.liters = vLiters,
+ pb.`lines` = vLines,
+ pb.height = vHeight
WHERE pb.ticketFk = vTicketFk;
UPDATE tTrain tt
@@ -52910,17 +52316,13 @@ BEGIN
tt.height
LIMIT 1;
- -- Si no le encuentra una balda adecuada, intentamos darle un carro entero si queda alguno libre
+ -- Si no le encuentra una balda, intentamos darle un carro entero libre
+
IF NOT (SELECT COUNT(*) FROM tTrain WHERE ticketFk) THEN
- SELECT tt.wagon
- INTO vFreeWagonFk
- FROM tTrain tt
- LEFT JOIN (
- SELECT DISTINCT wagon
- FROM tTrain
- WHERE ticketFk IS NOT NULL
- ) nn ON nn.wagon = tt.wagon
- WHERE nn.wagon IS NULL
+ SELECT wagon INTO vFreeWagonFk
+ FROM tTrain
+ GROUP BY wagon
+ HAVING COUNT(ticketFk) = 0
ORDER BY wagon
LIMIT 1;
@@ -52929,38 +52331,35 @@ BEGIN
SET ticketFk = vFirstTicketFk
WHERE wagon = vFreeWagonFk;
- -- Se anulan el resto de carros libres para que sólo uno lleve un pedido excesivo
- DELETE tt.*
- FROM tTrain tt
- LEFT JOIN (
- SELECT DISTINCT wagon
- FROM tTrain
- WHERE ticketFk IS NOT NULL
- ) nn ON nn.wagon = tt.wagon
- WHERE nn.wagon IS NULL;
- END IF;
- END IF;
+ -- Se anulan el resto de carros libres,
+ -- máximo un carro con pedido excesivo
- FETCH c1 INTO vTicketFk, vTicketLines, vTicketVolume;
- IF vDone OR NOT (SELECT COUNT(*) FROM tTrain WHERE ticketFk IS NULL) THEN
- LEAVE read_loop;
- END IF;
- ELSE
- FETCH c1 INTO vTicketFk, vTicketLines, vTicketVolume;
- IF vDone THEN
- LEAVE read_loop;
- END IF;
+ DELETE tt
+ FROM tTrain tt
+ JOIN (SELECT wagon
+ FROM tTrain
+ GROUP BY wagon
+ HAVING COUNT(ticketFk) = 0
+ ) sub ON sub.wagon = tt.wagon;
+ END IF;
+ END IF;
END IF;
END LOOP;
- CLOSE c1;
+ CLOSE vTickets;
IF (SELECT COUNT(*) FROM tTrain WHERE ticketFk) THEN
- UPDATE collection c
- JOIN state st ON st.code = 'ON_PREPARATION'
- SET c.stateFk = st.id
- WHERE c.id = vCollectionFk;
+ -- Se obtiene nº de colección
+
+ INSERT INTO collection
+ SET itemPackingTypeFk = vItemPackingTypeFk,
+ trainFk = vTrainFk,
+ wagons = vWagons,
+ warehouseFk = vWarehouseFk;
+
+ SELECT LAST_INSERT_ID() INTO vCollectionFk;
-- Asigna las bandejas
+
INSERT IGNORE INTO ticketCollection(ticketFk, collectionFk, `level`, wagon, liters)
SELECT tt.ticketFk, vCollectionFk, tt.shelve, tt.wagon, tt.liters
FROM tTrain tt
@@ -52968,37 +52367,34 @@ BEGIN
ORDER BY tt.wagon, tt.shelve;
-- Actualiza el estado de los tickets
- CALL collection_setState(vCollectionFk, vStateFk);
+
+ CALL collection_setState(vCollectionFk, vStateCode);
-- Aviso para la preparacion previa
+
INSERT INTO ticketDown(ticketFk, collectionFk)
SELECT tc.ticketFk, tc.collectionFk
FROM ticketCollection tc
WHERE tc.collectionFk = vCollectionFk;
- CALL sales_mergeByCollection(vCollectionFk);
+ CALL collection_mergeSales(vCollectionFk);
UPDATE `collection` c
- JOIN (
+ JOIN(
SELECT COUNT(*) saleTotalCount,
SUM(s.isPicked <> 0) salePickedCount
FROM ticketCollection tc
JOIN sale s ON s.ticketFk = tc.ticketFk
- WHERE tc.collectionFk = vCollectionFk
- AND s.quantity > 0
- ) sub
+ WHERE tc.collectionFk = vCollectionFk
+ AND s.quantity > 0
+ )sub
SET c.saleTotalCount = sub.saleTotalCount,
c.salePickedCount = sub.salePickedCount
WHERE c.id = vCollectionFk;
-
ELSE
- DELETE FROM `collection`
- WHERE id = vCollectionFk;
- SET vCollectionFk = NULL;
+ SET vCollectionFk = NULL;
END IF;
- DO RELEASE_LOCK(vLockName);
-
DROP TEMPORARY TABLE
tTrain,
tmp.productionBuffer;
@@ -53739,7 +53135,7 @@ BEGIN
SELECT * FROM (
SELECT cc.client clientFk, ci.grade
FROM creditClassification cc
- JOIN creditInsurance ci ON cc.id = ci.creditClassification
+ JOIN creditInsurance ci ON cc.id = ci.creditClassificationFk
WHERE dateEnd IS NULL
ORDER BY ci.creationDate DESC
LIMIT 10000000000000000000) t1
@@ -55223,7 +54619,6 @@ BEGIN
supplierFk,
dated,
isExcludedFromAvailable,
- isRaid,
commission,
currencyFk,
companyFk,
@@ -55234,7 +54629,6 @@ BEGIN
supplierFk,
dated,
isExcludedFromAvailable,
- isRaid,
commission,
currencyFk,
companyFk,
@@ -55441,7 +54835,7 @@ CREATE DEFINER=`vn`@`localhost` PROCEDURE `entry_getTransfer`(
BEGIN
/**
* Retorna los artículos trasladables a partir de una entrada.
- *
+ *
* @param vSelf Id de entrada
*/
DECLARE vDateShipped DATE;
@@ -55602,7 +54996,7 @@ BEGIN
LEFT JOIN tmp.buyUltimateFromInterval bufi ON bufi.itemFk = i.id
LEFT JOIN buy b3 ON b3.id = bufi.buyFk
WHERE ic.display
- AND NOT e.isRaid
+ AND NOT tr.isRaid
AND (ti.visible OR ti.available)
ORDER BY i.typeFk, i.name, i.id, i.size, i.category, o.name;
@@ -55664,17 +55058,19 @@ BEGIN
*
* @param vSelf Id de entrada
*/
- DECLARE vIsEditable BOOL;
+ DECLARE vIsNotEditable BOOL DEFAULT FALSE;
- SELECT e.isBooked INTO vIsEditable
+ SELECT TRUE INTO vIsNotEditable
FROM `entry` e
- JOIN entryType et ON et.code = e.typeFk
- WHERE NOT et.isInformal
- AND e.id = vSelf;
+ LEFT JOIN entryType et ON et.code = e.typeFk
+ WHERE e.id = vSelf
+ AND e.isBooked
+ AND (e.typeFk IS NULL OR NOT et.isInformal);
- IF vIsEditable AND NOT IFNULL(@isModeInventory, FALSE) THEN
+ IF vIsNotEditable AND NOT IFNULL(@isModeInventory, FALSE) THEN
CALL util.throw(CONCAT('Entry ', vSelf, ' is not editable'));
END IF;
+
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -55995,12 +55391,17 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `entry_splitByShelving`(vShelvingFk VARCHAR(3), vFromEntryFk INT, vToEntryFk INT)
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `entry_splitByShelving`(
+ vShelvingCode VARCHAR(10),
+ vFromEntryFk INT,
+ vToEntryFk INT
+)
BEGIN
/**
- * Divide las compras entre dos entradas de acuerdo con lo ubicado en una matr�cula
+ * Divide las compras entre dos entradas de
+ * acuerdo con lo ubicado en una matricula.
*
- * @param vShelvingFk Identificador de vn.shelving
+ * @param vShelvingCode Código de vn.shelving
* @param vFromEntryFk Entrada origen
* @param vToEntryFk Entrada destino
*/
@@ -56010,16 +55411,17 @@ BEGIN
DECLARE vDone BOOLEAN DEFAULT FALSE;
DECLARE cur CURSOR FOR
- SELECT bb.id buyFk,
+ SELECT bb.id buyFk,
LEAST(bb.stickers, FLOOR(ish.visible / ish.packing)) ishStickers,
bb.stickers buyStickers
FROM itemShelving ish
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN (SELECT b.id, b.itemFk, b.stickers
FROM buy b
WHERE b.entryFk = vFromEntryFk
ORDER BY b.stickers DESC
LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk
- WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci
+ WHERE sh.code = vShelvingCode COLLATE utf8_general_ci
AND NOT ish.isSplit
GROUP BY ish.id;
@@ -56103,9 +55505,10 @@ BEGIN
UPDATE buy SET printedStickers = vIshStickers WHERE id = LAST_INSERT_ID();
END IF;
- UPDATE itemShelving
- SET isSplit = TRUE
- WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci;
+ UPDATE itemShelving ish
+ JOIN shelving sh ON sh.id = ish.shelvingFk
+ SET ish.isSplit = TRUE
+ WHERE sh.code = vShelvingCode COLLATE utf8_general_ci;
END LOOP;
CLOSE cur;
END ;;
@@ -56220,7 +55623,7 @@ BEGIN
FROM vn.entry e
JOIN vn.travel t ON t.id = e.travelFk
JOIN vn.warehouse w ON w.id = t.warehouseInFk
- WHERE t.shipped >= util.VN_CURDATE()
+ WHERE t.landed >= util.VN_CURDATE()
AND e.currencyFk = vCurrency
AND NOT e.isBooked;
@@ -56231,7 +55634,7 @@ BEGIN
SET e.commission = vComission;
SELECT `name` INTO vCurrencyName
- FROM currency
+ FROM currency
WHERE id = vCurrency;
CALL entry_recalc();
@@ -56312,22 +55715,26 @@ CREATE DEFINER=`vn`@`localhost` PROCEDURE `expeditionPallet_build`(
vWorkerFk INT,
OUT vPalletFk INT
)
-BEGIN
-/** Construye un pallet de expediciones.
+proc: BEGIN
+/**
+ * Builds an expedition pallet.
*
- * Primero comprueba si esas expediciones ya pertenecen a otro pallet,
- * en cuyo caso actualiza ese pallet.
+ * First, it checks if these expeditions already belong to another pallet,
+ * in which case it returns an error.
*
- * @param vExpeditions JSON_ARRAY con esta estructura [exp1, exp2, exp3, ...]
- * @param vArcId INT Identificador de arcRead
- * @param vWorkerFk INT Identificador de worker
- * @param out vPalletFk Identificador de expeditionPallet
+ * @param vExpeditions JSON_ARRAY with this structure [exp1, exp2, exp3, ...]
+ * @param vArcId INT Identifier of arcRead
+ * @param vWorkerFk INT Identifier of worker
+ * @param out vPalletFk Identifier of expeditionPallet
*/
+
DECLARE vCounter INT;
DECLARE vExpeditionFk INT;
DECLARE vTruckFk INT;
DECLARE vPrinterFk INT;
DECLARE vExpeditionStateTypeFk INT;
+ DECLARE vFreeExpeditionCount INT;
+ DECLARE vExpeditionWithPallet INT;
CREATE OR REPLACE TEMPORARY TABLE tExpedition (
expeditionFk INT,
@@ -56351,48 +55758,63 @@ BEGIN
WHERE e.id = vExpeditionFk;
END WHILE;
- SELECT palletFk INTO vPalletFk
- FROM (
- SELECT palletFk, count(*) n
- FROM tExpedition
- WHERE palletFk > 0
- GROUP BY palletFk
- ORDER BY n DESC
- LIMIT 100
- ) sub
- LIMIT 1;
+ SELECT COUNT(expeditionFk) INTO vFreeExpeditionCount
+ FROM tExpedition
+ WHERE palletFk IS NULL;
- IF vPalletFk IS NULL THEN
- SELECT roadmapStopFk INTO vTruckFk
- FROM (
- SELECT rm.roadmapStopFk, count(*) n
- FROM routesMonitor rm
- JOIN tExpedition e ON e.routeFk = rm.routeFk
- GROUP BY roadmapStopFk
- ORDER BY n DESC
- LIMIT 1
- ) sub;
+ SELECT COUNT(expeditionFk) INTO vExpeditionWithPallet
+ FROM tExpedition
+ WHERE palletFk;
- IF vTruckFk IS NULL THEN
- CALL util.throw ('TRUCK_NOT_AVAILABLE');
- END IF;
-
- INSERT INTO expeditionPallet SET truckFk = vTruckFk;
-
- SET vPalletFk = LAST_INSERT_ID();
+ IF vExpeditionWithPallet THEN
+ UPDATE arcRead
+ SET error = (
+ SELECT GROUP_CONCAT(expeditionFk SEPARATOR ', ')
+ FROM tExpedition
+ WHERE palletFk
+ )
+ WHERE id = vArcId;
+ LEAVE proc;
END IF;
+ IF NOT vFreeExpeditionCount THEN
+ CALL util.throw ('NO_FREE_EXPEDITIONS');
+ END IF;
+
+ SELECT roadmapStopFk INTO vTruckFk
+ FROM (
+ SELECT rm.roadmapStopFk, count(*) n
+ FROM routesMonitor rm
+ JOIN tExpedition e ON e.routeFk = rm.routeFk
+ WHERE e.palletFk IS NULL
+ GROUP BY roadmapStopFk
+ ORDER BY n DESC
+ LIMIT 1
+ ) sub;
+
+ IF vTruckFk IS NULL THEN
+ CALL util.throw ('TRUCK_NOT_AVAILABLE');
+ END IF;
+
+ INSERT INTO expeditionPallet SET truckFk = vTruckFk;
+
+ SET vPalletFk = LAST_INSERT_ID();
+
INSERT INTO expeditionScan(expeditionFk, palletFk, workerFk)
SELECT expeditionFk, vPalletFk, vWorkerFk
FROM tExpedition
- ON DUPLICATE KEY UPDATE palletFk = vPalletFk, workerFk = vWorkerFk;
+ WHERE palletFk IS NULL;
SELECT id INTO vExpeditionStateTypeFk
FROM expeditionStateType
WHERE code = 'PALLETIZED';
-
+
INSERT INTO expeditionState(expeditionFk, typeFk)
- SELECT expeditionFk, vExpeditionStateTypeFk FROM tExpedition;
+ SELECT expeditionFk, vExpeditionStateTypeFk
+ FROM tExpedition
+ WHERE palletFk IS NULL;
+
+ UPDATE arcRead SET error = NULL WHERE id = vArcId;
SELECT printerFk INTO vPrinterFk FROM arcRead WHERE id = vArcId;
@@ -56651,12 +56073,12 @@ CREATE DEFINER=`vn`@`localhost` PROCEDURE `expeditionScan_Put`(
vExpeditionFk INT
)
BEGIN
- IF NOT (SELECT TRUE FROM expedition WHERE id = vExpeditionFk LIMIT 1) THEN
- CALL util.throw('Expedition not exists');
+ IF NOT EXISTS (SELECT id FROM expeditionPallet WHERE id = vPalletFk) THEN
+ CALL util.throw('Pallet not exists');
END IF;
- IF NOT (SELECT TRUE FROM expeditionPallet WHERE id = vPalletFk LIMIT 1) THEN
- CALL util.throw('Pallet not exists');
+ IF NOT EXISTS (SELECT id FROM expedition WHERE id = vExpeditionFk) THEN
+ CALL util.throw('Expedition not exists');
END IF;
REPLACE expeditionScan(expeditionFk, palletFk)
@@ -56880,7 +56302,8 @@ BEGIN
a.nickname,
sub2.itemPackingTypeConcat,
est.code,
- es.isScanned
+ es2.isScanned,
+ es2.scanOrder
FROM expedition e
JOIN ticket t ON t.id = e.ticketFk
JOIN ticketState ts ON ts.ticketFk = e.ticketFk
@@ -56902,8 +56325,9 @@ BEGIN
SELECT MAX(id)
FROM expeditionState es
WHERE expeditionFk = e.id)
+ LEFT JOIN expeditionState es2 ON es2.id = es.id
WHERE t.routeFk = vRouteFk AND e.freightItemFk <> FALSE
- ORDER BY r.created, t.priority DESC;
+ ORDER BY r.dated, t.priority DESC;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -56982,6 +56406,114 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `expedition_selfConsumptionPackaging` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `expedition_selfConsumptionPackaging`(
+ vSelf INT,
+ vAction ENUM('add', 'remove')
+)
+proc:BEGIN
+/**
+ * Maneja el consumo de cajas para autoconsumo, permitiendo
+ * añadir o quitar cajas utilizadas según la acción indicada.
+ *
+ * @param vSelf Id de expedición
+ */
+ DECLARE vClientFk INT;
+ DECLARE vAddressFk INT;
+ DECLARE vItemFk INT;
+ DECLARE vItemName VARCHAR(50);
+ DECLARE vWarehouseFk INT;
+ DECLARE vCreated DATE;
+ DECLARE vTicketFk INT;
+ DECLARE vSaleFk INT;
+ DECLARE vQuantity INT;
+
+ IF vAction NOT IN ('add', 'remove') THEN
+ CALL util.throw('Action not supported');
+ END IF;
+
+ SELECT pc.clientSelfConsumptionFk,
+ pc.addressSelfConsumptionFk,
+ i.id,
+ i.name,
+ t.warehouseFk,
+ e.created
+ INTO vClientFk,
+ vAddressFk,
+ vItemFk,
+ vItemName,
+ vWarehouseFk,
+ vCreated
+ FROM expedition e
+ LEFT JOIN packaging p ON p.id = e.packagingFk
+ LEFT JOIN item i ON i.id = p.itemFk
+ JOIN ticket t ON t.id = e.ticketFk
+ JOIN productionConfig pc
+ WHERE e.id = vSelf;
+
+ IF vClientFk IS NULL OR vItemFk IS NULL THEN
+ LEAVE proc;
+ END IF;
+
+ SET vCreated = DATE(vCreated);
+
+ SELECT id INTO vTicketFk
+ FROM ticket
+ WHERE shipped BETWEEN vCreated AND util.dayEnd(vCreated)
+ AND clientFk = vClientFk
+ AND addressFk = vAddressFk
+ AND warehouseFk = vWarehouseFk
+ AND nickname = 'CAJAS AUTOCONSUMO'
+ LIMIT 1;
+
+ IF vTicketFk IS NULL AND vAction = 'add' THEN
+ INSERT INTO ticket(clientFk, warehouseFk, shipped, nickname, addressFk)
+ VALUES (vClientFk, vWarehouseFk, vCreated, 'CAJAS AUTOCONSUMO', vAddressFk);
+
+ SET vTicketFk = LAST_INSERT_ID();
+ END IF;
+
+ SELECT id, quantity INTO vSaleFk, vQuantity
+ FROM sale
+ WHERE itemFk = vItemFk
+ AND ticketFk = vTicketFk
+ LIMIT 1;
+
+ IF vAction = 'add' THEN
+ IF vSaleFk IS NOT NULL THEN
+ UPDATE sale
+ SET quantity = quantity + 1
+ WHERE id = vSaleFk;
+ ELSE
+ INSERT INTO sale(itemFk, ticketFk, concept, quantity)
+ VALUES (vItemFk, vTicketFk, vItemName, 1);
+ END IF;
+ ELSE
+ IF vSaleFk IS NOT NULL THEN
+ IF vQuantity > 1 THEN
+ UPDATE sale
+ SET quantity = quantity - 1
+ WHERE id = vSaleFk;
+ ELSE
+ DELETE FROM sale WHERE id = vSaleFk;
+ END IF;
+ 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_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expedition_StateGet` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -57540,7 +57072,7 @@ BEGIN
JOIN travel tr ON tr.id = e.travelFk
WHERE tr.warehouseInFk = vWarehouseFk
AND tr.landed BETWEEN vDateLastInventory AND vDateYesterday
- AND NOT isRaid
+ AND NOT tr.isRaid
GROUP BY b.itemFk;
-- Transfers
@@ -57553,7 +57085,7 @@ BEGIN
JOIN travel tr ON tr.id = e.travelFk
WHERE tr.warehouseOutFk = vWarehouseFk
AND tr.shipped BETWEEN vDateLastInventory AND vDateYesterday
- AND NOT isRaid
+ AND NOT tr.isRaid
GROUP BY b.itemFk
) sub
ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity, 0) + sub.quantityOut;
@@ -58571,7 +58103,7 @@ BEGIN
) eWithheld ON TRUE
WHERE tii.taxTypeSageFk IS NOT NULL
AND (tii.taxCode IS NULL OR tii.taxCode NOT IN ('import10', 'import21'))
- GROUP BY tii.PorcentajeIva, tii.expenseFk;
+ GROUP BY tii.CuentaIvaRepercutido;
-- Línea iva inversor sujeto pasivo
INSERT INTO XDiario(
@@ -58636,7 +58168,7 @@ BEGIN
AND NOT(tii.isVies
AND c.nontaxableTransactionTypeFk = tii.transactionTypeSageFk
AND tii.taxCode = 'nonTaxable')
- GROUP BY tii.PorcentajeIva, tii.expenseFk;
+ GROUP BY tii.CuentaIvaRepercutido;
-- Actualización del registro original
UPDATE invoiceIn ii
@@ -59500,6 +59032,75 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `invoiceOut_newFromAddress` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `invoiceOut_newFromAddress`(
+ IN vAddressFk INT,
+ IN vSerial CHAR(2),
+ IN vMaxShipped DATE,
+ IN vCompanyFk INT,
+ IN vTaxArea VARCHAR(25),
+ IN vRef VARCHAR(25),
+ OUT vInvoiceId INT)
+BEGIN
+/**
+ * Factura los tickets de un consignatario hasta una fecha dada
+ * @param vAddressFk Id del consignatario a facturar
+ * @param vSerial Serie de factura
+ * @param vMaxShipped Fecha hasta la cual cogerá tickets para facturar
+ * @param vCompanyFk Id de la empresa desde la que se factura
+ * @param vTaxArea Tipo de iva en relacion a la empresa y al cliente, NULL por defecto
+ * @param vRef Referencia de la factura en caso que se quiera forzar, NULL por defecto
+ * @return vInvoiceId factura
+ */
+ DECLARE vIsRefEditable BOOLEAN;
+
+ IF vRef IS NOT NULL AND vSerial IS NOT NULL THEN
+ SELECT isRefEditable INTO vIsRefEditable
+ FROM invoiceOutSerial
+ WHERE code = vSerial;
+
+ IF NOT vIsRefEditable THEN
+ CALL util.throw('serial non editable');
+ END IF;
+ END IF;
+
+ DROP TEMPORARY TABLE IF EXISTS `tmp`.`ticketToInvoice`;
+ CREATE TEMPORARY TABLE `tmp`.`ticketToInvoice`
+ (PRIMARY KEY (`id`))
+ ENGINE = MEMORY
+ SELECT id FROM ticket t
+ WHERE t.addressFk = vAddressFk
+ AND t.refFk IS NULL
+ AND t.companyFk = vCompanyFk
+ AND t.shipped BETWEEN
+ util.firstDayOfYear(vMaxShipped - INTERVAL 1 YEAR)
+ AND util.dayend(vMaxShipped);
+
+ CALL invoiceOut_new(vSerial, util.VN_CURDATE(), vTaxArea, vInvoiceId);
+
+ UPDATE invoiceOut
+ SET `ref` = vRef
+ WHERE id = vInvoiceId
+ AND vRef IS NOT NULL;
+
+ IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN
+ CALL invoiceOutBooking(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 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceOut_newFromClient` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -59697,7 +59298,7 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `itemFuentesBalance` */;
+/*!50003 DROP PROCEDURE IF EXISTS `itemCampaign_add` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
@@ -59705,82 +59306,57 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemFuentesBalance`(vDaysInFuture INT)
-BEGIN
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemCampaign_add`()
+proc: BEGIN
+/**
+ * Añade registros a tabla itemCampaign.
+ *
+ * @param vDateFrom Fecha desde
+ * @param vDateTo Fecha hasta
+ * @param vCampaign Código de la campaña
+ */
+ DECLARE vYesterday DATE;
+ DECLARE vCampaign VARCHAR(100);
+ DECLARE vScopeDays INT;
+ DECLARE vPreviousDays INT;
+ DECLARE vDateSumFrom DATE;
+ DECLARE vDateSumTo DATE;
- /* Se utiliza para calcular la necesidad de mover mercancia entre el almacén de fuentes y el nuestro
- *
- * @param vDaysInFuture Rango de dias para calcular entradas y salidas
- *
- */
-
- DECLARE vWarehouseFk INT;
+ SET vYesterday = util.yesterday();
- SELECT s.warehouseFk INTO vWarehouseFk
- FROM vn.sector s
- WHERE s.code = 'FUENTES_PICASSE';
-
- CALL cache.stock_refresh(FALSE);
+ SELECT dated, code, scopeDays, previousDays
+ INTO vDateSumTo, vCampaign, vScopeDays, vPreviousDays
+ FROM campaign
+ WHERE dated >= vYesterday
+ ORDER BY dated
+ LIMIT 1;
- SELECT i.id itemFk,
- i.longName,
- i.size,
- i.subName,
- v.amount - IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as visible,
- fue.Fuentes,
- alb.Albenfruit,
- sale.venta,
- IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as compra,
- IFNULL(v.amount,0) + IFNULL(sale.venta,0) + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0)
- - IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as saldo
- FROM vn.item i
- JOIN vn.itemType it ON it.id = i.typeFk
- JOIN vn.itemCategory ic ON ic.id = it.categoryFk
- LEFT JOIN (
- SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS Fuentes
- FROM vn.itemShelving ish
- JOIN vn.shelving sh ON sh.code = ish.shelvingFk
- JOIN vn.parking p ON p.id = sh.parkingFk
- JOIN vn.sector s ON s.id = p.sectorFk
- WHERE s.code = 'FUENTES_PICASSE'
- GROUP BY ish.itemFk
- ) fue ON fue.itemFk = i.id
- LEFT JOIN (
- SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS Albenfruit
- FROM vn.itemShelving ish
- JOIN vn.shelving sh ON sh.code = ish.shelvingFk
- JOIN vn.parking p ON p.id = sh.parkingFk
- JOIN vn.sector s ON s.id = p.sectorFk
- WHERE s.code = 'ALBENFRUIT'
- GROUP BY ish.itemFk
- ) alb ON alb.itemFk = i.id
- LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = vWarehouseFk
- LEFT JOIN (
- SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as venta
- FROM itemTicketOut
- WHERE shipped BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE()))
- AND warehouseFk = vWarehouseFk
- GROUP BY itemFk
- ) sale ON sale.item_id = i.id
- LEFT JOIN (
- SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as compra
- FROM itemEntryIn
- WHERE landed BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE()))
- AND warehouseInFk = vWarehouseFk
- AND isVirtualStock = FALSE
- GROUP BY itemFk
- ) buy ON buy.item_id = i.id
- LEFT JOIN (
- SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as traslado
- FROM itemEntryOut
- WHERE shipped BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE()))
- AND warehouseOutFk = vWarehouseFk
- GROUP BY itemFk
- ) mov ON mov.item_id = i.id
- WHERE (v.amount OR fue.Fuentes OR alb.Albenfruit)
- AND i.itemPackingTypeFk = 'H'
- AND ic.shortLife;
+ IF vCampaign IS NULL THEN
+ CALL util.throw('Missing data in campaign table');
+ END IF;
+ IF NOT vYesterday BETWEEN vDateSumTo - INTERVAL vPreviousDays DAY
+ AND vDateSumTo THEN
+ LEAVE proc;
+ END IF;
+
+ SET vDateSumFrom = vDateSumTo - INTERVAL vScopeDays DAY;
+ SET vDateSumTo = vDateSumTo - INTERVAL 1 DAY;
+
+ INSERT INTO itemCampaign(dated, itemFk, quantity, total, campaign)
+ SELECT vYesterday,
+ s.itemFk,
+ SUM(s.quantity) quantity,
+ SUM((s.quantity * s.price) * (100 - s.discount) / 100) total,
+ vCampaign
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN client c ON c.id = t.clientFk
+ WHERE t.shipped BETWEEN vDateSumFrom AND util.dayEnd(vDateSumTo)
+ AND c.typeFk = 'normal'
+ AND NOT t.isDeleted
+ GROUP BY s.itemFk
+ HAVING quantity;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -59797,7 +59373,7 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `itemMinimumQuantity_check`(
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemMinimumQuantity_check`(
vSelf INT,
vItemFk INT,
vStarted DATE,
@@ -59875,7 +59451,11 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemPlacementSupplyAiming`(vShelvingFk VARCHAR(10), quantity INT, vItemFk INT)
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemPlacementSupplyAiming`(
+ vShelvingCode VARCHAR(10),
+ vQuantity INT,
+ vItemFk INT
+)
BEGIN
SELECT ish.itemFk,
@@ -59885,21 +59465,21 @@ BEGIN
ish.itemShelvingFk,
ish.shelving,
ish.stock,
- LEAST(ish.stock,quantity) as total,
+ LEAST(ish.stock,vQuantity) total,
CONCAT(
- CAST(FLOOR(LEAST(ish.stock,quantity) / ish.packing) AS DECIMAL(10,0)),
+ CAST(FLOOR(LEAST(ish.stock, vQuantity) / 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, vQuantity) MOD ish.packing,
+ CONCAT(' + ',CAST(LEAST(ish.stock, vQuantity) 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
+ LEAST(ish.stock, vQuantity)
+ ) proposal
+ FROM itemShelvingPlacementSupplyStock ish
+ WHERE ish.shelving = vShelvingCode COLLATE utf8_general_ci
AND ish.itemFk = vItemFk;
END ;;
@@ -59941,7 +59521,9 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemPlacementSupplyGetOrder`(vSector INT )
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemPlacementSupplyGetOrder`(
+ vSectorFk INT
+)
BEGIN
DECLARE vId INT;
@@ -59949,31 +59531,35 @@ BEGIN
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
+ FROM itemShelvingPlacementSupply isps
+ JOIN itemShelving ish ON ish.id = isps.itemShelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
WHERE isps.userFk = getUser()
ORDER BY isps.created DESC
LIMIT 1;
- SET vNextParkingFk = vn.itemShelvingPlacementSupply_ClosestGet(vLastParkingFk);
+ SET vNextParkingFk = itemShelvingPlacementSupply_ClosestGet(vLastParkingFk);
SELECT ipsl.id INTO vId
- FROM vn.itemPlacementSupplyList ipsl
- JOIN vn.itemShelvingPlacementSupplyStock ispss ON ispss.itemFk = ipsl.itemFk
+ FROM itemPlacementSupplyList ipsl
+ JOIN 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
+ AND ipsl.sectorFk = vSectorFk
+ ORDER BY ipsl.repoUserFk DESC,
+ ipsl.priority DESC,
+ (ispss.parkingFk = vNextParkingFk) DESC,
+ ispss.parking DESC,
+ ipsl.created
LIMIT 1;
- UPDATE vn.itemPlacementSupply
+ UPDATE itemPlacementSupply
SET repoUserFk = getUser()
WHERE id = vId;
- SELECT * FROM vn.itemPlacementSupplyList
+ SELECT * FROM itemPlacementSupplyList
WHERE id = vId
- AND sectorFk = vSector;
+ AND sectorFk = vSectorFk;
END ;;
DELIMITER ;
@@ -59991,7 +59577,10 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemPlacementSupplyStockGetTargetList`(vItemFk INT,vSectorFk INT)
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemPlacementSupplyStockGetTargetList`(
+ vItemFk INT,
+ vSectorFk INT
+)
BEGIN
/**
* Devuelve la lista de ubicaciones para itemFk en ese sector. Se utiliza en la preparación previa.
@@ -60005,11 +59594,11 @@ BEGIN
SUM(ish.visible) stockTotal,
ish.created,
p.pickingOrder
- 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 sc ON sc.id = p.sectorFk
- JOIN vn.warehouse w ON w.id = sc.warehouseFk
+ FROM itemShelving ish
+ JOIN shelving sh ON sh.id = ish.shelvingFk
+ JOIN parking p ON p.id = sh.parkingFk
+ JOIN sector sc ON sc.id = p.sectorFk
+ JOIN warehouse w ON w.id = sc.warehouseFk
WHERE ish.visible > 0
AND ish.itemFk = vItemFk
GROUP BY ish.id
@@ -60178,125 +59767,6 @@ 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 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingLog_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_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelvingLog_get`(vShelvingFk VARCHAR(10) )
-BEGIN
-
-/**
- * Devuelve el log de los item en cada carro
- *
- * @param vShelvingFk Matrícula del carro
- *
- */
-
- SELECT isl.itemShelvingFk,
- isl.created,
- isl.accion,
- isl.itemFk,
- isl.shelvingFk,
- isl.quantity,
- isl.visible,
- isl.available,
- isl.grouping,
- isl.packing,
- isl.stars,
- item.longName,
- item.size,
- item.subName,
- worker.code,
- isl.accion
- FROM item
- JOIN itemShelvingLog isl ON item.id = isl.itemFk
- JOIN worker ON isl.workerFk = worker.id
- WHERE shelvingFk = vShelvingFk OR isl.itemFk = vShelvingFk
- ORDER BY isl.created DESC;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `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 = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelvingMakeFromDate`(IN `vShelvingFk` VARCHAR(8), IN `vBarcode` VARCHAR(22), IN `vQuantity` INT, IN `vPackagingFk` VARCHAR(10), IN `vGrouping` INT, IN `vPacking` INT, IN `vWarehouseFk` INT, `vCreated` VARCHAR(22))
-BEGIN
-
- DECLARE vItemFk INT;
-
- SELECT vn.barcodeToItem(vBarcode) INTO vItemFk;
-
- 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 visible = visible+vQuantity,
- created = vCreated
- WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk
- AND itemFk = vItemFk
- AND packing = vPacking;
-
- ELSE
- CALL cache.last_buy_refresh(FALSE);
- INSERT INTO itemShelving( itemFk,
- shelvingFk,
- visible,
- created,
- `grouping`,
- packing,
- packagingFk)
- SELECT vItemFk,
- vShelvingFk,
- vQuantity,
- vCreated,
- IF(vGrouping = 0, IFNULL(b.packing, vPacking), vGrouping) `grouping`,
- IF(vPacking = 0, b.packing, vPacking) packing,
- IF(vPackagingFk = '', b.packagingFk, vPackagingFk) packaging
- FROM vn.item i
- LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk
- LEFT JOIN vn.buy b ON b.id = lb.buy_id
- WHERE i.id = vItemFk;
- END IF;
-
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -60334,46 +59804,13 @@ BEGIN
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
+ JOIN shelving sh ON sh.id = 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 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!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 = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` 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 visible = visible - vQuantity
- WHERE id = vItemShelvingFk;
-
-
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -60429,7 +59866,7 @@ BEGIN
AND IFNULL(sub3.transit,0) < s.quantity
AND s.isPicked = FALSE
AND s.reserved = FALSE
- AND t.shipped BETWEEN util.VN_CURDATE() AND MIDNIGHT(util.VN_CURDATE())
+ AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight()
AND tst.isPreviousPreparable = TRUE
AND t.warehouseFk = vWarehouseFk
AND iss.sectorFk = vSectorFk
@@ -60807,7 +60244,8 @@ BEGIN
getUser());
UPDATE itemShelving
- SET visible = visible - vQuantity
+ SET visible = visible - vQuantity,
+ available = available - vQuantity
WHERE id = vItemShelvingFk;
UPDATE vn.saleTracking
@@ -60912,18 +60350,19 @@ proc: BEGIN
DECLARE vReservedQuantity INT;
DECLARE vOutStanding INT;
DECLARE vUserFk INT;
- DECLARE vTotalReservedQuantity INT;
+ DECLARE vTotalReservedQuantity INT;
DECLARE vSaleQuantity INT;
+ DECLARE vIsRequiredTx BOOL DEFAULT NOT @@in_transaction;
DECLARE vItemShelvingAvailable CURSOR FOR
SELECT ish.id itemShelvingFk,
ish.available
FROM sale s
JOIN itemShelving ish ON ish.itemFk = s.itemFk
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN sector sc ON sc.id = p.sectorFk
- JOIN productionConfig pc
+ JOIN productionConfig pc
WHERE s.id = vSaleFk
AND NOT sc.isHideForPickers
AND (sc.id = vSectorFk OR vSectorFk IS NULL)
@@ -60938,15 +60377,15 @@ proc: BEGIN
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
- ROLLBACK;
+ CALL util.tx_rollback(vIsRequiredTx);
RESIGNAL;
END;
-
- START TRANSACTION;
-
+
+ CALL util.tx_start(vIsRequiredTx);
+
SELECT id INTO vSaleFk
FROM sale
- WHERE id = vSaleFk
+ WHERE id = vSaleFk
FOR UPDATE;
SELECT MAX(p.pickingOrder), s.quantity - SUM(IFNULL(iss.quantity, 0)), s.quantity
@@ -60954,12 +60393,12 @@ proc: BEGIN
FROM sale s
LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id
LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
- LEFT JOIN shelving sh ON sh.code = ish.shelvingFk
+ LEFT JOIN shelving sh ON sh.id = ish.shelvingFk
LEFT JOIN parking p ON p.id = sh.parkingFk
WHERE s.id = vSaleFk;
IF vOutStanding <= 0 THEN
- COMMIT;
+ CALL util.tx_commit(vIsRequiredTx);
LEAVE proc;
END IF;
@@ -60979,7 +60418,7 @@ proc: BEGIN
IF vTotalReservedQuantity <> vSaleQuantity THEN
CALL util.debugAdd('itemShelvingSale_addBySale',
CONCAT(vSaleFk, ' - ', vSaleQuantity,' - ', vTotalReservedQuantity,'-', vOutStanding,'-', account.myUser_getId()));
-
+
UPDATE sale
SET quantity = vTotalReservedQuantity
WHERE id = vSaleFk;
@@ -60987,7 +60426,7 @@ proc: BEGIN
LEAVE l;
END IF;
- SELECT id INTO vItemShelvingFk
+ SELECT id INTO vItemShelvingFk
FROM itemShelving
WHERE id = vItemShelvingFk
FOR UPDATE;
@@ -60996,19 +60435,19 @@ proc: BEGIN
SET vOutStanding = vOutStanding - vReservedQuantity;
IF vReservedQuantity > 0 THEN
- CALL util.debugAdd('itemShelvingSale_addBySale_reservedQuantity',
- CONCAT(vSaleFk, ' - ', vReservedQuantity, ' - ', vOutStanding, account.myUser_getId()));
- INSERT INTO itemShelvingSale(
- itemShelvingFk,
- saleFk,
- quantity,
- userFk,
- isPicked)
- SELECT vItemShelvingFk,
- vSaleFk,
- vReservedQuantity,
- vUserFk,
- FALSE;
+ CALL util.debugAdd('itemShelvingSale_addBySale_reservedQuantity',
+ CONCAT(vSaleFk, ' - ', vReservedQuantity, ' - ', vOutStanding, account.myUser_getId()));
+ INSERT INTO itemShelvingSale(
+ itemShelvingFk,
+ saleFk,
+ quantity,
+ userFk,
+ isPicked)
+ SELECT vItemShelvingFk,
+ vSaleFk,
+ vReservedQuantity,
+ vUserFk,
+ FALSE;
UPDATE itemShelving
SET available = available - vReservedQuantity
@@ -61017,7 +60456,7 @@ proc: BEGIN
END IF;
END LOOP;
CLOSE vItemShelvingAvailable;
- COMMIT;
+ CALL util.tx_commit(vIsRequiredTx);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -61034,7 +60473,7 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_addBySaleGroup`(
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelvingSale_addBySaleGroup`(
vSaleGroupFk INT(11)
)
BEGIN
@@ -61145,6 +60584,68 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_deleteAdded` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelvingSale_deleteAdded`(
+ vSelf INT(11)
+)
+proc: BEGIN
+/**
+ * Borra una reservea devolviendo la cantidad al itemShelving
+ *
+ * @param vSelf Identificador del itemShelvingSale
+ */
+ DECLARE vSaleFk INT;
+ DECLARE vHasSalesPicked BOOL;
+
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ START TRANSACTION;
+
+ SELECT iss.saleFk INTO vSaleFk
+ FROM itemShelvingSale iss
+ JOIN sale s ON s.id = iss.saleFk
+ WHERE iss.id = vSelf AND s.isAdded
+ FOR UPDATE;
+
+ IF vSaleFk IS NULL THEN
+ CALL util.throw('The sale can not be deleted');
+ END IF;
+
+ SELECT COUNT(*) INTO vHasSalesPicked
+ FROM itemShelvingSale
+ WHERE saleFk = vSaleFk AND isPicked;
+
+ IF vHasSalesPicked THEN
+ CALL util.throw('A sale with picked sales cannot be deleted');
+ END IF;
+
+ UPDATE itemShelvingSale iss
+ JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
+ SET ish.available = ish.available + iss.quantity
+ WHERE iss.saleFk = vSaleFk;
+
+ DELETE FROM sale WHERE id = vSaleFk;
+
+ 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 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_doReserve` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -61339,7 +60840,8 @@ CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelvingSale_setQuantity`(
vItemShelvingSaleFk INT(10),
vQuantity DECIMAL(10,0),
vIsItemShelvingSaleEmpty BOOLEAN,
- vSectorFk INT
+ vSectorFk INT,
+ vShelvingFk VARCHAR(10)
)
BEGIN
/**
@@ -61360,6 +60862,7 @@ BEGIN
DECLARE vItemFk INT;
DECLARE vTotalQuantity INT;
DECLARE vStateCode VARCHAR(45);
+ DECLARE vCurrentShelvingFk VARCHAR(10);
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
@@ -61381,18 +60884,26 @@ BEGIN
iss.saleFk,
iss.itemShelvingFk,
SUM(IFNULL(iss.quantity,0)),
- IF(sgd.id, 'PREVIOUS_PREPARATION', 'PREPARED')
+ IF(sgd.id, 'PREVIOUS_PREPARATION', 'PREPARED'),
+ sh.code
INTO vItemFk,
vSaleFk,
vItemShelvingFk,
vReservedQuantity,
- vStateCode
+ vStateCode,
+ vCurrentShelvingFk
FROM itemShelvingSale iss
JOIN sale s ON s.id = iss.saleFk
- LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleFk = iss.saleFk
+ JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
+ LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = iss.saleFk
+ LEFT JOIN shelving sh ON sh.id = ish.shelvingFk
WHERE iss.id = vItemShelvingSaleFk
AND NOT iss.isPicked;
+ IF NOT (vCurrentShelvingFk <=> vShelvingFk) THEN
+ CALL util.throw('The shelving can not be different from the shelving reserved');
+ END IF;
+
IF vQuantity > vReservedQuantity
OR (vQuantity < vReservedQuantity AND NOT vIsItemShelvingSaleEmpty)
OR (vQuantity = vReservedQuantity AND vIsItemShelvingSaleEmpty) THEN
@@ -61533,7 +61044,7 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelving_add`(
- vShelvingFk VARCHAR(8),
+ vShelvingCode VARCHAR(10),
vBarcode VARCHAR(22),
vQuantity INT,
vPackagingFk VARCHAR(10),
@@ -61545,7 +61056,7 @@ BEGIN
/**
* Añade registro o lo actualiza si ya existe.
*
- * @param vShelvingFk matrícula del carro
+ * @param vShelvingCode matrícula del carro
* @param vBarcode el id del registro
* @param vQuantity indica la cantidad del producto
* @param vPackagingFk el packaging del producto en itemShelving, NULL para coger el de la ultima compra
@@ -61556,10 +61067,15 @@ BEGIN
**/
DECLARE vItemFk INT;
DECLARE vBuyFk INT;
+ DECLARE vShelvingFk INT;
SELECT id INTO vBuyFk
FROM buy WHERE id = vBarcode;
+ SELECT id INTO vShelvingFk
+ FROM shelving
+ WHERE code COLLATE utf8_unicode_ci = vShelvingCode;
+
SELECT barcodeToItem(vBarcode) INTO vItemFk;
IF vBuyFk IS NULL THEN
@@ -61573,7 +61089,7 @@ BEGIN
END IF;
IF (SELECT COUNT(*) FROM itemShelving
- WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk
+ WHERE shelvingFk = vShelvingFk
AND itemFk = vItemFk
AND packing = vPacking
AND buyFk = vBuyFk) THEN
@@ -61581,7 +61097,9 @@ BEGIN
UPDATE itemShelving
SET visible = visible + vQuantity,
available = available + vQuantity
- WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking;
+ WHERE shelvingFk = vShelvingFk
+ AND itemFk = vItemFk
+ AND packing = vPacking;
ELSE
@@ -61619,31 +61137,40 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelving_addByClaim`(vClaimFk INT, vShelvingFk VARCHAR(3))
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelving_addByClaim`(
+ vClaimFk INT,
+ vShelvingCode VARCHAR(10)
+)
BEGIN
/**
* Insert items of claim into itemShelving.
*
* @param vClaimFk The claim
- * @param vShelvingFk The shelving
+ * @param vShelvingCode The shelving code
* @table tmp.buyUltimate
*/
DECLARE vWarehouseFk INT;
+ DECLARE vShelvingFk INT;
SELECT t.warehouseFk INTO vWarehouseFk
FROM claim c
JOIN ticket t ON t.id = c.ticketFk
WHERE c.id = vClaimFk;
+ SELECT id INTO vShelvingFk
+ FROM shelving
+ WHERE code COLLATE utf8_unicode_ci = vShelvingCode;
+
CALL buy_getUltimate(NULL, vWarehouseFk, util.VN_CURDATE());
INSERT INTO itemShelving (itemFk, shelvingFk, packing, `grouping`, visible)
- SELECT s.itemFk, vShelvingFk, b.packing, b.`grouping`, cb.quantity AS visible
+ SELECT s.itemFk, vShelvingFk, b.packing, b.`grouping`, cb.quantity visible
FROM claim c
JOIN claimBeginning cb ON c.id = cb.claimFk
JOIN sale s ON s.id = cb.saleFk
JOIN ticket t ON t.id = s.ticketFk
- JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk AND bu.warehouseFk = t.warehouseFk
+ JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
+ AND bu.warehouseFk = t.warehouseFk
JOIN buy b ON b.id = bu.buyFk
WHERE c.id = vClaimFk;
END ;;
@@ -61662,18 +61189,24 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelving_addList`(vShelvingFk VARCHAR(3), vList TEXT, vIsChecking BOOL, vWarehouseFk INT)
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelving_addList`(
+ vShelvingCode VARCHAR(10),
+ vList TEXT,
+ vIsChecking BOOL,
+ vWarehouseFk INT
+)
BEGIN
-/* Recorre cada elemento en la colección vList.
+/**
+ * Recorre cada elemento en la colección vList.
* Si el parámetro isChecking = FALSE, llama a itemShelving_add.
*
* Cuando es TRUE sólo inserta los elementos de la colección que no están ya en
- * ese shelving, actualizando los valores del campo vn.itemShelving.isChecked
+ * ese shelving, actualizando los valores del campo itemShelving.isChecked
*
- * param vShelvingFk Identificador de vn.shelving
- * param vList JSON array con esta estructura: '[value1, value2, ...]'
- * param vIsChecking Define si hay que añadir o comprobar los items
- * param vWarehouseFk Identificador de vn.warehouse
+ * @param vShelvingCode Código de shelving
+ * @param vList JSON array con esta estructura: '[value1, value2, ...]'
+ * @param vIsChecking Define si hay que añadir o comprobar los items
+ * @param vWarehouseFk Identificador de warehouse
*/
DECLARE vListLength INT DEFAULT JSON_LENGTH(vList);
DECLARE vCounter INT DEFAULT 0;
@@ -61681,28 +61214,34 @@ BEGIN
DECLARE vPath VARCHAR(6);
DECLARE vItemFk INT;
DECLARE vIsChecked BOOL;
+ DECLARE vShelvingFk INT;
+
+ SELECT id INTO vShelvingFk
+ FROM shelving
+ WHERE code COLLATE utf8_unicode_ci = vShelvingCode;
WHILE vCounter < vListLength DO
- SET vPath = CONCAT('$[',vCounter,']');
- SET vBarcode = JSON_EXTRACT(vList,vPath);
+ SET vPath = CONCAT('$[', vCounter, ']');
+ SET vBarcode = JSON_EXTRACT(vList, vPath);
SET vIsChecked = NULL;
IF vIsChecking THEN
SELECT barcodeToItem(vBarcode) INTO vItemFk;
- SELECT COUNT(*) INTO vIsChecked
- FROM vn.itemShelving
- WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk
+ SELECT IF(COUNT(*), TRUE, FALSE) INTO vIsChecked
+ FROM itemShelving
+ WHERE shelvingFk = vShelvingFk
AND itemFk = vItemFk;
END IF;
- IF NOT (vIsChecking AND vIsChecked) THEN
- CALL vn.itemShelving_add(vShelvingFk, vBarcode, 1, NULL, NULL, NULL, vWarehouseFk);
+ IF NOT vIsChecking OR NOT vIsChecked THEN
+ CALL itemShelving_add(vShelvingCode, vBarcode, 1, NULL, NULL, NULL, vWarehouseFk);
END IF;
- UPDATE vn.itemShelving
+ UPDATE itemShelving
SET isChecked = vIsChecked
- WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk
- AND itemFk = vItemFk AND isChecked IS NULL;
+ WHERE shelvingFk = vShelvingFk
+ AND itemFk = vItemFk
+ AND isChecked IS NULL;
SET vCounter = vCounter + 1;
END WHILE;
@@ -61821,17 +61360,20 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelving_get`(IN vSelf VARCHAR(8))
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelving_get`(
+ vShelvingCode VARCHAR(10)
+)
BEGIN
/**
-* Lista artículos de itemshelving
+* Lista artículos de itemShelving.
*
-* @param vSelf matrícula del carro
+* @param vShelvingCode Matrícula del carro
**/
SELECT ish.itemFk item,
- IFNULL(i.longName, CONCAT(i.name, ' ', i.size)) description,
+ i.name,
+ i.longName,
+ i.size,
ish.visible,
- CEIL(ish.visible/ish.packing) stickers,
ish.packing,
ish.grouping,
p.code,
@@ -61839,13 +61381,15 @@ BEGIN
s.priority,
ish.isChecked,
ic.url,
- ish.available
+ ish.available,
+ ish.buyFk,
+ ish.shelvingFk
FROM itemShelving ish
JOIN item i ON i.id = ish.itemFk
- JOIN shelving s ON vSelf = s.code COLLATE utf8_unicode_ci
- LEFT JOIN parking p ON s.parkingFk = p.id
+ JOIN shelving s ON s.id = ish.shelvingFk
+ LEFT JOIN parking p ON p.id = s.parkingFk
JOIN hedera.imageConfig ic
- WHERE ish.shelvingFk COLLATE utf8_unicode_ci = vSelf;
+ WHERE s.code COLLATE utf8_unicode_ci = vShelvingCode;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -61862,23 +61406,33 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelving_getAlternatives`(vShelvingFk VARCHAR(10))
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelving_getAlternatives`(
+ vShelvingCode VARCHAR(10)
+)
BEGIN
/**
- * Devuelve un listado de posibles ubicaciones alternativas a ubicar los item de la matricula
- * del carro que se le ha pasado.
+ * Devuelve un listado de posibles ubicaciones alternativas a ubicar
+ * los item de la matricula del carro que se le ha pasado.
*
- * @param vShelvingFk matricula del carro
+ * @param vShelvingCode Matricula del carro
*/
- SELECT is2.id,is2.shelvingFk , p.code, is2.itemFk , is2.visible, p.pickingOrder
+ DECLARE vShelvingFk INT;
+
+ SELECT id INTO vShelvingFk
+ FROM shelving
+ WHERE code COLLATE utf8_unicode_ci = vShelvingCode;
+
+ SELECT is2.id,is2.shelvingFk, p.code, is2.itemFk , is2.visible, p.pickingOrder
FROM itemShelving is2
- JOIN shelving sh ON sh.code = is2.shelvingFk
+ JOIN shelving sh ON sh.id = is2.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN sector s ON s.id = p.sectorFk
- LEFT JOIN operator o ON o.sectorFk = s.id AND o.workerFk = account.myUser_getId()
+ LEFT JOIN operator o ON o.sectorFk = s.id
+ AND o.workerFk = account.myUser_getId()
JOIN warehouse wh ON wh.id = s.warehouseFk
- JOIN itemShelving is3 ON is3.itemFk = is2.itemFk AND is3.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci
- WHERE is2.shelvingFk <> vShelvingFk COLLATE utf8_unicode_ci
+ JOIN itemShelving is3 ON is3.itemFk = is2.itemFk
+ AND is3.shelvingFk = vShelvingFk
+ WHERE is2.shelvingFk <> vShelvingFk
GROUP BY is2.id
ORDER BY p.pickingOrder DESC;
END ;;
@@ -61914,7 +61468,7 @@ BEGIN
ish.itemFk itemFk,
sh.priority
FROM vn.itemShelving ish
- JOIN vn.shelving sh ON sh.`code` = ish.shelvingFk
+ JOIN vn.shelving sh ON sh.id = ish.shelvingFk
JOIN vn.parking pk ON pk.id = sh.parkingFk
WHERE ish.itemFk = vItemFk
ORDER BY sh.priority DESC, created ASC;
@@ -61936,14 +61490,14 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelving_getItemDetails`(
vBarcodeItem INT,
- vShelvingFK VARCHAR(10)
+ vShelvingCode VARCHAR(10)
)
BEGIN
/**
* Obtiene el precio y visible de un item
*
* @param vBarcodeItem barcode de artículo
- * @param vShelvingFK Ubicación actual del artículo
+ * @param vShelvingCode Ubicación actual del artículo
*/
DECLARE vIsItem BOOL;
DECLARE vBuyFk INT;
@@ -61973,19 +61527,20 @@ BEGIN
WITH visible AS(
SELECT itemFk,
IFNULL(buyingValue, 0) +
- IFNULL(freightValue, 0) +
- IFNULL(comissionValue, 0) +
- IFNULL(packageValue, 0) itemCost
- FROM vn.buy b
+ IFNULL(freightValue, 0) +
+ IFNULL(comissionValue, 0) +
+ IFNULL(packageValue, 0) itemCost
+ FROM vn.buy b
WHERE b.id = vBuyFk
) SELECT v.itemFk,
- vShelvingFK,
+ vShelvingCode,
v.itemCost,
SUM(ish.visible) visible
FROM vn.itemShelving ish
+ JOIN vn.shelving sh ON sh.id = ish.shelvingFK
JOIN visible v
- WHERE ish.shelvingFK = vShelvingFK COLLATE utf8mb3_general_ci
- AND ish.itemFk = v.itemFk;
+ WHERE sh.code = vShelvingCode COLLATE utf8mb3_general_ci
+ AND ish.itemFk = v.itemFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -62002,16 +61557,22 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelving_getSaleDate`(vShelvingFk VARCHAR(3))
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelving_getSaleDate`(
+ vShelvingCode VARCHAR(10)
+)
BEGIN
-
- /* Devuelve la mínima fecha en que se necesita cada producto en esa matrícula.
- *
- * @param vShelvingFk Matrícula del carro o pallet
- */
-
+/**
+ * Devuelve la mínima fecha en que se necesita cada producto en esa matrícula.
+ *
+ * @param vShelvingCode Matrícula del carro o pallet
+ */
DECLARE vWarehouseFk INT;
DECLARE vStockScopeDays INT;
+ DECLARE vShelvingFk INT;
+
+ SELECT id INTO vShelvingFk
+ FROM shelving
+ WHERE code COLLATE utf8_unicode_ci = vShelvingCode;
SELECT s.warehouseFk, stockScopeDays
INTO vWarehouseFk, vStockScopeDays
@@ -62033,7 +61594,7 @@ BEGIN
ENGINE = MEMORY
SELECT itemFk, SUM(visible) visible
FROM itemShelving
- WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci
+ WHERE shelvingFk = vShelvingFk
GROUP BY itemFk;
CREATE OR REPLACE TEMPORARY TABLE tmp.tStockByDay
@@ -62055,7 +61616,7 @@ BEGIN
SELECT ish.itemFk, - SUM(ish.visible), util.VN_CURDATE()
FROM itemShelving ish
JOIN tmp.tItems i ON i.itemFk = ish.itemFk
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON sh.parkingFk = p.id
JOIN sector s ON s.id = p.sectorFk
WHERE s.isReserve
@@ -62113,7 +61674,7 @@ BEGIN
UPDATE tmp.tStockByDay sbd
JOIN (SELECT ish.itemFK, SUM(ish.visible) amount
FROM itemShelving ish
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN sector s ON s.id = p.sectorFk
WHERE s.warehouseFk = vWarehouseFk
@@ -62153,10 +61714,10 @@ BEGIN
p.sectorFk,
ish.shelvingFk
FROM itemShelving ish
- JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.shelving sh ON sh.id = ish.shelvingFk
LEFT JOIN parking p ON p.id = parkingFk
LEFT JOIN vn.sector s ON s.id = p.sectorFk
- WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci
+ WHERE ish.shelvingFk = vShelvingFk
) sub4 ON sub4.itemFk = ts.itemFk
LEFT JOIN sector s ON s.id = sub4.sectorFk
LEFT JOIN item i ON i.id = ts.itemFk
@@ -62223,7 +61784,7 @@ BEGIN
JOIN item i ON i.id = ish.itemFk
JOIN itemType it ON it.id = i.typeFk
JOIN tmp.stockMisfit sm ON sm.itemFk = ish.itemFk
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
LEFT JOIN (
SELECT s.itemFk, sum(s.quantity) notPrepared
@@ -62259,18 +61820,18 @@ DELIMITER ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelving_selfConsumption`(
- vShelvingFk VARCHAR(10) COLLATE utf8_general_ci,
+ vShelvingCode VARCHAR(10) COLLATE utf8_general_ci,
vItemFk INT,
vQuantity INT
)
BEGIN
/**
- * Leave the indicated amount on the shelf
+ * Leave the indicated amount on the shelve
* and create a ticket with the difference.
*
- * @param vShelvingFk id of the shelf where the item is located.
- * @param vItemFk article of which the self-consumption ticket is to be created.
- * @param vQuantity amount that will stay on the shelf
+ * @param vShelvingCode Code of the shelve where the item is located
+ * @param vItemFk Item of which the self-consumption ticket is to be created
+ * @param vQuantity Amount that will stay on the shelve
*/
DECLARE vVisible INT;
DECLARE vClientFk INT;
@@ -62280,6 +61841,11 @@ BEGIN
DECLARE vAgencyModeFk INT;
DECLARE vItemShelvingFk INT;
DECLARE vAddressFk INT;
+ DECLARE vShelvingFk INT;
+
+ SELECT id INTO vShelvingFk
+ FROM shelving
+ WHERE code = vShelvingCode;
SELECT c.id,
pc.clientSelfConsumptionFk,
@@ -62296,7 +61862,7 @@ BEGIN
JOIN parking p ON p.sectorFk = s.id
JOIN shelving s2 ON s2.parkingFk = p.id
JOIN productionConfig pc
- WHERE s2.code = vShelvingFk;
+ WHERE s2.id = vShelvingFk;
IF vClientFk IS NULL THEN
CALL util.throw('The company does not have a customer assigned');
@@ -62306,7 +61872,7 @@ BEGIN
CALL util.throw('The shelf cannot have NULL or negative quantities');
END IF;
- IF vShelvingFk IS NULL THEN
+ IF vShelvingCode IS NULL THEN
CALL util.throw('The shelf is necessary');
END IF;
@@ -62339,7 +61905,8 @@ BEGIN
WHERE id = vItemFk;
UPDATE itemShelving
- SET visible = IF(id = vItemShelvingFk, vQuantity, 0)
+ SET visible = IF(id = vItemShelvingFk, vQuantity, 0),
+ available = IF(id = vItemShelvingFk, vQuantity, 0)
WHERE shelvingFk = vShelvingFk
AND itemFk = vItemFk;
@@ -62362,7 +61929,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelving_transfer`(
vItemShelvingFk INT,
- vShelvingFk VARCHAR(10)
+ vShelvingCode VARCHAR(10)
)
BEGIN
/**
@@ -62370,9 +61937,14 @@ BEGIN
* fusionando si coincide el packing y la fecha.
*
* @param vItemShelvingFk Identificador de itemShelving
- * @param vShelvingFk Identificador de shelving
+ * @param vShelvingCode Código de shelving
*/
DECLARE vNewItemShelvingFk INT;
+ DECLARE vShelvingFk INT;
+
+ SELECT id INTO vShelvingFk
+ FROM shelving
+ WHERE code COLLATE utf8_unicode_ci = vShelvingCode;
SELECT MAX(ish.id) INTO vNewItemShelvingFk
FROM itemShelving ish
@@ -62387,20 +61959,19 @@ BEGIN
AND ish2.packing = ish.packing
AND DATE(ish2.created) = DATE(ish.created)
AND ish2.buyFk = ish.buyFk
- WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci;
+ WHERE ish.shelvingFk = vShelvingFk;
IF vNewItemShelvingFk THEN
UPDATE itemShelving ish
JOIN itemShelving ish2 ON ish2.id = vItemShelvingFk
- SET ish.visible = ish.visible + ish2.visible
+ SET ish.visible = ish.visible + ish2.visible,
+ ish.available = ish.available + ish2.available
WHERE ish.id = vNewItemShelvingFk;
DELETE FROM itemShelving
WHERE id = vItemShelvingFk;
ELSE
- IF (SELECT EXISTS(SELECT id FROM shelving
- WHERE code = vShelvingFk COLLATE utf8_unicode_ci)) THEN
-
+ IF (SELECT EXISTS(SELECT id FROM shelving WHERE id = vShelvingFk)) THEN
UPDATE itemShelving
SET shelvingFk = vShelvingFk
WHERE id = vItemShelvingFk;
@@ -62768,6 +62339,58 @@ 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 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `item_calculateStock` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `item_calculateStock`(
+ vDated DATE
+)
+BEGIN
+/**
+ * Calculate the stock of the auction warehouse from the inventory date to vDated
+ *
+ * @param vDated Date to calculate the stock.
+ * @return tmp.item, tmp.buyUltimate
+ */
+ DECLARE vAuctionWarehouseFk INT;
+
+ SELECT warehouseFk INTO vAuctionWarehouseFk
+ FROM auctionConfig;
+
+ CREATE OR REPLACE TEMPORARY TABLE tmp.item
+ (UNIQUE INDEX i USING HASH (itemFk))
+ ENGINE = MEMORY
+ SELECT itemFk, SUM(quantity) quantity
+ FROM itemEntryIn
+ WHERE landed = vDated
+ AND vDated >= util.VN_CURDATE()
+ AND warehouseInFk = vAuctionWarehouseFk
+ AND NOT isVirtualStock
+ GROUP BY itemFk
+ HAVING quantity;
+
+ CALL `cache`.stock_refresh(FALSE);
+
+ INSERT INTO tmp.item (itemFk, quantity)
+ SELECT item_id, amount
+ FROM `cache`.stock
+ WHERE warehouse_id = vAuctionWarehouseFk
+ ON DUPLICATE KEY UPDATE quantity = tmp.item.quantity + VALUES(quantity);
+
+ CALL buy_getUltimate(NULL, vAuctionWarehouseFk, vDated);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -63428,7 +63051,7 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`vn`@`localhost` PROCEDURE `item_devalueA2`(
vSelf INT,
- vShelvingFK VARCHAR(10),
+ vShelvingCode VARCHAR(10) COLLATE utf8mb3_general_ci,
vBuyingValue DECIMAL(10,4),
vQuantity INT
)
@@ -63439,7 +63062,7 @@ BEGIN
* de almacén y shelvings correspondientes
*
* @param vSelf Id de artículo a devaluar
- * @param vShelvingFK Ubicación actual del artículo
+ * @param vShelvingCode Código de shelving / ubicación
* @param vBuyingValue Nuevo precio de coste
* @param vQuantity Cantidad del ítem a pasar a A2
*/
@@ -63536,10 +63159,11 @@ BEGIN
CALL util.throw ('The item has not a buy');
END IF;
- SELECT id,visible INTO vTargetItemShelvingFk, vCurrentVisible
- FROM itemShelving
- WHERE shelvingFk = vShelvingFK COLLATE utf8mb3_general_ci
- AND itemFk = vSelf
+ SELECT ish.id, ish.visible INTO vTargetItemShelvingFk, vCurrentVisible
+ FROM itemShelving ish
+ JOIN shelving sh ON sh.id = ish.shelvingFk
+ WHERE sh.code = vShelvingCode
+ AND ish.itemFk = vSelf
LIMIT 1;
IF vCurrentVisible IS NULL THEN
@@ -63730,7 +63354,8 @@ BEGIN
WHERE id = vTargetItemShelvingFk;
ELSE
UPDATE itemShelving
- SET visible = vCurrentVisible - vQuantity
+ SET visible = vCurrentVisible - vQuantity,
+ available = GREATEST(0, available - vQuantity)
WHERE id = vTargetItemShelvingFk;
END IF;
@@ -63814,16 +63439,17 @@ BEGIN
userFk,
isChecked)
SELECT vItemA2Fk,
- shelvingFk,
+ ish.shelvingFk,
vQuantity ,
- `grouping`,
- packing,
- packagingFk,
+ ish.`grouping`,
+ ish.packing,
+ ish.packagingFk,
account.myUser_getId(),
- isChecked
- FROM itemShelving
- WHERE itemFK = vSelf
- AND shelvingFk = vShelvingFK COLLATE utf8mb3_general_ci
+ ish.isChecked
+ FROM itemShelving ish
+ JOIN shelving sh ON sh.id = ish.shelvingFk
+ WHERE ish.itemFK = vSelf
+ AND sh.code = vShelvingCode
ON DUPLICATE KEY UPDATE
visible = vQuantity + VALUES(visible);
@@ -63959,16 +63585,16 @@ BEGIN
JOIN vn.entry e ON e.id = b.entryFk
JOIN vn.travel tr ON tr.id = e.travelFk
JOIN vn.supplier s ON s.id = e.supplierFk
- JOIN vn.state st ON st.`code` = IF(tr.landed < util.VN_CURDATE()
+ JOIN vn.state st ON st.`code` = IF(tr.landed < util.VN_CURDATE()
OR (util.VN_CURDATE() AND tr.isReceived),
'DELIVERED',
'FREE')
WHERE tr.landed >= vDateInventory
AND tr.warehouseInFk = vWarehouseFk
- AND (s.id <> vSupplierInventoryFk OR vDated IS NULL)
+ AND (s.id <> vSupplierInventoryFk OR vDated IS NULL)
AND b.itemFk = vItemFk
AND NOT e.isExcludedFromAvailable
- AND NOT e.isRaid
+ AND NOT tr.isRaid
),
entriesOut AS (
SELECT 'entry',
@@ -64004,7 +63630,7 @@ BEGIN
AND b.itemFk = vItemFk
AND NOT e.isExcludedFromAvailable
AND NOT w.isFeedStock
- AND NOT e.isRaid
+ AND NOT tr.isRaid
),
sales AS (
WITH itemSales AS (
@@ -64056,10 +63682,10 @@ BEGIN
NULL
FROM itemSales s
LEFT JOIN vn.state stPrep ON stPrep.`code` = 'PREPARED'
- LEFT JOIN vn.saleTracking stk ON stk.saleFk = s.saleFk
+ LEFT JOIN vn.saleTracking stk ON stk.saleFk = s.saleFk
AND stk.stateFk = stPrep.id
GROUP BY s.saleFk
- ),
+ ),
orders AS (
SELECT 'order' originType,
o.id originId,
@@ -64124,9 +63750,9 @@ BEGIN
t.`in` invalue,
t.`out`,
@a := @a + IFNULL(t.`in`, 0) - IFNULL(t.`out`, 0) balance,
- @currentLineFk := IF (@shipped < util.VN_CURDATE()
+ @currentLineFk := IF (@shipped < util.VN_CURDATE()
OR (@shipped = util.VN_CURDATE() AND (t.isPicked OR a.`code` >= 'ON_PREPARATION')),
- t.lineFk,
+ t.lineFk,
@currentLineFk) lastPreparedLineFk,
t.isTicket,
t.lineFk,
@@ -64163,21 +63789,21 @@ BEGIN
UNION ALL
SELECT originType,
originId,
- shipped,
- alertlevel,
- stateName,
+ shipped,
+ alertlevel,
+ stateName,
reference,
entityType,
- entityId,
+ entityId,
entityName,
- `in`,
- `out`,
- @a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0),
- 0,
- isTicket,
- lineFk,
- isPicked,
- clientType,
+ `in`,
+ `out`,
+ @a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0),
+ 0,
+ isTicket,
+ lineFk,
+ isPicked,
+ clientType,
claimFk,
`order`
FROM tItemDiary
@@ -64244,7 +63870,6 @@ BEGIN
i.minimum `min`,
p.name producer,
o.code origin,
- v.visible - IFNULL(vVisibleItemShelving, 0) unlocated,
a.available,
vVisibleItemShelving,
v.visible,
@@ -64425,7 +64050,7 @@ BEGIN
AND NOT e.isExcludedFromAvailable
AND b.quantity <> 0
AND (vItemFk IS NULL OR b.itemFk = vItemFk)
- AND NOT e.isRaid
+ AND NOT t.isRaid
UNION ALL
SELECT r.itemFk,
r.shipment,
@@ -64517,18 +64142,20 @@ CREATE DEFINER=`vn`@`localhost` PROCEDURE `item_getSimilar`(
vSelf INT,
vWarehouseFk INT,
vDated DATE,
- vShowType BOOL
+ vShowType BOOL,
+ vDaysInForward INT
)
BEGIN
/**
-* Propone articulos disponibles ordenados, con la cantidad
-* de veces usado y segun sus caracteristicas.
-*
-* @param vSelf Id de artículo
-* @param vWarehouseFk Id de almacen
-* @param vDated Fecha
-* @param vShowType Mostrar tipos
-*/
+ * Propone articulos ordenados, con la cantidad
+ * de veces usado y segun sus caracteristicas.
+ *
+ * @param vSelf Id de artículo
+ * @param vWarehouseFk Id de almacen
+ * @param vDated Fecha
+ * @param vShowType Mostrar tipos
+ * @param vDaysInForward Días de alcance para las ventas (https://redmine.verdnatura.es/issues/7956#note-4)
+ */
DECLARE vAvailableCalcFk INT;
DECLARE vVisibleCalcFk INT;
DECLARE vTypeFk INT;
@@ -64536,6 +64163,7 @@ BEGIN
CALL cache.available_refresh(vAvailableCalcFk, FALSE, vWarehouseFk, vDated);
CALL cache.visible_refresh(vVisibleCalcFk, FALSE, vWarehouseFk);
+ CALL buy_getUltimate(NULL, vWarehouseFk, vDated);
WITH itemTags AS (
SELECT i.id,
@@ -64557,6 +64185,7 @@ BEGIN
WHERE i.id = vSelf
)
SELECT i.id itemFk,
+ NULL advanceable, -- https://redmine.verdnatura.es/issues/7956#note-4
i.longName,
i.subName,
i.tag5,
@@ -64585,14 +64214,13 @@ BEGIN
AND a.calc_id = vAvailableCalcFk
LEFT JOIN cache.visible v ON v.item_id = i.id
AND v.calc_id = vVisibleCalcFk
- LEFT JOIN cache.last_buy lb ON lb.item_id = i.id
- AND lb.warehouse_id = vWarehouseFk
+ LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.id
LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id
AND ip.itemFk = vSelf
LEFT JOIN vn.itemTag it ON it.itemFk = i.id
AND it.priority = vPriority
LEFT JOIN vn.tag t ON t.id = it.tagFk
- LEFT JOIN vn.buy b ON b.id = lb.buy_id
+ LEFT JOIN vn.buy b ON b.id = bu.buyFk
JOIN itemTags its
WHERE a.available > 0
AND (i.typeFk = its.typeFk OR NOT vShowType)
@@ -64609,6 +64237,8 @@ BEGIN
(i.tag8 = its.tag8) DESC,
match8 DESC
LIMIT 100;
+
+ DROP TEMPORARY TABLE tmp.buyUltimate;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -64777,22 +64407,22 @@ BEGIN
ALTER TABLE tmp.itemInventory
ADD `buy_date` datetime NOT NULL;
-
+
CREATE OR REPLACE TEMPORARY TABLE lastBuyScope
SELECT i.id, MAX(t.landed) lastLanded
- FROM item i
- JOIN buy b ON b.itemFk = i.id
+ FROM item i
+ JOIN buy b ON b.itemFk = i.id
JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
+ JOIN travel t ON t.id = e.travelFk
JOIN supplier s ON s.id = e.supplierFk
JOIN warehouse w ON w.id = t.warehouseInFk
WHERE t.landed BETWEEN (vDated + INTERVAL - vLastBuyScope DAY) AND vDated
AND NOT s.name = 'INVENTARIO'
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND w.isComparative
- AND NOT e.isRaid
+ AND NOT t.isRaid
GROUP BY i.id;
-
+
UPDATE tmp.itemInventory y
JOIN lastBuyScope lbs ON lbs.id = y.id
SET y.buy_date = lbs.lastLanded;
@@ -65181,7 +64811,7 @@ BEGIN
LIMIT 1;
SET vHasNotInventory = (vInventoried IS NULL);
-
+
IF vHasNotInventory THEN
SELECT landed INTO vInventoryClone
FROM travel tr
@@ -65206,7 +64836,7 @@ BEGIN
PRIMARY KEY (warehouseInventory, itemFk) USING HASH
)
ENGINE = MEMORY;
-
+
-- Inventario inicial
IF vHasNotInventory THEN
INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
@@ -65265,7 +64895,7 @@ BEGIN
JOIN warehouse w ON w.id = tr.warehouseInFk
WHERE tr.landed BETWEEN vInventoried AND vDateDayEnd
AND IF(tr.landed = util.VN_CURDATE(), tr.isReceived, TRUE)
- AND NOT e.isRaid
+ AND NOT tr.isRaid
AND w.valuatedInventory
AND t.isInventory
AND e.supplierFk <> vInventorySupplierFk
@@ -65287,7 +64917,7 @@ BEGIN
JOIN itemCategory ic ON ic.id = t.categoryFk
JOIN warehouse w ON w.id = tr.warehouseOutFk
WHERE tr.shipped BETWEEN vInventoried AND vDateDayEnd
- AND NOT e.isRaid
+ AND NOT tr.isRaid
AND w.valuatedInventory
AND t.isInventory
AND (t.id = vItemTypeFk OR vItemTypeFk IS NULL)
@@ -65315,7 +64945,7 @@ BEGIN
ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + s.quantity * IF(vHasNotInventory, 1, -1);
-- Volver a poner lo que esta aun en las estanterias
- IF vDated = util.VN_CURDATE() THEN
+ IF vDated = util.VN_CURDATE() THEN
INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
SELECT w.id,
s.itemFk,
@@ -65352,14 +64982,14 @@ BEGIN
JOIN warehouse wIn ON wIn.id = tr.warehouseInFk
JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk
WHERE vDated >= tr.shipped AND vDated < tr.landed
- AND NOT isRaid
+ AND NOT tr.isRaid
AND wIn.valuatedInventory
AND t.isInventory
AND e.isConfirmed
AND (t.id = vItemTypeFk OR vItemTypeFk IS NULL)
AND (ic.id = vItemCategoryFk OR vItemCategoryFk IS NULL)
ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity);
-
+
CALL buy_getUltimate (NULL, NULL, vDateDayEnd);
DELETE FROM tInventory WHERE quantity IS NULL OR NOT quantity;
@@ -65389,7 +65019,7 @@ BEGIN
JOIN warehouse w ON w.id = warehouseFk
JOIN item i ON i.id = ti.itemFk
JOIN itemType tp ON tp.id = i.typeFk
- JOIN itemCategory ic ON ic.id = tp.categoryFk
+ JOIN itemCategory ic ON ic.id = tp.categoryFk
WHERE w.valuatedInventory
AND ti.total > 0;
@@ -65728,155 +65358,6 @@ set @cajas := 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_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `machineWorker_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 */ ;
-DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `machineWorker_add`(vPlate VARCHAR(10), vWorkerFk INT)
-BEGIN
-
-/**
- * Inserta registro si el vWorkerFk no ha registrado nada en las últimas 12 horas
- * @param vPlate número de matrícula
- * @param vWorkerFk id del worker
- *
-*/
- UPDATE vn.machineWorker mw
- JOIN vn.machine m ON m.id = mw.machineFk
- SET mw.outTimed = util.VN_NOW()
- WHERE (mw.workerFk = vWorkerFk OR m.plate = vPlate)
- AND ISNULL(mw.outTimed);
-
- INSERT INTO machineWorker (machineFk, workerFk)
- SELECT m.id, vWorkerFk
- FROM machine m
- WHERE m.plate= vPlate;
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `machineWorker_getHistorical` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `machineWorker_getHistorical`(vPlate VARCHAR(20), vWorkerFk INT)
-BEGIN
-/**
- * Obtiene historial de la matrícula vPlate que el trabajador vWorkerFk escanea,
- * si es jefe de producción muestra el historial completo.
- *
- * @param vPlate número de matrícula
- * @param vWorkerFk id del trabajador
- *
-*/
- DECLARE vWorkerName VARCHAR(255) DEFAULT account.user_getNameFromId(vWorkerFk);
-
- SELECT mw.inTimed,account.user_getNameFromId(mw.workerFk) as workerName, mw.outTimed
- FROM machineWorker mw
- JOIN machine m ON m.plate = vPlate
- WHERE mw.machineFk = m.id
- AND mw.workerFk = IF(account.user_hasRole(vWorkerName, 'coolerAssist'), mw.workerFk, vWorkerFk)
- ORDER BY mw.inTimed DESC;
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `machineWorker_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 */ ;
-DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `machineWorker_update`(vPlate VARCHAR(10), vWorkerFk INT)
-BEGIN
-
-/**
- * Actualiza el registro correspondiente si el vWorkerFk se ha registrado en las últimas horas (campo maxHours de machineWorkerConfig) con vPlate,
- *
- * @param vPlate número de matrícula
- * @param vWorkerFk id del trabajador
- *
-*/
-
- DECLARE vMachineFk INT(10);
- DECLARE vMaxHours INT(10);
-
- SELECT m.id INTO vMachineFk
- FROM machine m
- WHERE m.plate = vPlate;
-
- SELECT maxHours INTO vMaxHours
- FROM machineWorkerConfig;
-
- IF (SELECT COUNT(*)
- FROM machineWorker m
- WHERE m.workerFk = vWorkerFk
- AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW()) AND ISNULL(m.outTimed)) THEN
-
- UPDATE machineWorker m
- SET m.outTimed = CURRENT_TIMESTAMP()
- WHERE m.workerFk = vWorkerFk
- AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW())
- AND ISNULL(m.outTimed)
- AND m.machineFk = vMachineFk;
-
- END IF;
-
-END ;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `machine_getWorkerPlate` */;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `machine_getWorkerPlate`(vWorkerFk INT)
-BEGIN
-/**
- * Selecciona la matrícula del vehículo del workerfk
- *
- * @param vWorkerFk el id del trabajador
- */
- SELECT m.plate
- FROM machine m
- JOIN machineWorker mw ON mw.machineFk = m.id
- WHERE mw.inTimed >= TIMESTAMPADD(HOUR , -12,util.VN_NOW())
- AND ISNULL(mw.outTimed)
- AND mw.workerFk = vWorkerFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -66074,176 +65555,176 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `multipleInventory`(
- vDate DATE,
- vWarehouseFk TINYINT,
- vMaxDays TINYINT
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `multipleInventory`(
+ vDate DATE,
+ vWarehouseFk TINYINT,
+ vMaxDays TINYINT
)
-proc: BEGIN
- DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY;
- DECLARE vDateFrom DATE DEFAULT vDate;
- DECLARE vDateTo DATETIME;
- DECLARE vDateToTomorrow DATETIME;
- DECLARE vDefaultDayRange INT;
- DECLARE vCalcFk INT;
-
- IF vDate < util.VN_CURDATE() THEN
- LEAVE proc;
- END IF;
-
- IF vDate = util.VN_CURDATE() THEN
- SELECT inventoried INTO vDateFrom
- FROM config;
- END IF;
-
- SELECT defaultDayRange INTO vDefaultDayRange
- FROM comparativeConfig;
-
- SET vDateTo = vDate + INTERVAL IFNULL(vMaxDays, vDefaultDayRange) DAY;
- SET vDateToTomorrow = vDateTo + INTERVAL 1 DAY;
-
- ALTER TABLE tmp.itemInventory
- 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';
-
- -- Calculo del inventario
- CREATE OR REPLACE TEMPORARY TABLE tItemInventoryCalc
- (PRIMARY KEY (itemFk))
- ENGINE = MEMORY
- SELECT itemFk,
- SUM(quantity) quantity
- FROM (
- SELECT s.itemFk, - s.quantity quantity
- FROM sale s
- JOIN ticket t ON t.id = s.ticketFk
- JOIN warehouse w ON w.id = t.warehouseFk
- WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate)
- AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk
- AND w.isComparative
- UNION ALL
- SELECT b.itemFk, b.quantity
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- JOIN warehouse w ON w.id = t.warehouseInFk
- WHERE t.landed BETWEEN vDateFrom AND util.dayEnd(vDate)
- AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk
- AND w.isComparative
- AND NOT e.isExcludedFromAvailable
- AND NOT e.isRaid
- UNION ALL
- SELECT b.itemFk, - b.quantity
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- JOIN warehouse w ON w.id = t.warehouseOutFk
- WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate)
- AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk
- AND w.isComparative
- AND NOT e.isExcludedFromAvailable
- AND NOT e.isRaid
- ) sub
- GROUP BY itemFk;
-
- -- Cálculo del visible
- CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk);
-
- CREATE OR REPLACE TEMPORARY TABLE tItemVisibleCalc
- (PRIMARY KEY (item_id))
- ENGINE = MEMORY
- SELECT item_id, visible
- FROM cache.visible
- WHERE calc_id = vCalcFk;
-
- UPDATE tmp.itemInventory it
- LEFT JOIN tItemInventoryCalc iic ON iic.itemFk = it.id
- LEFT JOIN tItemVisibleCalc ivc ON ivc.item_id = it.id
- SET it.inventory = iic.quantity,
- it.visible = ivc.visible,
- it.avalaible = iic.quantity,
- it.sd = iic.quantity;
-
- -- Calculo del disponible
- CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc
- (INDEX (itemFk, warehouseFk))
- ENGINE = MEMORY
- SELECT sub.itemFk,
- vWarehouseFk warehouseFk,
- sub.dated,
- SUM(sub.quantity) quantity
- FROM (
- SELECT s.itemFk,
- DATE(t.shipped) dated,
- - s.quantity quantity
- FROM sale s
- JOIN ticket t ON t.id = s.ticketFk
- JOIN warehouse w ON w.id = t.warehouseFk
- WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo
- AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk
- AND w.isComparative
- UNION ALL
- SELECT b.itemFk, t.landed, b.quantity
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- JOIN warehouse w ON w.id = t.warehouseInFk
- WHERE t.landed BETWEEN vDateTomorrow AND vDateTo
- AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk
- AND w.isComparative
- AND NOT e.isExcludedFromAvailable
- AND NOT e.isRaid
- UNION ALL
- SELECT b.itemFk, t.shipped, - b.quantity
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- JOIN warehouse w ON w.id = t.warehouseOutFk
- WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo
- AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk
- AND w.isComparative
- AND NOT e.isExcludedFromAvailable
- AND NOT e.isRaid
- ) sub
- GROUP BY sub.itemFk, sub.dated;
-
- CALL item_getAtp(vDate);
- CALL travel_upcomingArrivals(vWarehouseFk, vDate);
-
- CREATE OR REPLACE TEMPORARY TABLE tItemAvailableCalc
- (PRIMARY KEY (itemFk))
- ENGINE = MEMORY
- SELECT it.itemFk,
- SUM(it.quantity) quantity,
- im.quantity minQuantity
- FROM tmp.itemCalc it
- JOIN tmp.itemAtp im ON im.itemFk = it.itemFk
- JOIN item i ON i.id = it.itemFk
- LEFT JOIN origin o ON o.id = i.originFk
- LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk
- WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL,
- t.landing,
- vDateToTomorrow)
- GROUP BY it.itemFk;
-
- UPDATE tmp.itemInventory it
- JOIN tItemAvailableCalc iac ON iac.itemFk = it.id
- SET it.avalaible = IF(iac.minQuantity > 0,
- it.avalaible,
- it.avalaible + iac.minQuantity),
- it.sd = it.inventory + iac.quantity;
-
- DROP TEMPORARY TABLE
- tmp.itemTravel,
- tmp.itemCalc,
- tmp.itemAtp,
- tItemInventoryCalc,
- tItemVisibleCalc,
- tItemAvailableCalc;
+proc: BEGIN
+ DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY;
+ DECLARE vDateFrom DATE DEFAULT vDate;
+ DECLARE vDateTo DATETIME;
+ DECLARE vDateToTomorrow DATETIME;
+ DECLARE vDefaultDayRange INT;
+ DECLARE vCalcFk INT;
+
+ IF vDate < util.VN_CURDATE() THEN
+ LEAVE proc;
+ END IF;
+
+ IF vDate = util.VN_CURDATE() THEN
+ SELECT inventoried INTO vDateFrom
+ FROM config;
+ END IF;
+
+ SELECT defaultDayRange INTO vDefaultDayRange
+ FROM comparativeConfig;
+
+ SET vDateTo = vDate + INTERVAL IFNULL(vMaxDays, vDefaultDayRange) DAY;
+ SET vDateToTomorrow = vDateTo + INTERVAL 1 DAY;
+
+ ALTER TABLE tmp.itemInventory
+ 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';
+
+ -- Calculo del inventario
+ CREATE OR REPLACE TEMPORARY TABLE tItemInventoryCalc
+ (PRIMARY KEY (itemFk))
+ ENGINE = MEMORY
+ SELECT itemFk,
+ SUM(quantity) quantity
+ FROM (
+ SELECT s.itemFk, - s.quantity quantity
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate)
+ AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk
+ AND w.isComparative
+ UNION ALL
+ SELECT b.itemFk, b.quantity
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN warehouse w ON w.id = t.warehouseInFk
+ WHERE t.landed BETWEEN vDateFrom AND util.dayEnd(vDate)
+ AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk
+ AND w.isComparative
+ AND NOT e.isExcludedFromAvailable
+ AND NOT t.isRaid
+ UNION ALL
+ SELECT b.itemFk, - b.quantity
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN warehouse w ON w.id = t.warehouseOutFk
+ WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate)
+ AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk
+ AND w.isComparative
+ AND NOT e.isExcludedFromAvailable
+ AND NOT t.isRaid
+ ) sub
+ GROUP BY itemFk;
+
+ -- Cálculo del visible
+ CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk);
+
+ CREATE OR REPLACE TEMPORARY TABLE tItemVisibleCalc
+ (PRIMARY KEY (item_id))
+ ENGINE = MEMORY
+ SELECT item_id, visible
+ FROM cache.visible
+ WHERE calc_id = vCalcFk;
+
+ UPDATE tmp.itemInventory it
+ LEFT JOIN tItemInventoryCalc iic ON iic.itemFk = it.id
+ LEFT JOIN tItemVisibleCalc ivc ON ivc.item_id = it.id
+ SET it.inventory = iic.quantity,
+ it.visible = ivc.visible,
+ it.avalaible = iic.quantity,
+ it.sd = iic.quantity;
+
+ -- Calculo del disponible
+ CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc
+ (INDEX (itemFk, warehouseFk))
+ ENGINE = MEMORY
+ SELECT sub.itemFk,
+ vWarehouseFk warehouseFk,
+ sub.dated,
+ SUM(sub.quantity) quantity
+ FROM (
+ SELECT s.itemFk,
+ DATE(t.shipped) dated,
+ - s.quantity quantity
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo
+ AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk
+ AND w.isComparative
+ UNION ALL
+ SELECT b.itemFk, t.landed, b.quantity
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN warehouse w ON w.id = t.warehouseInFk
+ WHERE t.landed BETWEEN vDateTomorrow AND vDateTo
+ AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk
+ AND w.isComparative
+ AND NOT e.isExcludedFromAvailable
+ AND NOT t.isRaid
+ UNION ALL
+ SELECT b.itemFk, t.shipped, - b.quantity
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN warehouse w ON w.id = t.warehouseOutFk
+ WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo
+ AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk
+ AND w.isComparative
+ AND NOT e.isExcludedFromAvailable
+ AND NOT t.isRaid
+ ) sub
+ GROUP BY sub.itemFk, sub.dated;
+
+ CALL item_getAtp(vDate);
+ CALL travel_upcomingArrivals(vWarehouseFk, vDate);
+
+ CREATE OR REPLACE TEMPORARY TABLE tItemAvailableCalc
+ (PRIMARY KEY (itemFk))
+ ENGINE = MEMORY
+ SELECT it.itemFk,
+ SUM(it.quantity) quantity,
+ im.quantity minQuantity
+ FROM tmp.itemCalc it
+ JOIN tmp.itemAtp im ON im.itemFk = it.itemFk
+ JOIN item i ON i.id = it.itemFk
+ LEFT JOIN origin o ON o.id = i.originFk
+ LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk
+ WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL,
+ t.landing,
+ vDateToTomorrow)
+ GROUP BY it.itemFk;
+
+ UPDATE tmp.itemInventory it
+ JOIN tItemAvailableCalc iac ON iac.itemFk = it.id
+ SET it.avalaible = IF(iac.minQuantity > 0,
+ it.avalaible,
+ it.avalaible + iac.minQuantity),
+ it.sd = it.inventory + iac.quantity;
+
+ DROP TEMPORARY TABLE
+ tmp.itemTravel,
+ tmp.itemCalc,
+ tmp.itemAtp,
+ tItemInventoryCalc,
+ tItemVisibleCalc,
+ tItemAvailableCalc;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -67052,60 +66533,66 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `previousSticker_get`(vSaleGroupFk INT)
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `previousSticker_get`(
+ vSaleGroupFk INT
+)
BEGIN
/**
* Devuelve los campos a imprimir en una etiqueta de preparación previa.
- * Actualiza el valor de vn.saleGroup.parkingFk en el caso de que exista un
+ * Actualiza el valor de saleGroup.parkingFk en el caso de que exista un
* saleGroup del mismo ticket con parking, del mismo sector, para que todos se
* pongan juntos.
*
- * @param vSaleGroupFk Identificador de vn.saleGroup
+ * @param vSaleGroupFk Identificador de saleGroup
*/
DECLARE vTicketFk INT;
DECLARE vParkingFk INT;
DECLARE vSectorFk INT;
+ DECLARE vTicketLines INT;
- SELECT s.ticketFk
- INTO vTicketFk
- FROM vn.saleGroupDetail sgd
- JOIN vn.sale s ON s.id = sgd.saleFk
- WHERE sgd.saleGroupFk = vSaleGroupFk
- LIMIT 1;
+ WITH ticketData AS(
+ SELECT DISTINCT s.ticketFk
+ FROM vn.saleGroupDetail sgd
+ JOIN vn.sale s ON s.id = sgd.saleFk
+ WHERE sgd.saleGroupFk = vSaleGroupFk
+ )
+ SELECT COUNT(*), s.ticketFk INTO vTicketLines, vTicketFk
+ FROM vn.sale s
+ JOIN ticketData td ON td.ticketFk = s.ticketFk;
SELECT sg.parkingFk, sc.sectorFk
INTO vParkingFk, vSectorFk
- FROM vn.saleGroup sg
- JOIN vn.sectorCollectionSaleGroup scsg ON scsg.saleGroupFk = sg.id
- JOIN vn.sectorCollection sc ON sc.id = scsg.sectorCollectionFk
- JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = sg.id
- JOIN vn.sale s ON s.id = sgd.saleFk
+ FROM saleGroup sg
+ JOIN sectorCollectionSaleGroup scsg ON scsg.saleGroupFk = sg.id
+ JOIN sectorCollection sc ON sc.id = scsg.sectorCollectionFk
+ JOIN saleGroupDetail sgd ON sgd.saleGroupFk = sg.id
+ JOIN sale s ON s.id = sgd.saleFk
WHERE s.ticketFk = vTicketFk
AND sg.parkingFk IS NOT NULL
LIMIT 1;
- UPDATE vn.saleGroup sg
+ UPDATE saleGroup sg
SET sg.parkingFk = vParkingFk
WHERE sg.id = vSaleGroupFk
AND sg.sectorFk = vSectorFk;
SELECT sgd.saleGroupFk,
t.id ticketFk,
- p.code as location,
- t.observations,
+ COUNT(*) previousLines,
IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) shippingHour,
IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) shippingMinute ,
IFNULL(MAX(i.itemPackingTypeFk),'H') itemPackingTypeFk ,
- count(*) items,
+ vTicketLines ticketLines,
+ p.code `location`,
sc.description sector
- FROM vn.sale s
- JOIN vn.item i ON i.id = s.itemFk
- JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id
- JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk
- JOIN vn.sector sc ON sc.id = sg.sectorFk
- JOIN vn.ticket t ON t.id = s.ticketFk
- LEFT JOIN vn.parking p ON p.id = sg.parkingFk
- LEFT JOIN vn.`zone` z ON z.id = t.zoneFk
+ FROM sale s
+ JOIN item i ON i.id = s.itemFk
+ JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
+ JOIN saleGroup sg ON sg.id = sgd.saleGroupFk
+ JOIN sector sc ON sc.id = sg.sectorFk
+ JOIN ticket t ON t.id = s.ticketFk
+ LEFT JOIN parking p ON p.id = sg.parkingFk
+ LEFT JOIN `zone` z ON z.id = t.zoneFk
WHERE sgd.saleGroupFk = vSaleGroupFk;
END ;;
DELIMITER ;
@@ -67174,13 +66661,11 @@ proc: BEGIN
DECLARE vEndingDate DATETIME;
DECLARE vIsTodayRelative BOOLEAN;
- SELECT util.dayEnd(util.VN_CURDATE()) + INTERVAL LEAST(vScopeDays, maxProductionScopeDays) DAY
- INTO vEndingDate
- FROM productionConfig;
-
- SELECT isTodayRelative INTO vIsTodayRelative
- FROM worker
- WHERE id = getUser(); -- Cambiar por account.myUser_getId(), falta dar permisos
+ SELECT w.isTodayRelative, util.dayEnd(util.VN_CURDATE()) + INTERVAL LEAST(vScopeDays, pc.maxProductionScopeDays) DAY
+ INTO vIsTodayRelative,vEndingDate
+ FROM worker w
+ JOIN productionConfig pc
+ WHERE w.id = account.myUser_getId();
CALL prepareTicketList(util.yesterday(), vEndingDate);
@@ -67378,7 +66863,7 @@ proc: BEGIN
st.code = 'previousPrepared' isPreviousPrepared,
sc.itemPackingTypeFk
FROM itemShelving ish
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN sector sc ON sc.id = p.sectorFk
JOIN sectorType st ON st.id = sc.typeFk
@@ -67427,14 +66912,13 @@ proc: BEGIN
UPDATE tmp.productionBuffer pb
JOIN sale s ON s.ticketFk = pb.ticketFk
JOIN item i ON i.id = s.itemFk
- JOIN itemType it ON it.id = i.typeFk
- JOIN itemCategory ic ON ic.id = it.categoryFk
- JOIN cache.last_buy lb ON lb.warehouse_id = vWarehouseFk AND lb.item_id = s.itemFk
+ JOIN cache.last_buy lb ON lb.warehouse_id = vWarehouseFk
+ AND lb.item_id = s.itemFk
JOIN buy b ON b.id = lb.buy_id
JOIN packaging p ON p.id = b.packagingFk
- JOIN productionConfig pc
SET pb.hasPlantTray = TRUE
WHERE p.isPlantTray
+ AND s.quantity >= b.packing
AND pb.isOwn;
DROP TEMPORARY TABLE
@@ -67753,7 +67237,6 @@ BEGIN
i.itemPackingTypeFk,
isa.`size`,
isa.Estado,
- isa.sectorProdPriority,
isa.available,
isa.sectorFk,
isa.matricula,
@@ -67811,7 +67294,7 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `raidUpdate` */;
+/*!50003 DROP PROCEDURE IF EXISTS `queueMember_updateQueue` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
@@ -67819,34 +67302,31 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `raidUpdate`()
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `queueMember_updateQueue`(
+ vBusinessFk INT
+)
BEGIN
-/**
- * Actualiza el travel de las entradas de redadas
- */
- UPDATE entry e
- JOIN entryVirtual ev ON ev.entryFk = e.id
- JOIN travel t ON t.id = e.travelFk
- JOIN (
- SELECT *
- FROM (
- SELECT t.id, t.landed, tt.warehouseInFk, tt.warehouseOutFk
- FROM travel t
- JOIN (
- SELECT t.warehouseInFk, t.warehouseOutFk
- FROM entryVirtual ev
- JOIN entry e ON e.id = ev.entryFk
- JOIN travel t ON t.id = e.travelFk
- GROUP BY t.warehouseInFk, t.warehouseOutFk
- ) tt ON t.warehouseInFk = tt.warehouseInFk AND t.warehouseOutFk = tt.warehouseOutFk
- WHERE shipped > util.VN_CURDATE() AND NOT isDelivered
- ORDER BY t.landed
- LIMIT 10000000000000000000
- ) t
- GROUP BY t.warehouseInFk, t.warehouseOutFk
- ) tt ON t.warehouseInFk = tt.warehouseInFk AND t.warehouseOutFk = tt.warehouseOutFk
- SET e.travelFk = t.id;
+ /**
+ * Elimina la entrada de la cola anterior y luego inserta la nueva para un trabajador.
+ *
+ * @param vBusinessFk ID del negocio
+ */
+ DECLARE vNewQueue VARCHAR(10);
+ DECLARE vExtension VARCHAR(10);
+ DECLARE exit handler FOR SQLEXCEPTION
+ SELECT d.pbxQueue, s.extension
+ INTO vNewQueue, vExtension
+ FROM business b
+ JOIN department d ON d.id = b.departmentFk
+ JOIN pbx.sip s ON s.user_id = b.workerFk
+ WHERE b.id = vBusinessFk;
+
+ DELETE FROM pbx.queueMember
+ WHERE extension = vExtension COLLATE utf8_general_ci;
+
+ INSERT IGNORE INTO pbx.queueMember (queue, extension)
+ VALUES (vNewQueue, vExtension);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -68424,7 +67904,7 @@ BEGIN
rm.ticketFree = 0,
rm.ticketProduction = 0,
rm.ticketPacked = 0,
- rm.dated = r.created;
+ rm.dated = r.dated;
UPDATE routesMonitor rm
JOIN (
@@ -68581,8 +68061,10 @@ BEGIN
*/
DECLARE vIsUpdatable, vIsFreelance BOOL DEFAULT 0;
DECLARE vAgencyModePricePercentage DOUBLE;
+ DECLARE vIsKmTruckRate BOOL;
+ DECLARE vCountryFk INT;
- SELECT r.created >= rc.cutoffDated INTO vIsUpdatable
+ SELECT r.dated >= rc.cutoffDated INTO vIsUpdatable
FROM route r
JOIN routeConfig rc
WHERE r.id = vSelf;
@@ -68591,10 +68073,17 @@ BEGIN
DELETE FROM routeCommission
WHERE routeFk = vSelf;
- SELECT w.isFreelance INTO vIsFreelance
+ SELECT w.isFreelance, v.isKmTruckRate, p.countryFk INTO vIsFreelance, vIsKmTruckRate, vCountryFk
FROM route r
JOIN worker w ON w.id = r.workerFk
- WHERE r.id = vSelf;
+ JOIN vehicle v ON v.id = r.vehicleFk
+ LEFT JOIN ticket t ON t.routeFk = r.id
+ LEFT JOIN address a ON a.id = t.addressFk
+ LEFT JOIN province p ON p.id = a.provinceFk
+ WHERE r.id = vSelf
+ GROUP BY p.countryFk
+ ORDER BY COUNT(*) DESC
+ LIMIT 1;
SELECT ampp.percentage INTO vAgencyModePricePercentage
FROM route r
@@ -68609,7 +68098,9 @@ BEGIN
workCenterFk,
freelanceYearlyM3,
cat4m3,
- cat5m3
+ cat5m3,
+ isKmTruckRate,
+ countryFk
)
SELECT vSelf,
r.commissionWorkCenterFk,
@@ -68621,11 +68112,14 @@ BEGIN
IFNULL(r.m3, 0),
0
),
- rc.distributionCat4M3 * IFNULL(r.m3, 0),
- rc.distributionCat5M3 * IFNULL(r.m3, 0)
+ IFNULL(wc.distributionCat4M3, rc.distributionCat4M3) * IFNULL(r.m3, 0),
+ IFNULL(wc.distributionCat5M3, rc.distributionCat5M3) * IFNULL(r.m3, 0),
+ vIsKmTruckRate,
+ vCountryFk
FROM route r
JOIN vehicle v ON v.id = r.vehicleFk
JOIN routeConfig rc
+ LEFT JOIN workCenterCommission wc ON wc.workCenterFk = r.commissionWorkCenterFk
WHERE r.id = vSelf
AND r.workerFk
AND r.commissionWorkCenterFk;
@@ -68638,21 +68132,28 @@ BEGIN
yearlyKm,
yearlyM3,
cat4m3,
- cat5m3
+ cat5m3,
+ isKmTruckRate,
+ countryFk
)
SELECT vSelf,
r.commissionWorkCenterFk,
(r.kmEnd - r.kmStart) *
IF(v.isKmTruckRate, rc.kmHeavy, rc.kmLight),
IFNULL(r.m3, 0) *
- IF(v.isKmTruckRate, rc.deliveryM3Cat5, rc.deliveryM3Cat4),
+ IF(v.isKmTruckRate,
+ IFNULL(wc.deliveryM3Cat5, rc.deliveryM3Cat5),
+ IFNULL(wc.deliveryM3Cat4, rc.deliveryM3Cat4)),
(r.kmEnd - r.kmStart) * rc.kmYearly,
IFNULL(r.m3, 0) * rc.m3Yearly,
- rc.distributionCat4M3 * IFNULL(r.m3, 0),
- rc.distributionCat5M3 * IFNULL(r.m3, 0)
+ IFNULL(wc.distributionCat4M3, rc.distributionCat4M3) * IFNULL(r.m3, 0),
+ IFNULL(wc.distributionCat5M3, rc.distributionCat5M3) * IFNULL(r.m3, 0),
+ vIsKmTruckRate,
+ vCountryFk
FROM route r
JOIN vehicle v ON v.id = r.vehicleFk
JOIN routeConfig rc
+ LEFT JOIN workCenterCommission wc ON wc.workCenterFk = r.commissionWorkCenterFk
WHERE r.id = vSelf
AND r.kmStart
AND r.kmEnd
@@ -69312,6 +68813,39 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `saleTracking_sectorCollectionAddPrevOK` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `saleTracking_sectorCollectionAddPrevOK`(
+ vSectorCollectionFk INT
+)
+BEGIN
+/**
+ * Inserta los registros de sectorCollection con el estado PREVIA OK si la reserva está picked
+ *
+ * @param vSectorCollectionFk Identificador de vn.sectorCollection
+ */
+ REPLACE saleTracking(saleFk, isChecked, workerFk, stateFk)
+ SELECT sgd.saleFk, TRUE, sc.userFk, s.id
+ FROM sectorCollection sc
+ JOIN sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id
+ JOIN saleGroupDetail sgd ON sgd.saleGroupFk = scsg.saleGroupFk
+ JOIN state s ON s.code = 'OK PREVIOUS'
+ JOIN itemShelvingSale iss ON iss.saleFk = sgd.saleFk
+ WHERE sc.id = vSectorCollectionFk AND iss.isPicked;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `saleTracking_updateIsChecked` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -69388,7 +68922,7 @@ BEGIN
DECLARE vQuantity INT;
DECLARE vRemainder INT DEFAULT 0;
DECLARE vRemainderSaleFk INT;
- DECLARE vShelving VARCHAR(10);
+ DECLARE vShelvingFk VARCHAR(10);
DECLARE vTicketFk INT;
SELECT s.quantity,
@@ -69435,7 +68969,7 @@ w1: WHILE vQuantity >= vPacking DO
p.pickingOrder,
ish.created
FROM itemShelving ish
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
LEFT JOIN itemShelvingSale iss
ON iss.itemShelvingFk = ish.id
@@ -69623,9 +69157,9 @@ w1: WHILE vQuantity >= vPacking DO
CALL dipole.expedition_Add(vExpeditionFk,vPrinterFk, TRUE);
SELECT shelvingFk, p.code
- INTO vShelving, vParkingCode
+ INTO vShelvingFk, vParkingCode
FROM itemShelving ish
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
WHERE ish.id = vItemShelvingFk;
@@ -69634,7 +69168,7 @@ w1: WHILE vQuantity >= vPacking DO
itemFk = vItemFk,
quantity = vPacking,
longName = vConcept,
- shelvingFk = vShelving,
+ shelvingFk = vShelvingFk,
parkingCode = vParkingCode,
phone = RIGHT(phone,vMaxPhoneLength),
street = RIGHT(street, vMAxStreetLength)
@@ -69736,7 +69270,7 @@ BEGIN
AND iss.created >= vDated
GROUP BY iss.itemShelvingFk, s.itemFk) tISS
ON tISS.itemFk = ish.itemFk AND tISS.itemShelvingFk = ish.id
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN tmp.productionBuffer pb ON pb.ticketFk = s.ticketFk
JOIN agencyMode am ON am.id = pb.agencyModeFk
@@ -69954,7 +69488,7 @@ BEGIN
isTooLittle BOOL DEFAULT FALSE,
isVip BOOL DEFAULT FALSE,
PRIMARY KEY (ticketFk, saleFk)
- ) ENGINE = MEMORY;
+ ); -- No memory
INSERT INTO tmp.sale_problems(ticketFk,
saleFk,
@@ -70001,7 +69535,7 @@ BEGIN
SUM(ish.visible) visible,
s.warehouseFk warehouseFk
FROM itemShelving ish
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN sector s ON s.id = p.sectorFk
GROUP BY ish.itemFk, s.warehouseFk;
@@ -70041,7 +69575,7 @@ BEGIN
LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
AND issw.warehouseFk = t.warehouseFk
WHERE IFNULL(v.visible, 0) < s.quantity
- AND IFNULL(av.available, 0) < s.quantity
+ AND IFNULL(av.available, 0) < 0
AND IFNULL(issw.visible, 0) < s.quantity
AND NOT s.isPicked
AND NOT s.reserved
@@ -70104,7 +69638,7 @@ BEGIN
LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
AND issw.warehouseFk = t.warehouseFk
WHERE IFNULL(v.visible, 0) < s.quantity
- AND IFNULL(av.available, 0) >= s.quantity
+ AND IFNULL(av.available, 0) >= 0
AND IFNULL(issw.visible, 0) < s.quantity
AND s.quantity > 0
AND NOT s.isPicked
@@ -71029,14 +70563,16 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `shelvingChange`(IN `vShelvingO` VARCHAR(8), IN `vShelvingD` VARCHAR(8))
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `shelvingChange`(
+ `vShelvingO` VARCHAR(10),
+ `vShelvingD` VARCHAR(10)
+)
BEGIN
-
- UPDATE vn.itemShelving
- SET shelvingFk = vShelvingD COLLATE utf8_unicode_ci
- WHERE shelvingFk = vShelvingO COLLATE utf8_unicode_ci;
-
-
+ UPDATE itemShelving ish
+ JOIN shelving sh1 ON sh1.code = vShelvingD COLLATE utf8_unicode_ci
+ JOIN shelving sh2 ON sh2.code = vShelvingO COLLATE utf8_unicode_ci
+ SET ish.shelvingFk = sh1.id
+ WHERE ish.shelvingFk = sh2.id;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -71084,10 +70620,12 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `shelvingParking_get`(vShelvingFk VARCHAR(10), vWarehouseFk INT, vDayRange INT)
-BEGIN
-
-
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `shelvingParking_get`(
+ vShelvingCode VARCHAR(10),
+ vWarehouseFk INT,
+ vDayRange INT
+)
+BEGIN
SELECT s.itemFk,
s.concept,
CAST(SUM(s.quantity) AS DECIMAL(10,0)) as sinServir,
@@ -71095,15 +70633,16 @@ SELECT s.itemFk,
FROM vn.sale s
LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id
JOIN vn.ticket t ON t.id = s.ticketFk
- LEFT JOIN vn.itemShelvingStock ist ON ist.itemFk = s.itemFk AND ist.warehouseFk = vWarehouseFk
- JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk AND ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci
+ LEFT JOIN vn.itemShelvingStock ist ON ist.itemFk = s.itemFk
+ AND ist.warehouseFk = vWarehouseFk
+ JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
+ AND sh.code = vShelvingCode COLLATE utf8_general_ci
WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(TIMESTAMPADD(DAY, GREATEST(0,vDayRange), util.VN_CURDATE()))
AND iss.saleFk IS NULL
AND t.warehouseFk = vWarehouseFk
GROUP BY s.itemFk
HAVING sinServir > aparcado;
-
-
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -71154,12 +70693,12 @@ BEGIN
DELETE ish.*
FROM itemShelving ish
- JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.shelving sh ON sh.id = ish.shelvingFk
WHERE sh.parkingFk IS NULL
AND ish.created < TIMESTAMPADD(WEEK,-1,util.VN_CURDATE());
UPDATE shelving sh
- LEFT JOIN itemShelving its ON its.shelvingFk = sh.`code`
+ LEFT JOIN itemShelving its ON its.shelvingFk = sh.id
SET isPrinted = 0,
parkingFk = NULL
WHERE its.id IS NULL
@@ -71167,12 +70706,13 @@ UPDATE shelving sh
AND (
sh.parked IS NULL
OR
- sh.parked < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())
- )
+ sh.parked < util.VN_CURDATE() - INTERVAL 2 WEEK
+ )
AND IF(code REGEXP '^[A-Za-z]{2}[0-9]', LEFT (code, 2) NOT IN (
- SELECT DISTINCT LEFT(its.shelvingFk, 2)
+ SELECT DISTINCT LEFT(sh.code, 2)
FROM itemShelving its
- WHERE its.shelvingFk REGEXP '^[A-Za-z]{2}[0-9]'
+ JOIN shelving sh ON sh.id = its.shelvingFk
+ WHERE sh.code REGEXP '^[A-Za-z]{2}[0-9]'
), TRUE);
END ;;
@@ -71217,7 +70757,7 @@ BEGIN
LEFT JOIN (
SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS reserva
FROM vn.itemShelving ish
- JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.shelving sh ON sh.id = ish.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
JOIN vn.sector s ON s.id = p.sectorFk
WHERE s.code = 'FUENTES_PICASSE'
@@ -71260,7 +70800,7 @@ BEGIN
sh.isSpam
FROM vn.itemShelving ish
JOIN vn.item i ON i.id = ish.itemFk
- JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.shelving sh ON sh.id = ish.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
JOIN vn.sector s ON s.id = p.sectorFk
JOIN vn.warehouse w ON w.id = s.warehouseFk
@@ -71341,6 +70881,107 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `stockBought_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_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `stockBought_calculate`(
+ vDated DATE
+)
+proc: BEGIN
+/**
+ * Calculate the stock of the auction warehouse from the inventory date to vDated
+ * without taking into account the outputs of the same day vDated
+ *
+ * @param vDated Date to calculate the stock
+ */
+ IF vDated < util.VN_CURDATE() THEN
+ LEAVE proc;
+ END IF;
+
+ CREATE OR REPLACE TEMPORARY TABLE tCurrentData
+ SELECT workerFk, reserve
+ FROM stockBought
+ WHERE dated = vDated
+ AND reserve;
+
+ DELETE FROM stockBought WHERE dated = vDated;
+
+ CREATE OR REPLACE TEMPORARY TABLE tStockSold
+ SELECT it.workerFk,
+ SUM(ic.cm3 * ito.quantity / vc.palletM3 / 1000000) sold
+ FROM itemTicketOut ito
+ JOIN item i ON i.id = ito.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ JOIN ticket t ON t.id = ito.ticketFk
+ JOIN warehouse wh ON wh.id = t.warehouseFk
+ JOIN itemCost ic ON ic.itemFk = ito.itemFk
+ AND ic.warehouseFk = t.warehouseFk
+ JOIN volumeConfig vc
+ WHERE ito.shipped BETWEEN vDated AND util.dayEnd(vDated)
+ AND wh.code = 'VNH'
+ GROUP BY it.workerFk;
+
+ CALL item_calculateStock(vDated);
+
+ CREATE OR REPLACE TEMPORARY TABLE tStockBought
+ SELECT it.workerFk,
+ SUM((ti.quantity / b.packing) *
+ buy_getVolume(b.id)
+ ) / vc.palletM3 / 1000000 bought
+ FROM itemType it
+ JOIN item i ON i.typeFk = it.id
+ LEFT JOIN tmp.item ti ON ti.itemFk = i.id
+ JOIN itemCategory ic ON ic.id = it.categoryFk
+ JOIN warehouse wh ON wh.code = 'VNH'
+ JOIN tmp.buyUltimate bu ON bu.itemFk = i.id
+ AND bu.warehouseFk = wh.id
+ JOIN buy b ON b.id = bu.buyFk
+ JOIN volumeConfig vc
+ WHERE ic.display
+ GROUP BY it.workerFk
+ HAVING bought;
+
+
+ INSERT INTO stockBought(workerFk, bought, dated)
+ SELECT tb.workerFk,
+ ROUND(GREATEST(tb.bought - IFNULL(ts.sold, 0), 0), 2),
+ vDated
+ FROM tStockBought tb
+ LEFT JOIN tStockSold ts ON ts.workerFk = tb.workerFk;
+
+ UPDATE stockBought s
+ JOIN tCurrentData ts ON ts.workerFk = s.workerFk
+ SET s.reserve = ts.reserve
+ WHERE s.dated = vDated;
+
+ INSERT INTO stockBought (workerFk, reserve, dated)
+ SELECT ts.workerFk, ts.reserve, vDated
+ FROM tCurrentData ts
+ WHERE ts.workerFk NOT IN (
+ SELECT workerFk
+ FROM stockBought
+ WHERE dated = vDated
+ );
+
+ UPDATE stockBought s
+ JOIN tStockSold ts ON ts.workerFk = s.workerFk
+ SET s.bought = IF(s.bought < ABS(ts.sold), 0, ROUND(s.bought - ABS(ts.sold), 1))
+ WHERE s.dated = vDated;
+
+ DROP TEMPORARY TABLE tCurrentData, tmp.item, tmp.buyUltimate, tStockSold;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `stockBuyedByWorker` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -71373,7 +71014,7 @@ BEGIN
WHERE dated = vDated
AND userFk = vWorker;
- CALL stockTraslation(vDated);
+ CALL item_calculateStock(vDated);
INSERT INTO stockBuyed(userFk, buyed, `dated`, reserved, requested, description)
SELECT it.workerFk,
@@ -71455,7 +71096,7 @@ BEGIN
DELETE FROM stockBuyed WHERE dated = vDated;
- CALL stockTraslation(vDated);
+ CALL item_calculateStock(vDated);
INSERT INTO stockBuyed(userFk, buyed, `dated`, description)
SELECT it.workerFk,
@@ -71511,60 +71152,6 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `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 = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `stockTraslation`(
- vDated DATE
-)
-BEGIN
-/**
- * Calcula el stock del almacén de subasta desde FechaInventario hasta vDated
- * sin tener en cuenta las salidas del mismo dia vDated
- * para ver el transporte a reservar
- *
- * @param vDated Fecha hasta la cual calcula el stock
- * @return tmp.item
- */
- DECLARE vAuctionWarehouseFk INT;
-
- SELECT warehouseFk INTO vAuctionWarehouseFk
- FROM auctionConfig;
-
- CREATE OR REPLACE TEMPORARY TABLE tmp.item
- (UNIQUE INDEX i USING HASH (itemFk))
- ENGINE = MEMORY
- SELECT itemFk, SUM(quantity) quantity
- FROM itemEntryIn
- WHERE landed = vDated
- AND vDated >= util.VN_CURDATE()
- AND warehouseInFk = vAuctionWarehouseFk
- AND NOT isVirtualStock
- GROUP BY itemFk
- HAVING quantity;
-
- CALL `cache`.stock_refresh(FALSE);
-
- INSERT INTO tmp.item (itemFk, quantity)
- SELECT item_id, amount
- FROM `cache`.stock
- WHERE warehouse_id = vAuctionWarehouseFk
- ON DUPLICATE KEY UPDATE quantity = tmp.item.quantity + VALUES(quantity);
-
- CALL buy_getUltimate(NULL, vAuctionWarehouseFk, 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 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `subordinateGetList` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -72063,7 +71650,7 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `supplier_statementWithEntries`(
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `supplier_statementWithEntries`(
vSupplierFk INT,
vCurrencyFk INT,
vCompanyFk INT,
@@ -72081,14 +71668,14 @@ BEGIN
* @param vOrderBy Order by criteria
* @param vIsConciliated Indicates whether it is reconciled or not
* @param vHasEntries Indicates if future entries must be shown
-* @return tmp.supplierStatement
+* @return tmp.supplierStatement
*/
DECLARE vBalanceStartingDate DATETIME;
SET @euroBalance:= 0;
SET @currencyBalance:= 0;
- SELECT balanceStartingDate
+ SELECT balanceStartingDate
INTO vBalanceStartingDate
FROM invoiceInConfig;
@@ -72128,14 +71715,14 @@ BEGIN
c.code,
'invoiceIn' statementType
FROM invoiceIn ii
- JOIN invoiceInDueDay iid ON iid.invoiceInFk = ii.id
+ LEFT JOIN invoiceInDueDay iid ON iid.invoiceInFk = ii.id
JOIN currency c ON c.id = ii.currencyFk
WHERE ii.issued >= vBalanceStartingDate
- AND ii.supplierFk = vSupplierFk
+ AND ii.supplierFk = vSupplierFk
AND vCurrencyFk IN (ii.currencyFk, 0)
AND vCompanyFk IN (ii.companyFk, 0)
AND (vIsConciliated = ii.isBooked OR NOT vIsConciliated)
- GROUP BY iid.id
+ GROUP BY iid.id, ii.id
UNION ALL
SELECT p.bankFk,
p.companyFk,
@@ -72171,7 +71758,7 @@ BEGIN
AND vCurrencyFk IN (p.currencyFk, 0)
AND vCompanyFk IN (p.companyFk, 0)
AND (vIsConciliated = p.isConciliated OR NOT vIsConciliated)
- UNION ALL
+ UNION ALL
SELECT NULL,
companyFk,
NULL,
@@ -72198,7 +71785,7 @@ BEGIN
AND vCurrencyFk IN (se.currencyFk,0)
AND vCompanyFk IN (se.companyFk,0)
AND (vIsConciliated = se.isConciliated OR NOT vIsConciliated)
- UNION ALL
+ UNION ALL
SELECT NULL bankFk,
e.companyFk,
'E' serial,
@@ -72214,7 +71801,7 @@ BEGIN
FALSE isBooked,
c.code,
'order'
- FROM entry e
+ FROM entry e
JOIN travel tr ON tr.id = e.travelFk
JOIN currency c ON c.id = e.currencyFk
WHERE e.supplierFk = vSupplierFk
@@ -72756,7 +72343,7 @@ BEGIN
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.shelving sh ON sh.id = ish.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
WHERE p.sectorFk = vSectorFk
) sub ON sub.id = td.ticketFk
@@ -73294,6 +72881,44 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `ticketRefund_upsert` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `ticketRefund_upsert`(
+ vRefundTicketFk INT,
+ vOriginalTicketFk INT
+)
+ READS SQL DATA
+BEGIN
+/**
+ * Common code for ticketRefund triggers
+ *
+ * @param vRefundTicketFk
+ * @param vOriginalTicketFk
+ */
+ DECLARE vIsDeleted BOOL;
+
+ SELECT COUNT(*) INTO vIsDeleted
+ FROM ticket
+ WHERE id IN (vRefundTicketFk, vOriginalTicketFk)
+ AND isDeleted;
+
+ IF vIsDeleted THEN
+ CALL util.throw('The refund ticket cannot be deleted tickets');
+ END IF;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketStateToday_setState` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -73667,8 +73292,7 @@ BEGIN
CREATE OR REPLACE TEMPORARY TABLE tmp.filter
(INDEX (id))
- SELECT
- origin.ticketFk futureId,
+ SELECT origin.ticketFk futureId,
dest.ticketFk id,
dest.state,
origin.futureState,
@@ -73699,48 +73323,51 @@ BEGIN
origin.warehouseFk futureWarehouseFk,
origin.companyFk futureCompanyFk,
IFNULL(dest.nickname, origin.nickname) nickname,
- dest.landed
+ dest.landed,
+ dest.preparation,
+ origin.departmentFk
FROM (
- SELECT
- s.ticketFk,
- c.salesPersonFk workerFk,
- t.shipped,
- t.totalWithVat,
- st.name futureState,
- am.name futureAgency,
- count(s.id) futureLines,
- GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) futureIpt,
- CAST(SUM(litros) AS DECIMAL(10,0)) futureLiters,
- SUM(s.quantity <= (IFNULL(il.stock,0) + IFNULL(im.amount, 0))) hasStock,
- z.id futureZoneFk,
- z.name futureZoneName,
- st.classColor,
- t.clientFk,
- t.nickname,
- t.addressFk,
- t.warehouseFk,
- t.companyFk,
- t.agencyModeFk
- FROM ticket t
- JOIN client c ON c.id = t.clientFk
- JOIN sale s ON s.ticketFk = t.id
- JOIN saleVolume sv ON sv.saleFk = s.id
- JOIN item i ON i.id = s.itemFk
- JOIN ticketState ts ON ts.ticketFk = t.id
- JOIN state st ON st.id = ts.stateFk
- JOIN agencyMode am ON t.agencyModeFk = am.id
- JOIN zone z ON t.zoneFk = z.id
- LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk
- LEFT JOIN tmp.itemMinacum im ON im.itemFk = i.id
- AND im.warehouseFk = vWarehouseFk
- LEFT JOIN tmp.itemList il ON il.itemFk = i.id
- WHERE t.shipped BETWEEN vDateFuture AND util.dayend(vDateFuture)
- AND t.warehouseFk = vWarehouseFk
- GROUP BY t.id
+ SELECT s.ticketFk,
+ c.salesPersonFk workerFk,
+ t.shipped,
+ t.totalWithVat,
+ st.name futureState,
+ am.name futureAgency,
+ count(s.id) futureLines,
+ GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) futureIpt,
+ CAST(SUM(litros) AS DECIMAL(10,0)) futureLiters,
+ SUM(s.quantity <= (IFNULL(il.stock,0) + IFNULL(im.amount, 0))) hasStock,
+ z.id futureZoneFk,
+ z.name futureZoneName,
+ st.classColor,
+ t.clientFk,
+ t.nickname,
+ t.addressFk,
+ t.warehouseFk,
+ t.companyFk,
+ t.agencyModeFk,
+ wd.departmentFk
+ FROM ticket t
+ JOIN client c ON c.id = t.clientFk
+ JOIN workerDepartment wd ON wd.workerFk = c.salesPersonFk
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN saleVolume sv ON sv.saleFk = s.id
+ JOIN item i ON i.id = s.itemFk
+ JOIN ticketState ts ON ts.ticketFk = t.id
+ JOIN `state` st ON st.id = ts.stateFk
+ JOIN agencyMode am ON t.agencyModeFk = am.id
+ JOIN `zone` z ON t.zoneFk = z.id
+ LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk
+ LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk
+ LEFT JOIN tmp.itemMinacum im ON im.itemFk = i.id
+ AND im.warehouseFk = vWarehouseFk
+ LEFT JOIN tmp.itemList il ON il.itemFk = i.id
+ WHERE t.shipped BETWEEN vDateFuture AND util.dayend(vDateFuture)
+ AND t.warehouseFk = vWarehouseFk
+ GROUP BY t.id
) origin
LEFT JOIN (
- SELECT
- t.id ticketFk,
+ SELECT t.id ticketFk,
st.name state,
GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) ipt,
t.shipped,
@@ -73756,18 +73383,25 @@ BEGIN
t.warehouseFk,
t.companyFk,
t.landed,
- t.agencyModeFk
+ t.agencyModeFk,
+ SEC_TO_TIME(
+ COALESCE(HOUR(t.shipped), HOUR(zc.hour), HOUR(z.hour)) * 3600 +
+ COALESCE(MINUTE(t.shipped), MINUTE(zc.hour), MINUTE(z.hour)) * 60
+ ) preparation
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
JOIN saleVolume sv ON sv.saleFk = s.id
JOIN item i ON i.id = s.itemFk
JOIN ticketState ts ON ts.ticketFk = t.id
- JOIN state st ON st.id = ts.stateFk
+ JOIN `state` st ON st.id = ts.stateFk
JOIN agencyMode am ON t.agencyModeFk = am.id
LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk
+ LEFT JOIN `zone` z ON z.id = t.zoneFk
+ LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk
+ JOIN ticketCanAdvanceConfig tc
WHERE t.shipped BETWEEN vDateToAdvance AND util.dayend(vDateToAdvance)
AND t.warehouseFk = vWarehouseFk
- AND st.order <= 5
+ AND st.order <= tc.destinationOrder
GROUP BY t.id
) dest ON dest.addressFk = origin.addressFk
WHERE origin.hasStock;
@@ -73813,6 +73447,7 @@ BEGIN
t.clientFk,
t.warehouseFk,
ts.alertLevel,
+ sub2.alertLevel futureAlertLevel,
t.shipped,
t.totalWithVat,
sub2.shipped futureShipped,
@@ -73839,6 +73474,7 @@ BEGIN
t.addressFk,
t.id,
t.shipped,
+ ts.alertLevel,
st.name state,
st.code,
st.classColor,
@@ -74430,7 +74066,7 @@ BEGIN
c.isTaxDataChecked,
t.companyFk,
t.shipped,
- IFNULL(a.hasDailyInvoice, co.hasDailyInvoice),
+ c.hasDailyInvoice,
w.isManaged,
c.hasToInvoice
INTO vClientFk,
@@ -74442,9 +74078,6 @@ BEGIN
vHasToInvoice
FROM ticket t
JOIN `client` c ON c.id = t.clientFk
- JOIN province p ON p.id = c.provinceFk
- LEFT JOIN autonomy a ON a.id = p.autonomyFk
- JOIN country co ON co.id = p.countryFk
JOIN warehouse w ON w.id = t.warehouseFk
WHERE t.id = vCurTicketFk;
@@ -74472,7 +74105,7 @@ BEGIN
IF(vHasDailyInvoice) AND vHasToInvoice THEN
SELECT invoiceSerial(vClientFk, vCompanyFk, 'quick') INTO vSerial;
- IF vSerial IS NULL THEN
+ IF vSerial IS NULL THEN
CALL util.throw('Cannot booking without a serial');
END IF;
@@ -74851,7 +74484,7 @@ BEGIN
SUM(ish.visible) visible,
s.warehouseFk warehouseFk
FROM itemShelving ish
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN sector s ON s.id = p.sectorFk
GROUP BY ish.itemFk,
@@ -75293,7 +74926,7 @@ BEGIN
SUM(ish.visible) visible,
s.warehouseFk warehouseFk
FROM itemShelving ish
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN sector s ON s.id = p.sectorFk
GROUP BY ish.itemFk,
@@ -75437,7 +75070,9 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `ticket_getTax`(IN vTaxArea VARCHAR(25))
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `ticket_getTax`(
+ vTaxArea VARCHAR(25)
+)
BEGIN
/**
* Calcula la base imponible, el IVA y el recargo de equivalencia para
@@ -75471,30 +75106,39 @@ BEGIN
CREATE OR REPLACE TEMPORARY TABLE tmp.ticketTax
(PRIMARY KEY (ticketFk, code, rate))
ENGINE = MEMORY
- SELECT * FROM (
- SELECT tmpTicket.ticketFk,
- bp.pgcFk,
- SUM(s.quantity * s.price * (100 - s.discount) / 100 ) 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
+ WITH sales AS (
+ SELECT s.ticketFk,
+ s.itemFk,
+ s.quantity * s.price * (100 - s.discount) / 100 total,
+ t.companyFk,
+ t.addressFk,
+ su.countryFk,
+ ata.areaFk,
+ itc.taxClassFk
+ FROM vn.sale s
+ JOIN tmp.ticket tmp ON tmp.ticketFk = s.ticketFk
+ JOIN vn.ticket t ON t.id = s.ticketFk
+ JOIN vn.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
+ JOIN vn.itemTaxCountry itc ON itc.itemFk = s.itemFk
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
- ) t3
+ HAVING total
+ )
+ SELECT s.ticketFk,
+ bp.pgcFk,
+ SUM(s.total) taxableBase,
+ pgc.rate,
+ tc.code,
+ bp.priority
+ FROM sales s
+ JOIN vn.bookingPlanner bp ON bp.countryFk = s.countryFk
+ AND bp.taxAreaFk = s.areaFk
+ AND bp.taxClassFk = s.taxClassFk
+ JOIN vn.pgc ON pgc.code = bp.pgcFk
+ JOIN vn.taxClass tc ON tc.id = bp.taxClassFk
+ GROUP BY s.ticketFk, pgc.code, pgc.rate
+ HAVING taxableBase
ORDER BY priority;
CREATE OR REPLACE TEMPORARY TABLE tmp.ticketServiceTax
@@ -75713,16 +75357,29 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_mergeSales`(
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `ticket_mergeSales`(
vSelf INT
)
BEGIN
+/**
+ * Para un ticket se agrupa las diferentes líneas de venta de un mismo artículo en una sola
+ * siempre y cuando tengan el mismo precio y dto.
+ *
+ * @param vSelf Id de ticket
+ */
+ DECLARE vHasSalesToMerge BOOL;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
+ START TRANSACTION;
+
+ SELECT id INTO vSelf
+ FROM ticket
+ WHERE id = vSelf FOR UPDATE;
+
CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve
(PRIMARY KEY (id))
ENGINE = MEMORY
@@ -75732,26 +75389,24 @@ BEGIN
JOIN itemType it ON it.id = i.typeFk
WHERE s.ticketFk = vSelf
AND it.isMergeable
- GROUP BY s.itemFk, s.price, s.discount;
+ GROUP BY s.itemFk, s.price, s.discount
+ HAVING COUNT(*) > 1;
- START TRANSACTION;
+ SELECT COUNT(*) INTO vHasSalesToMerge FROM tSalesToPreserve;
- UPDATE sale s
- JOIN tSalesToPreserve stp ON stp.id = s.id
- SET s.quantity = newQuantity
- WHERE s.ticketFk = vSelf;
+ IF vHasSalesToMerge THEN
+ UPDATE sale s
+ JOIN tSalesToPreserve stp ON stp.id = s.id
+ SET s.quantity = newQuantity;
- DELETE s.*
- FROM sale s
- LEFT JOIN tSalesToPreserve stp ON stp.id = s.id
- JOIN item i ON i.id = s.itemFk
- JOIN itemType it ON it.id = i.typeFk
- WHERE s.ticketFk = vSelf
- AND stp.id IS NULL
- AND it.isMergeable;
+ DELETE s
+ FROM sale s
+ JOIN tSalesToPreserve stp ON stp.itemFk = s.itemFk
+ WHERE s.ticketFk = vSelf
+ AND s.id <> stp.id;
+ END IF;
COMMIT;
-
DROP TEMPORARY TABLE tSalesToPreserve;
END ;;
DELIMITER ;
@@ -76368,7 +76023,7 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setProblemRiskByClient`(
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `ticket_setProblemRiskByClient`(
vClientFk INT
)
BEGIN
@@ -76710,7 +76365,7 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setVolume`(
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `ticket_setVolume`(
vSelf INT
)
BEGIN
@@ -76747,7 +76402,7 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setVolumeItemCost`(
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `ticket_setVolumeItemCost`(
vItemFk INT
)
BEGIN
@@ -76894,123 +76549,123 @@ CREATE DEFINER=`vn`@`localhost` PROCEDURE `ticket_splitItemPackingType`(
)
BEGIN
/**
- * Clona y reparte las ventas de un ticket en funcion del tipo de empaquetado.
- * Respeta el id inicial para el tipo propuesto.
+ * Separa en diferentes tickets según el tipo de empaquetado
+ * El ticket original conserva las líneas del tipo de empaquetado especificado
+ * Las líneas sin tipo de empaquetado se asignan al ticket del tipo por defecto.
*
- * @param vSelf Id ticket
- * @param vOriginalItemPackingTypeFk Tipo para el que se reserva el número de ticket original
+ * @param vSelf Id del ticket original
+ * @param vOriginalItemPackingTypeFk Tipo de empaquetado a mantener en el ticket original
* @return table tmp.ticketIPT(ticketFk, itemPackingTypeFk)
*/
- DECLARE vItemPackingTypeFk VARCHAR(1) DEFAULT 'H';
+ DECLARE vIsDone BOOLEAN DEFAULT FALSE;
+ DECLARE vCurrentPackingType VARCHAR(1);
+ DECLARE vDefaultPackingType VARCHAR(1);
+ DECLARE vHasOriginalPackingType BOOLEAN;
DECLARE vNewTicketFk INT;
- DECLARE vPackingTypesToSplit INT;
- DECLARE vDone INT DEFAULT FALSE;
+ DECLARE vTicketFk INT;
- DECLARE vSaleGroup CURSOR FOR
- SELECT itemPackingTypeFk
- FROM tSaleGroup
- WHERE itemPackingTypeFk IS NOT NULL
- ORDER BY (itemPackingTypeFk = vOriginalItemPackingTypeFk) DESC;
+ DECLARE vItemPackingTypes CURSOR FOR
+ SELECT DISTINCT itemPackingTypeFk FROM tSalesToMove;
- DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE;
+
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ CREATE OR REPLACE TEMPORARY TABLE tSalesToMove (
+ ticketFk INT,
+ saleFk INT,
+ itemPackingTypeFk VARCHAR(1)
+ ) ENGINE=MEMORY;
+
+ SELECT COALESCE(MAX(ic.defaultPackingTypeFk), MAX(i.itemPackingTypeFk)) INTO vDefaultPackingType
+ FROM vn.sale s
+ JOIN item i ON i.id = s.itemFk
+ LEFT JOIN itemConfig ic ON ic.defaultPackingTypeFk = i.itemPackingTypeFk
+ WHERE s.ticketFk = vSelf
+ GROUP BY s.ticketFk;
+
+ SELECT EXISTS (
+ SELECT TRUE
+ FROM sale s
+ JOIN item i ON i.id = s.itemFk
+ WHERE s.ticketFk = vSelf
+ AND i.itemPackingTypeFk = vOriginalItemPackingTypeFk
+ ) INTO vHasOriginalPackingType;
+
+ IF vOriginalItemPackingTypeFk IS NULL OR NOT vHasOriginalPackingType THEN
+ SET vOriginalItemPackingTypeFk = vDefaultPackingType;
+ END IF;
START TRANSACTION;
- SELECT id
- FROM sale
- WHERE ticketFk = vSelf
- AND NOT quantity
+ SELECT t.id INTO vTicketFk
+ FROM ticket t
+ JOIN sale s ON s.id = t.id
+ WHERE t.id = vSelf
FOR UPDATE;
- DELETE FROM sale
- WHERE NOT quantity
- AND ticketFk = vSelf;
-
- CREATE OR REPLACE TEMPORARY TABLE tSale
- (PRIMARY KEY (id))
- ENGINE = MEMORY
- SELECT s.id, i.itemPackingTypeFk, IFNULL(sv.litros, 0) litros
+ INSERT INTO tSalesToMove (saleFk, itemPackingTypeFk)
+ SELECT s.id, i.itemPackingTypeFk
FROM sale s
JOIN item i ON i.id = s.itemFk
- LEFT JOIN saleVolume sv ON sv.saleFk = s.id
- WHERE s.ticketFk = vSelf;
+ WHERE s.ticketFk = vSelf
+ AND i.itemPackingTypeFk <> vOriginalItemPackingTypeFk;
- CREATE OR REPLACE TEMPORARY TABLE tSaleGroup
- ENGINE = MEMORY
- SELECT itemPackingTypeFk, SUM(litros) totalLitros
- FROM tSale
- GROUP BY itemPackingTypeFk;
+ OPEN vItemPackingTypes;
+ l: LOOP
+ SET vIsDone = FALSE;
+ FETCH vItemPackingTypes INTO vCurrentPackingType;
- SELECT COUNT(*) INTO vPackingTypesToSplit
- FROM tSaleGroup
- WHERE itemPackingTypeFk IS NOT NULL;
+ IF vIsDone THEN
+ LEAVE l;
+ END IF;
- CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT(
- ticketFk INT,
- itemPackingTypeFk VARCHAR(1)
- ) ENGINE = MEMORY;
+ CALL ticket_Clone(vSelf, vNewTicketFk);
- CASE vPackingTypesToSplit
- WHEN 0 THEN
- INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk)
- VALUES(vSelf, vItemPackingTypeFk);
- WHEN 1 THEN
- INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk)
- SELECT vSelf, itemPackingTypeFk
- FROM tSaleGroup
- WHERE itemPackingTypeFk IS NOT NULL;
- ELSE
- OPEN vSaleGroup;
- FETCH vSaleGroup INTO vItemPackingTypeFk;
+ SELECT id INTO vTicketFk
+ FROM ticket t
+ WHERE t.id = vNewTicketFk
+ FOR UPDATE;
- INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk)
- VALUES(vSelf, vItemPackingTypeFk);
+ UPDATE tSalesToMove
+ SET ticketFk = vNewTicketFk
+ WHERE itemPackingTypeFk = vCurrentPackingType;
- l: LOOP
- SET vDone = FALSE;
- FETCH vSaleGroup INTO vItemPackingTypeFk;
+ IF vCurrentPackingType = vDefaultPackingType THEN
+ INSERT INTO tSalesToMove (ticketFk, saleFk, itemPackingTypeFk)
+ SELECT vNewTicketFk, s.id, i.itemPackingTypeFk
+ FROM sale s
+ JOIN item i ON i.id = s.itemFk
+ WHERE s.ticketFk = vSelf
+ AND i.itemPackingTypeFk IS NULL;
+ END IF;
- IF vDone THEN
- LEAVE l;
- END IF;
+ END LOOP;
+ CLOSE vItemPackingTypes;
- CALL ticket_Clone(vSelf, vNewTicketFk);
+ UPDATE sale s
+ JOIN tSalesToMove t ON t.saleFk = s.id
+ SET s.ticketFk = t.ticketFk;
- INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk)
- VALUES(vNewTicketFk, vItemPackingTypeFk);
- END LOOP;
-
- CLOSE vSaleGroup;
-
- SELECT s.id
- FROM sale s
- JOIN tSale ts ON ts.id = s.id
- JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk
- FOR UPDATE;
-
- UPDATE sale s
- JOIN tSale ts ON ts.id = s.id
- JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk
- SET s.ticketFk = t.ticketFk;
-
- SELECT itemPackingTypeFk INTO vItemPackingTypeFk
- FROM tSaleGroup sg
- WHERE sg.itemPackingTypeFk IS NOT NULL
- ORDER BY sg.itemPackingTypeFk
- LIMIT 1;
-
- UPDATE sale s
- JOIN tSale ts ON ts.id = s.id
- JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = vItemPackingTypeFk
- SET s.ticketFk = t.ticketFk
- WHERE ts.itemPackingTypeFk IS NULL;
- END CASE;
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT
+ ENGINE=MEMORY
+ SELECT s.ticketFk, MAX(i.itemPackingTypeFk) itemPackingTypeFk
+ FROM sale s
+ JOIN item i ON i.id = s.itemFk
+ WHERE s.ticketFk = vSelf
+ GROUP BY s.ticketFk
+ UNION
+ SELECT ticketFk, MAX(itemPackingTypeFk)
+ FROM tSalesToMove
+ GROUP BY ticketFk;
COMMIT;
- DROP TEMPORARY TABLE
- tSale,
- tSaleGroup;
+ DROP TEMPORARY TABLE tSalesToMove;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -77989,7 +77644,7 @@ BEGIN
JOIN vn.entry e ON e.travelFk = tr.id
JOIN vn.buy b ON b.entryFk = e.id
WHERE tr.landed BETWEEN vFromDated AND vToDated
- AND e.isRaid = FALSE
+ AND NOT tr.isRaid
AND tr.warehouseInFk = vWarehouseFk
GROUP BY tr.landed , a.name ;
END ;;
@@ -78073,6 +77728,36 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+/*!50003 DROP PROCEDURE IF EXISTS `travel_checkRaid` */;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+DELIMITER ;;
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `travel_checkRaid`(
+ vIsRaid BOOL,
+ vDaysInForward INT
+)
+BEGIN
+/**
+ * Check if the values of isRaid and daysInforward are correct
+ *
+ * @param vIsRaid idRaid value
+ * @param vDaysInForward daysInForward value
+ */
+ IF (NOT vIsRaid AND vDaysInForward IS NOT NULL) OR (vIsRaid AND vDaysInForward IS NULL) THEN
+ CALL util.throw('The raid information is not correct');
+ END IF;
+END ;;
+DELIMITER ;
+/*!50003 SET sql_mode = @saved_sql_mode */ ;
+/*!50003 SET character_set_client = @saved_cs_client */ ;
+/*!50003 SET character_set_results = @saved_cs_results */ ;
+/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `travel_checkWarehouseIsFeedStock` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -78235,7 +77920,7 @@ BEGIN
END IF;
CALL entry_cloneHeader(vAuxEntryFk, vNewEntryFk, vNewTravelFk);
- CALL entry_copyBuys(vAuxEntryFk, vNewEntryFk);
+ CALL entry_copyBuys(vAuxEntryFk, vNewEntryFk);
SELECT evaNotes INTO vEvaNotes
FROM entry
@@ -78244,6 +77929,8 @@ BEGIN
UPDATE entry
SET evaNotes = vEvaNotes
WHERE id = vNewEntryFk;
+
+ CALL buy_recalcPricesByEntry(vNewEntryFk);
END LOOP;
SET @isModeInventory = FALSE;
@@ -78421,73 +78108,70 @@ DELIMITER ;
DELIMITER ;;
CREATE DEFINER=`vn`@`localhost` PROCEDURE `travel_moveRaids`()
BEGIN
-
-/*
- * Desplaza al dia siguiente los travels que contengan redadas y avisa a los compradores
- *
+/**
+ * Desplaza los travels en el futuro y avisa a los compradores
+ *
*/
DECLARE vDone BOOL DEFAULT FALSE;
- DECLARE vWorkerName VARCHAR(50);
- DECLARE vRaid TEXT;
- DECLARE vWorker VARCHAR(50) DEFAULT '';
+ DECLARE vBuyerEmail VARCHAR(40);
+ DECLARE vTravelLink TEXT;
DECLARE vMailBody TEXT DEFAULT '';
DECLARE vCur CURSOR FOR
- SELECT GROUP_CONCAT( DISTINCT CONCAT('https://salix.verdnatura.es/#!/travel/', ttr.id, '/summary ') ORDER BY ttr.id SEPARATOR '\n\r'),
- u.name
- FROM tmp.travel ttr
- JOIN entry e ON e.travelFk = ttr.id
+ SELECT GROUP_CONCAT(DISTINCT
+ CONCAT('https://salix.verdnatura.es/#!/travel/',
+ ttm.travelFk,
+ '/summary ')
+ ORDER BY ttm.travelFk SEPARATOR '\n\r') travelLink,
+ CONCAT(u.name, '@verdnatura.es') buyerEmail
+ FROM tTravelToMove ttm
+ JOIN entry e ON e.travelFk = ttm.travelFk
JOIN buy b ON b.entryFk = e.id
JOIN item i ON i.id = b.itemFk
JOIN itemType it ON it.id = i.typeFk
JOIN account.user u ON u.id = it.workerFk
GROUP BY u.name;
- DECLARE CONTINUE HANDLER FOR NOT FOUND
- SET vDone = TRUE;
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.travel;
- CREATE TEMPORARY TABLE tmp.travel
- SELECT tr.id,tr.landed
- FROM travel tr
- JOIN entry e ON e.travelFk = tr.id
- WHERE tr.landed = util.tomorrow()
- AND e.isRaid
- GROUP BY tr.id;
+
+ CREATE OR REPLACE TEMPORARY TABLE tTravelToMove
+ SELECT id travelFk,
+ util.VN_CURDATE() + INTERVAL daysInForward DAY newLanded
+ FROM travel
+ WHERE isRaid
+ AND daysInForward;
START TRANSACTION;
UPDATE travel tr
- JOIN tmp.travel ttr ON ttr.id = tr.id
- SET tr.landed = TIMESTAMPADD(DAY, 1, tr.landed);
+ JOIN tTravelToMove ttm ON ttm.travelFk = tr.id
+ SET tr.landed = ttm.newLanded;
OPEN vCur;
l: LOOP
SET vDone = FALSE;
- FETCH vCur INTO vRaid, vWorkerName;
+ FETCH vCur INTO vTravelLink, vBuyerEmail;
IF vDone THEN
LEAVE l;
END IF;
- CALL `vn`.`mail_insert`(CONCAT(vWorkerName, '@verdnatura.es'),
- 'noreply@verdnatura.es',
- 'Cambio de fecha en Redadas',
- CONCAT('Se ha movido las siguientes redadas: \n\r ', vRaid)
- );
-
+ CALL `vn`.`mail_insert`(
+ vBuyerEmail,
+ 'noreply@verdnatura.es',
+ 'Cambio de fecha en Redadas',
+ CONCAT('Se ha movido los siguientes travels: \n\r ', vTravelLink));
END LOOP;
CLOSE vCur;
COMMIT;
- DROP TEMPORARY TABLE tmp.travel;
-
+ DROP TEMPORARY TABLE tTravelToMove;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -79946,187 +79630,6 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-/*!50003 DROP PROCEDURE IF EXISTS `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_unicode_ci */ ;
-DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` 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 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;
- DECLARE vTo VARCHAR(50) DEFAULT NULL;
- DECLARE vUserName VARCHAR(50) DEFAULT NULL;
- DECLARE vBody VARCHAR(255) DEFAULT NULL;
-
- SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax
- INTO vDayBreak, vWeekBreak, vWeekScope, vDayWorkMax, vDayStayMax
- FROM workerTimeControlParams;
-
- SELECT MAX(timed) INTO vLastIn
- FROM workerTimeControl
- WHERE userFk = vUserFk
- AND direction = 'in';
-
- SELECT MAX(timed) INTO vLastOut
- FROM workerTimeControl
- WHERE userFk = vUserFk
- AND direction = 'out';
-
- SELECT CONCAT(u.name,'@verdnatura.es') INTO vTo
- FROM account.user u
- WHERE u.id = (SELECT bossFk FROM worker WHERE id = vUserFk);
-
- SELECT CONCAT(firstName,' ',lastName) INTO vUserName
- FROM worker w
- WHERE w.id = vUserFk;
-
-
- IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastIn) > vDayStayMax THEN -- NUEVA JORNADA
-
- -- VERIFICAR DESCANSO DIARIO
- IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN
- SELECT "Descansos 12 h" AS problem;
- -- ENVIAMOS CORREO AL BOSSFK
- SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 12 h") INTO vBody;
- CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
- END IF;
-
- -- VERIFICAR FICHADAS IMPARES DEL ÚLTIMO DÍA QUE SE FICHÓ
- IF (SELECT MOD(COUNT(*),2) -- <>0
- FROM workerTimeControl
- WHERE userFk = vUserFk
- AND timed >= vLastIn
- ) THEN
- SELECT "Dias con fichadas impares" AS problem;
- -- ENVIAMOS CORREO AL BOSSFK
- SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Dias con fichadas impares") INTO vBody;
- CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
- END IF;
-
- -- VERIFICAR VACACIONES
- SELECT at2.name INTO vCalendarStateType
- FROM calendar c
- JOIN business b ON b.id = c.businessFk
- JOIN absenceType at2 ON at2.id = c.dayOffTypeFk
- WHERE c.dated = util.VN_CURDATE()
- AND at2.isAllowedToWork = FALSE
- AND b.workerFk = vUserFk
- LIMIT 1;
-
- IF(LENGTH(vCalendarStateType)) THEN
- SELECT vCalendarStateType AS problem;
- -- ENVIAMOS CORREO AL BOSSFK
- SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Vacaciones") INTO vBody;
- CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
-
- END IF;
-
- -- VERIFICAR CONTRATO EN VIGOR
- IF (SELECT COUNT(*)
- FROM business b
- WHERE b.workerFk = vUserFk
- AND b.started <= vDated
- AND IFNULL(b.ended, vDated) >= vDated
- ) = 0 THEN
- SELECT "No hay un contrato en vigor" AS problem;
- -- ENVIAMOS CORREO AL BOSSFK
- SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"No hay un contrato en vigor") INTO vBody;
- CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
-
- END IF;
-
- -- VERIFICAR DESCANSO SEMANAL
- SET @vHasBreakWeek:= FALSE;
- SET @vLastTimed:= UNIX_TIMESTAMP((util.VN_NOW() - INTERVAL vWeekScope SECOND));
-
- DROP TEMPORARY TABLE IF EXISTS tmp.trash;
- CREATE TEMPORARY TABLE tmp.trash
- SELECT IF(vWeekBreak-(UNIX_TIMESTAMP(timed)-@vLastTimed) <= 0, @vHasBreakWeek:=TRUE, TRUE) alias,
- @vLastTimed:= UNIX_TIMESTAMP(timed)
- FROM workerTimeControl
- WHERE timed>= (util.VN_NOW() - INTERVAL vWeekScope SECOND)
- AND userFk= vUserFk
- AND direction IN ('in','out')
- ORDER BY timed ASC;
-
- IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA
- SELECT "Descansos 36 h" AS problem;
- -- ENVIAMOS CORREO AL BOSSFK
- SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 36 h") INTO vBody;
- CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
- END IF;
-
- DROP TEMPORARY TABLE tmp.trash;
-
- ELSE -- DIA ACTUAL
-
- -- VERIFICA QUE EL TIEMPO EFECTIVO NO SUPERE EL MÁXIMO
- SELECT IFNULL(SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))),0) - IF( MOD(COUNT(*),2), UNIX_TIMESTAMP(util.VN_NOW()), 0) INTO vTimedWorked
- FROM workerTimeControl wtc
- WHERE userFk = vUserFk
- AND timed >= vLastIn
- ORDER BY timed;
-
- IF vTimedWorked > vDayWorkMax THEN
- SELECT "Jornadas" AS problem;
- -- ENVIAMOS CORREO AL BOSSFK
- SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Jornadas") INTO vBody;
- CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
- END IF;
-
- END IF;
-
- -- VERIFICAR DEPARTAMENTO
- /* IF vTabletFk IS NOT NULL THEN
- SELECT wtcu.departmentFk INTO vDepartmentFk
- FROM workerTimeControlUserInfo wtcu
- WHERE wtcu.userFk = vUserFk;
- IF (SELECT COUNT(td.tabletFk)
- FROM tabletDepartment td
- WHERE td.tabletFk = vTabletFk AND td.departmentFk = vDepartmentFk
- ) = 0 THEN
- SELECT "No perteneces a este departamento." AS problem;
- -- ENVIAMOS CORREO AL BOSSFK
- SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No perteneces a este departamento.") INTO vBody;
- CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
- 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_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_checkBreak` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
@@ -81322,7 +80825,9 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
-CREATE DEFINER=`vn`@`localhost` PROCEDURE `worker_getHierarchy`(vUserFk INT)
+CREATE DEFINER=`vn`@`localhost` PROCEDURE `worker_getHierarchy`(
+ vUserFk INT
+)
BEGIN
/**
* Retorna una tabla temporal con los trabajadores que tiene
@@ -81335,15 +80840,16 @@ BEGIN
(PRIMARY KEY (workerFk))
ENGINE = MEMORY
WITH RECURSIVE workerHierarchy AS (
- SELECT id workerFk, bossFk, 0 depth
+ SELECT id workerFk, bossFk, 0 `depth`, CAST(id AS CHAR(255)) `path`
FROM vn.worker
WHERE id = vUserFk
UNION ALL
- SELECT w.id, w.bossFk, wh.depth + 1
+ SELECT w.id, w.bossFk, wh.`depth` + 1, CONCAT(wh.`path`, ',', w.id)
FROM vn.worker w
JOIN workerHierarchy wh ON w.bossFk = wh.workerFk
+ WHERE NOT FIND_IN_SET(w.id, wh.`path`)
)
- SELECT *
+ SELECT *
FROM workerHierarchy
ORDER BY depth, workerFk;
END ;;
@@ -81438,6 +80944,8 @@ BEGIN
SET businessFk = vNewBusinessFk
WHERE id = vSelf;
+ CALL queueMember_updateQueue(vNewBusinessFk);
+
IF vOldBusinessFk IS NULL THEN
CALL account.account_enable(vSelf);
@@ -83278,7 +82786,6 @@ SET character_set_client = utf8;
1 AS `send_mail`,
1 AS `tpv`,
1 AS `code`,
- 1 AS `show_AgencyName`,
1 AS `isRiskFree` */;
SET character_set_client = @saved_cs_client;
@@ -83331,7 +82838,6 @@ SET character_set_client = utf8;
1 AS `hasKgPrice`,
1 AS `Equivalente`,
1 AS `Imprimir`,
- 1 AS `Familia__`,
1 AS `do_photo`,
1 AS `odbc_date`,
1 AS `isFloramondo`,
@@ -83450,7 +82956,6 @@ SET character_set_client = utf8;
1 AS `credito`,
1 AS `Id_Pais`,
1 AS `activo`,
- 1 AS `gestdoc_id`,
1 AS `calidad`,
1 AS `pay_met_id`,
1 AS `created`,
@@ -83530,21 +83035,6 @@ SET character_set_client = utf8;
1 AS `itemOriginalFk` */;
SET character_set_client = @saved_cs_client;
---
--- Temporary table structure for view `Compres_mark`
---
-
-DROP TABLE IF EXISTS `Compres_mark`;
-/*!50001 DROP VIEW IF EXISTS `Compres_mark`*/;
-SET @saved_cs_client = @@character_set_client;
-SET character_set_client = utf8;
-/*!50001 CREATE VIEW `Compres_mark` AS SELECT
- 1 AS `Id_Compra`,
- 1 AS `comment`,
- 1 AS `mark`,
- 1 AS `odbc_date` */;
-SET character_set_client = @saved_cs_client;
-
--
-- Temporary table structure for view `Consignatarios`
--
@@ -83596,7 +83086,8 @@ SET character_set_client = utf8;
1 AS `Suben`,
1 AS `Base`,
1 AS `box`,
- 1 AS `costeRetorno` */;
+ 1 AS `costeRetorno`,
+ 1 AS `isActive` */;
SET character_set_client = @saved_cs_client;
--
@@ -83630,7 +83121,6 @@ SET character_set_client = utf8;
1 AS `Inventario`,
1 AS `Confirmada`,
1 AS `Pedida`,
- 1 AS `Redada`,
1 AS `comision`,
1 AS `odbc_date`,
1 AS `Notas_Eva`,
@@ -83650,18 +83140,6 @@ SET character_set_client = utf8;
1 AS `typeFk` */;
SET character_set_client = @saved_cs_client;
---
--- Temporary table structure for view `Entradas_Auto`
---
-
-DROP TABLE IF EXISTS `Entradas_Auto`;
-/*!50001 DROP VIEW IF EXISTS `Entradas_Auto`*/;
-SET @saved_cs_client = @@character_set_client;
-SET character_set_client = utf8;
-/*!50001 CREATE VIEW `Entradas_Auto` AS SELECT
- 1 AS `Id_Entrada` */;
-SET character_set_client = @saved_cs_client;
-
--
-- Temporary table structure for view `Entradas_orden`
--
@@ -85067,7 +84545,8 @@ SET character_set_client = utf8;
1 AS `Inventario`,
1 AS `Confirmada`,
1 AS `Pedida`,
- 1 AS `Redada`,
+ 1 AS `isRaid`,
+ 1 AS `daysInForward`,
1 AS `notas`,
1 AS `Id_Proveedor`,
1 AS `shipment`,
@@ -85619,7 +85098,6 @@ SET character_set_client = utf8;
1 AS `order`,
1 AS `alert_level`,
1 AS `code`,
- 1 AS `sectorProdPriority`,
1 AS `nextStateFk`,
1 AS `isPreviousPreparable`,
1 AS `isPicked` */;
@@ -85803,7 +85281,9 @@ SET character_set_client = utf8;
1 AS `cargoSupplierFk`,
1 AS `totalEntries`,
1 AS `appointment`,
- 1 AS `awbFk` */;
+ 1 AS `awbFk`,
+ 1 AS `isRaid`,
+ 1 AS `daysInForward` */;
SET character_set_client = @saved_cs_client;
--
@@ -85855,7 +85335,6 @@ SET character_set_client = utf8;
1 AS `Id_Proveedor`,
1 AS `Fecha`,
1 AS `Confirmada`,
- 1 AS `Redada`,
1 AS `empresa_id`,
1 AS `travel_id`,
1 AS `Pedida`,
@@ -86019,7 +85498,7 @@ USE `account`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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` = `myUser_getName`() */
+/*!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` from `user` `u` where `u`.`name` = `myUser_getName`() */
/*!50002 WITH CASCADED CHECK OPTION */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
@@ -87562,7 +87041,7 @@ USE `vn`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`vn`@`localhost` SQL SECURITY DEFINER */
-/*!50001 VIEW `expeditionPallet_Print` AS select `rs2`.`description` AS `truck`,`t`.`routeFk` AS `routeFk`,`r`.`description` AS `zone`,count(`es`.`id`) AS `eti`,`ep`.`id` AS `palletFk`,`rs`.`id` <=> `rm`.`roadmapStopFk` AS `isMatch`,`t`.`warehouseFk` AS `warehouseFk`,if(`r`.`created` > `util`.`VN_CURDATE`() + interval 1 day,ucase(dayname(`r`.`created`)),NULL) AS `nombreDia` from (((((((`roadmapStop` `rs` join `expeditionPallet` `ep` on(`ep`.`truckFk` = `rs`.`id`)) join `expeditionScan` `es` on(`es`.`palletFk` = `ep`.`id`)) join `expedition` `e` on(`e`.`id` = `es`.`expeditionFk`)) join `ticket` `t` on(`t`.`id` = `e`.`ticketFk`)) join `route` `r` on(`r`.`id` = `t`.`routeFk`)) left join `routesMonitor` `rm` on(`rm`.`routeFk` = `r`.`id`)) left join `roadmapStop` `rs2` on(`rs2`.`id` = `rm`.`roadmapStopFk`)) group by `ep`.`id`,`t`.`routeFk` */;
+/*!50001 VIEW `expeditionPallet_Print` AS select `rs2`.`description` AS `truck`,`t`.`routeFk` AS `routeFk`,`r`.`description` AS `zone`,count(`es`.`id`) AS `eti`,`ep`.`id` AS `palletFk`,`rs`.`id` <=> `rm`.`roadmapStopFk` AS `isMatch`,`t`.`warehouseFk` AS `warehouseFk`,if(`r`.`dated` > `util`.`VN_CURDATE`() + interval 1 day,ucase(dayname(`r`.`dated`)),NULL) AS `nombreDia` from (((((((`roadmapStop` `rs` join `expeditionPallet` `ep` on(`ep`.`truckFk` = `rs`.`id`)) join `expeditionScan` `es` on(`es`.`palletFk` = `ep`.`id`)) join `expedition` `e` on(`e`.`id` = `es`.`expeditionFk`)) join `ticket` `t` on(`t`.`id` = `e`.`ticketFk`)) join `route` `r` on(`r`.`id` = `t`.`routeFk`)) left join `routesMonitor` `rm` on(`rm`.`routeFk` = `r`.`id`)) left join `roadmapStop` `rs2` on(`rs2`.`id` = `rm`.`roadmapStopFk`)) group by `ep`.`id`,`t`.`routeFk` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
@@ -87580,7 +87059,7 @@ USE `vn`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`vn`@`localhost` SQL SECURITY DEFINER */
-/*!50001 VIEW `expeditionRoute_Monitor` AS select `r`.`id` AS `routeFk`,count(distinct if(`e`.`id` is null,`t`.`id`,NULL)) AS `tickets`,count(distinct `e`.`id`) AS `expeditions`,count(distinct `es`.`id`) AS `scanned`,max(`e`.`created`) AS `lastPacked`,`r`.`created` AS `created` from (((((`route` `r` left join `routesMonitor` `rm` on(`r`.`id` = `rm`.`routeFk`)) left join `roadmapStop` `rs` on(`rs`.`id` = `rm`.`roadmapStopFk`)) join `ticket` `t` on(`t`.`routeFk` = `r`.`id`)) left join `expedition` `e` on(`e`.`ticketFk` = `t`.`id`)) left join `expeditionScan` `es` on(`es`.`expeditionFk` = `e`.`id`)) where `r`.`created` >= `util`.`yesterday`() group by `r`.`id` */;
+/*!50001 VIEW `expeditionRoute_Monitor` AS select `r`.`id` AS `routeFk`,count(distinct if(`e`.`id` is null,`t`.`id`,NULL)) AS `tickets`,count(distinct `e`.`id`) AS `expeditions`,count(distinct `es`.`id`) AS `scanned`,max(`e`.`created`) AS `lastPacked`,`r`.`dated` AS `created` from (((((`route` `r` left join `routesMonitor` `rm` on(`r`.`id` = `rm`.`routeFk`)) left join `roadmapStop` `rs` on(`rs`.`id` = `rm`.`roadmapStopFk`)) join `ticket` `t` on(`t`.`routeFk` = `r`.`id`)) left join `expedition` `e` on(`e`.`ticketFk` = `t`.`id`)) left join `expeditionScan` `es` on(`es`.`expeditionFk` = `e`.`id`)) where `r`.`dated` >= `util`.`yesterday`() group by `r`.`id` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
@@ -87832,7 +87311,7 @@ USE `vn`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`vn`@`localhost` 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`.`isExcludedFromAvailable` = 0 and `b`.`quantity` <> 0 */;
+/*!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`,`t`.`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`.`isExcludedFromAvailable` = 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 */;
@@ -87850,7 +87329,7 @@ USE `vn`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`vn`@`localhost` 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`.`isExcludedFromAvailable` = 0 and `e`.`isRaid` = 0 and `b`.`quantity` <> 0 */;
+/*!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`.`isExcludedFromAvailable` = 0 and `t`.`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 */;
@@ -87940,7 +87419,7 @@ USE `vn`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`vn`@`localhost` 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`,`t`.`warehouseFk` AS `warehouseFk` from (((((((((`sale` `s` join `ticket` `t` on(`t`.`id` = `s`.`ticketFk`)) join `agencyMode` `am` on(`am`.`id` = `t`.`agencyModeFk`)) join `ticketStateToday` `tst` on(`tst`.`ticketFk` = `t`.`id`)) join `state` `st` on(`st`.`id` = `tst`.`state`)) join `item` `i` on(`i`.`id` = `s`.`itemFk`)) join `itemShelvingStock` `stock` on(`stock`.`itemFk` = `i`.`id`)) left join `saleTracking` `stk` on(`stk`.`saleFk` = `s`.`id`)) left join `zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `saleVolume` `sv` on(`sv`.`saleFk` = `s`.`id`)) where `t`.`shipped` between `util`.`yesterday`() and `util`.`dayend`(`util`.`VN_CURDATE`()) and `stk`.`id` is null and `stock`.`visible` > 0 and `stk`.`saleFk` is null and `st`.`isPreviousPreparable` <> 0 */;
+/*!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`,`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`,`t`.`warehouseFk` AS `warehouseFk` from (((((((((`sale` `s` join `ticket` `t` on(`t`.`id` = `s`.`ticketFk`)) join `agencyMode` `am` on(`am`.`id` = `t`.`agencyModeFk`)) join `ticketStateToday` `tst` on(`tst`.`ticketFk` = `t`.`id`)) join `state` `st` on(`st`.`id` = `tst`.`state`)) join `item` `i` on(`i`.`id` = `s`.`itemFk`)) join `itemShelvingStock` `stock` on(`stock`.`itemFk` = `i`.`id`)) left join `saleTracking` `stk` on(`stk`.`saleFk` = `s`.`id`)) left join `zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `saleVolume` `sv` on(`sv`.`saleFk` = `s`.`id`)) where `t`.`shipped` between `util`.`yesterday`() and `util`.`dayend`(`util`.`VN_CURDATE`()) and `stk`.`id` is null and `stock`.`visible` > 0 and `stk`.`saleFk` is null and `st`.`isPreviousPreparable` <> 0 */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
@@ -87958,7 +87437,7 @@ USE `vn`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`vn`@`localhost` 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`,`pk`.`sectorFk` AS `sectorFk` 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 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`,`pk`.`sectorFk` AS `sectorFk` from (((`itemShelving` `ish` join `shelving` `sh` on(`sh`.`id` = `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 */;
@@ -87976,7 +87455,7 @@ USE `vn`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`vn`@`localhost` SQL SECURITY DEFINER */
-/*!50001 VIEW `itemShelvingPlacementSupplyStock` AS select `ish`.`id` AS `itemShelvingFk`,`ish`.`itemFk` AS `itemFk`,`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`)) group by `ish`.`id` */;
+/*!50001 VIEW `itemShelvingPlacementSupplyStock` AS select `ish`.`id` AS `itemShelvingFk`,`ish`.`itemFk` AS `itemFk`,`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`.`id` = `ish`.`shelvingFk`)) left join `parking` `p` on(`p`.`id` = `sh`.`parkingFk`)) join `item` `i` on(`i`.`id` = `ish`.`itemFk`)) 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 */;
@@ -87994,7 +87473,7 @@ USE `vn`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`vn`@`localhost` 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 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`.`id` = `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 */;
@@ -88012,7 +87491,7 @@ USE `vn`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`vn`@`localhost` 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`,0 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`,`st`.`code` = 'previousPrepared' AS `isPreviousPrepared` 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 `sectorType` `st` on(`st`.`id` = `s`.`typeFk`)) where `ish`.`visible` <> 0 and `p`.`sectorFk` <> 0 group by `ish`.`itemFk`,`p`.`sectorFk` */;
+/*!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`,0 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`,`st`.`code` = 'previousPrepared' AS `isPreviousPrepared` from ((((`itemShelving` `ish` left join `shelving` `sh` on(`sh`.`id` = `ish`.`shelvingFk`)) left join `parking` `p` on(`p`.`id` = `sh`.`parkingFk`)) left join `sector` `s` on(`s`.`id` = `p`.`sectorFk`)) left join `sectorType` `st` on(`st`.`id` = `s`.`typeFk`)) where `ish`.`visible` <> 0 and `p`.`sectorFk` <> 0 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 */;
@@ -88030,7 +87509,7 @@ USE `vn`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`vn`@`localhost` 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 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`.`id` = `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 */;
@@ -88192,7 +87671,7 @@ USE `vn`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`vn`@`localhost` SQL SECURITY DEFINER */
-/*!50001 VIEW `lastPurchases` AS select `tr`.`landed` AS `landed`,`w`.`id` AS `warehouseFk`,`w`.`name` AS `warehouse`,`i`.`longName` AS `longName`,`i`.`subName` AS `subName`,`e`.`id` AS `entryFk`,`b`.`stickers` AS `stickers`,`b`.`packing` AS `packing`,`e`.`invoiceNumber` AS `ref`,`b`.`itemFk` AS `itemFk`,`ek`.`pro` AS `pro`,`ek`.`ref` AS `ektRef`,`ek`.`agj` AS `agj` from (((((`vn`.`buy` `b` join `vn`.`entry` `e` on(`e`.`id` = `b`.`entryFk`)) join `vn`.`item` `i` on(`i`.`id` = `b`.`itemFk`)) join `vn`.`travel` `tr` on(`tr`.`id` = `e`.`travelFk`)) join `vn`.`warehouse` `w` on(`w`.`id` = `tr`.`warehouseInFk`)) left join `edi`.`ekt` `ek` on(`ek`.`id` = `b`.`ektFk`)) where `tr`.`landed` between `util`.`yesterday`() and `util`.`tomorrow`() and `e`.`isRaid` = 0 and `b`.`stickers` > 0 */;
+/*!50001 VIEW `lastPurchases` AS select `tr`.`landed` AS `landed`,`w`.`id` AS `warehouseFk`,`w`.`name` AS `warehouse`,`i`.`longName` AS `longName`,`i`.`subName` AS `subName`,`e`.`id` AS `entryFk`,`b`.`stickers` AS `stickers`,`b`.`packing` AS `packing`,`e`.`invoiceNumber` AS `ref`,`b`.`itemFk` AS `itemFk`,`ek`.`pro` AS `pro`,`ek`.`ref` AS `ektRef`,`ek`.`agj` AS `agj` from (((((`vn`.`buy` `b` join `vn`.`entry` `e` on(`e`.`id` = `b`.`entryFk`)) join `vn`.`item` `i` on(`i`.`id` = `b`.`itemFk`)) join `vn`.`travel` `tr` on(`tr`.`id` = `e`.`travelFk`)) join `vn`.`warehouse` `w` on(`w`.`id` = `tr`.`warehouseInFk`)) left join `edi`.`ekt` `ek` on(`ek`.`id` = `b`.`ektFk`)) where `tr`.`landed` between `util`.`yesterday`() and `util`.`tomorrow`() and `tr`.`isRaid` = 0 and `b`.`stickers` > 0 */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
@@ -88840,7 +88319,7 @@ USE `vn`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`vn`@`localhost` SQL SECURITY DEFINER */
-/*!50001 VIEW `ticketStateToday` AS select `ts`.`ticketFk` AS `ticketFk`,`ts`.`state` AS `state`,`ts`.`productionOrder` AS `productionOrder`,`ts`.`alertLevel` AS `alertLevel`,`ts`.`userFk` AS `userFk`,`ts`.`code` AS `code`,`ts`.`updated` AS `updated`,`ts`.`isPicked` AS `isPicked` from (`ticketState` `ts` join `ticket` `t` on(`t`.`id` = `ts`.`ticketFk`)) where `t`.`shipped` between `util`.`VN_CURDATE`() and `MIDNIGHT`(`util`.`VN_CURDATE`()) */;
+/*!50001 VIEW `ticketStateToday` AS select `ts`.`ticketFk` AS `ticketFk`,`ts`.`state` AS `state`,`ts`.`productionOrder` AS `productionOrder`,`ts`.`alertLevel` AS `alertLevel`,`ts`.`userFk` AS `userFk`,`ts`.`code` AS `code`,`ts`.`updated` AS `updated`,`ts`.`isPicked` AS `isPicked` from (`ticketState` `ts` join `ticket` `t` on(`t`.`id` = `ts`.`ticketFk`)) where `t`.`shipped` between `util`.`VN_CURDATE`() and `util`.`midnight`() */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
@@ -89074,7 +88553,7 @@ USE `vn`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`vn`@`localhost` SQL SECURITY DEFINER */
-/*!50001 VIEW `workerWithoutTractor` AS select `c`.`workerFk` AS `workerFk`,`cl`.`name` AS `Trabajador`,count(distinct `c`.`id`) AS `Colecciones`,max(`c`.`created`) AS `created` from ((`collection` `c` join `client` `cl` on(`cl`.`id` = `c`.`workerFk`)) left join `machineWorker` `mw` on(`mw`.`workerFk` = `c`.`workerFk` and `mw`.`inTimed` > `util`.`VN_CURDATE`())) where `c`.`created` > `util`.`VN_CURDATE`() and `mw`.`workerFk` is null group by `c`.`workerFk` */;
+/*!50001 VIEW `workerWithoutTractor` AS select `c`.`workerFk` AS `workerFk`,`cl`.`name` AS `Trabajador`,count(distinct `c`.`id`) AS `Colecciones`,max(`c`.`created`) AS `created` from ((`collection` `c` join `client` `cl` on(`cl`.`id` = `c`.`workerFk`)) join `operator` `o` on(`o`.`workerFk` = `c`.`workerFk`)) where `c`.`created` > `util`.`VN_CURDATE`() and `o`.`machineFk` is null group by `c`.`workerFk` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
@@ -89116,7 +88595,7 @@ USE `vn2008`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
-/*!50001 VIEW `Agencias` AS select `am`.`id` AS `Id_Agencia`,`am`.`name` AS `Agencia`,`am`.`description` AS `description`,`am`.`deliveryMethodFk` AS `Vista`,`am`.`m3` AS `m3`,`am`.`web` AS `web`,`am`.`agencyFk` AS `agency_id`,`am`.`inflation` AS `inflacion`,`am`.`isVolumetric` AS `is_volumetric`,`am`.`reportMail` AS `send_mail`,`am`.`isActive` AS `tpv`,`am`.`code` AS `code`,`am`.`showAgencyName` AS `show_AgencyName`,`am`.`isRiskFree` AS `isRiskFree` from `vn`.`agencyMode` `am` */;
+/*!50001 VIEW `Agencias` AS select `am`.`id` AS `Id_Agencia`,`am`.`name` AS `Agencia`,`am`.`description` AS `description`,`am`.`deliveryMethodFk` AS `Vista`,`am`.`m3` AS `m3`,`am`.`web` AS `web`,`am`.`agencyFk` AS `agency_id`,`am`.`inflation` AS `inflacion`,`am`.`isVolumetric` AS `is_volumetric`,`am`.`reportMail` AS `send_mail`,`am`.`isActive` AS `tpv`,`am`.`code` AS `code`,`am`.`isRiskFree` AS `isRiskFree` from `vn`.`agencyMode` `am` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
@@ -89134,7 +88613,7 @@ USE `vn2008`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
-/*!50001 VIEW `Articles` AS select `i`.`id` AS `Id_Article`,`i`.`name` AS `Article`,`i`.`typeFk` AS `tipo_id`,`i`.`size` AS `Medida`,`i`.`inkFk` AS `Color`,`i`.`category` AS `Categoria`,`i`.`stems` AS `Tallos`,`i`.`originFk` AS `id_origen`,`i`.`description` AS `description`,`i`.`producerFk` AS `producer_id`,`i`.`intrastatFk` AS `Codintrastat`,`i`.`box` AS `caja`,`i`.`expenseFk` AS `expenseFk`,`i`.`comment` AS `comments`,`i`.`relevancy` AS `relevancy`,`i`.`image` AS `Foto`,`i`.`generic` AS `generic`,`i`.`density` AS `density`,`i`.`minPrice` AS `PVP`,`i`.`hasMinPrice` AS `Min`,`i`.`isActive` AS `isActive`,`i`.`longName` AS `longName`,`i`.`subName` AS `subName`,`i`.`tag5` AS `tag5`,`i`.`value5` AS `value5`,`i`.`tag6` AS `tag6`,`i`.`value6` AS `value6`,`i`.`tag7` AS `tag7`,`i`.`value7` AS `value7`,`i`.`tag8` AS `tag8`,`i`.`value8` AS `value8`,`i`.`tag9` AS `tag9`,`i`.`value9` AS `value9`,`i`.`tag10` AS `tag10`,`i`.`value10` AS `value10`,`i`.`minimum` AS `minimum`,`i`.`upToDown` AS `upToDown`,`i`.`hasKgPrice` AS `hasKgPrice`,`i`.`equivalent` AS `Equivalente`,`i`.`isToPrint` AS `Imprimir`,`i`.`family` AS `Familia__`,`i`.`doPhoto` AS `do_photo`,`i`.`created` AS `odbc_date`,`i`.`isFloramondo` AS `isFloramondo`,`i`.`supplyResponseFk` AS `supplyResponseFk`,`i`.`stemMultiplier` AS `stemMultiplier`,`i`.`itemPackingTypeFk` AS `itemPackingTypeFk`,`i`.`packingOut` AS `packingOut` from `vn`.`item` `i` */;
+/*!50001 VIEW `Articles` AS select `i`.`id` AS `Id_Article`,`i`.`name` AS `Article`,`i`.`typeFk` AS `tipo_id`,`i`.`size` AS `Medida`,`i`.`inkFk` AS `Color`,`i`.`category` AS `Categoria`,`i`.`stems` AS `Tallos`,`i`.`originFk` AS `id_origen`,`i`.`description` AS `description`,`i`.`producerFk` AS `producer_id`,`i`.`intrastatFk` AS `Codintrastat`,`i`.`box` AS `caja`,`i`.`expenseFk` AS `expenseFk`,`i`.`comment` AS `comments`,`i`.`relevancy` AS `relevancy`,`i`.`image` AS `Foto`,`i`.`generic` AS `generic`,`i`.`density` AS `density`,`i`.`minPrice` AS `PVP`,`i`.`hasMinPrice` AS `Min`,`i`.`isActive` AS `isActive`,`i`.`longName` AS `longName`,`i`.`subName` AS `subName`,`i`.`tag5` AS `tag5`,`i`.`value5` AS `value5`,`i`.`tag6` AS `tag6`,`i`.`value6` AS `value6`,`i`.`tag7` AS `tag7`,`i`.`value7` AS `value7`,`i`.`tag8` AS `tag8`,`i`.`value8` AS `value8`,`i`.`tag9` AS `tag9`,`i`.`value9` AS `value9`,`i`.`tag10` AS `tag10`,`i`.`value10` AS `value10`,`i`.`minimum` AS `minimum`,`i`.`upToDown` AS `upToDown`,`i`.`hasKgPrice` AS `hasKgPrice`,`i`.`equivalent` AS `Equivalente`,`i`.`isToPrint` AS `Imprimir`,`i`.`doPhoto` AS `do_photo`,`i`.`created` AS `odbc_date`,`i`.`isFloramondo` AS `isFloramondo`,`i`.`supplyResponseFk` AS `supplyResponseFk`,`i`.`stemMultiplier` AS `stemMultiplier`,`i`.`itemPackingTypeFk` AS `itemPackingTypeFk`,`i`.`packingOut` AS `packingOut` from `vn`.`item` `i` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
@@ -89206,7 +88685,7 @@ USE `vn2008`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
-/*!50001 VIEW `Clientes` AS select `c`.`id` AS `id_cliente`,`c`.`name` AS `cliente`,`c`.`fi` AS `if`,`c`.`socialName` AS `razonSocial`,`c`.`contact` AS `contacto`,`c`.`street` AS `domicilio`,`c`.`city` AS `poblacion`,`c`.`postcode` AS `codPostal`,`c`.`phone` AS `telefono`,`c`.`mobile` AS `movil`,`c`.`isRelevant` AS `real`,`c`.`email` AS `e-mail`,`c`.`iban` AS `iban`,`c`.`dueDay` AS `vencimiento`,`c`.`accountingAccount` AS `Cuenta`,`c`.`isEqualizated` AS `RE`,`c`.`provinceFk` AS `province_id`,`c`.`hasToInvoice` AS `invoice`,`c`.`credit` AS `credito`,`c`.`countryFk` AS `Id_Pais`,`c`.`isActive` AS `activo`,`c`.`gestdocFk` AS `gestdoc_id`,`c`.`quality` AS `calidad`,`c`.`payMethodFk` AS `pay_met_id`,`c`.`created` AS `created`,`c`.`isToBeMailed` AS `mail`,`c`.`contactChannelFk` AS `chanel_id`,`c`.`hasSepaVnl` AS `sepaVnl`,`c`.`hasCoreVnl` AS `coreVnl`,`c`.`hasCoreVnh` AS `coreVnh`,`c`.`hasLcr` AS `hasLcr`,`c`.`defaultAddressFk` AS `default_address`,`c`.`riskCalculated` AS `risk_calculated`,`c`.`hasToInvoiceByAddress` AS `invoiceByAddress`,`c`.`isTaxDataChecked` AS `contabilizado`,`c`.`isFreezed` AS `congelado`,`c`.`creditInsurance` AS `creditInsurance`,`c`.`isCreatedAsServed` AS `isCreatedAsServed`,`c`.`hasInvoiceSimplified` AS `hasInvoiceSimplified`,`c`.`salesPersonFk` AS `Id_Trabajador`,`c`.`isVies` AS `vies`,`c`.`bankEntityFk` AS `bankEntityFk`,`c`.`typeFk` AS `typeFk` from `vn`.`client` `c` */;
+/*!50001 VIEW `Clientes` AS select `c`.`id` AS `id_cliente`,`c`.`name` AS `cliente`,`c`.`fi` AS `if`,`c`.`socialName` AS `razonSocial`,`c`.`contact` AS `contacto`,`c`.`street` AS `domicilio`,`c`.`city` AS `poblacion`,`c`.`postcode` AS `codPostal`,`c`.`phone` AS `telefono`,`c`.`mobile` AS `movil`,`c`.`isRelevant` AS `real`,`c`.`email` AS `e-mail`,`c`.`iban` AS `iban`,`c`.`dueDay` AS `vencimiento`,`c`.`accountingAccount` AS `Cuenta`,`c`.`isEqualizated` AS `RE`,`c`.`provinceFk` AS `province_id`,`c`.`hasToInvoice` AS `invoice`,`c`.`credit` AS `credito`,`c`.`countryFk` AS `Id_Pais`,`c`.`isActive` AS `activo`,`c`.`quality` AS `calidad`,`c`.`payMethodFk` AS `pay_met_id`,`c`.`created` AS `created`,`c`.`isToBeMailed` AS `mail`,`c`.`contactChannelFk` AS `chanel_id`,`c`.`hasSepaVnl` AS `sepaVnl`,`c`.`hasCoreVnl` AS `coreVnl`,`c`.`hasCoreVnh` AS `coreVnh`,`c`.`hasLcr` AS `hasLcr`,`c`.`defaultAddressFk` AS `default_address`,`c`.`riskCalculated` AS `risk_calculated`,`c`.`hasToInvoiceByAddress` AS `invoiceByAddress`,`c`.`isTaxDataChecked` AS `contabilizado`,`c`.`isFreezed` AS `congelado`,`c`.`creditInsurance` AS `creditInsurance`,`c`.`isCreatedAsServed` AS `isCreatedAsServed`,`c`.`hasInvoiceSimplified` AS `hasInvoiceSimplified`,`c`.`salesPersonFk` AS `Id_Trabajador`,`c`.`isVies` AS `vies`,`c`.`bankEntityFk` AS `bankEntityFk`,`c`.`typeFk` AS `typeFk` from `vn`.`client` `c` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
@@ -89247,24 +88726,6 @@ USE `vn2008`;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
---
--- Final view structure for view `Compres_mark`
---
-
-/*!50001 DROP VIEW IF EXISTS `Compres_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 = utf8mb4 */;
-/*!50001 SET character_set_results = utf8mb4 */;
-/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
-/*!50001 CREATE ALGORITHM=UNDEFINED */
-/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
-/*!50001 VIEW `Compres_mark` AS select `bm`.`id` AS `Id_Compra`,`bm`.`comment` AS `comment`,`bm`.`mark` AS `mark`,`bm`.`odbcDate` AS `odbc_date` from `vn`.`buyMark` `bm` */;
-/*!50001 SET character_set_client = @saved_cs_client */;
-/*!50001 SET character_set_results = @saved_cs_results */;
-/*!50001 SET collation_connection = @saved_col_connection */;
-
--
-- Final view structure for view `Consignatarios`
--
@@ -89296,7 +88757,7 @@ USE `vn2008`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
-/*!50001 VIEW `Cubos` AS select `p`.`id` AS `Id_Cubo`,`p`.`volume` AS `Volumen`,`p`.`width` AS `X`,`p`.`depth` AS `Y`,`p`.`height` AS `Z`,`p`.`isPackageReturnable` AS `Retornable`,`p`.`created` AS `odbc_date`,`p`.`itemFk` AS `item_id`,`p`.`price` AS `pvp`,`p`.`cubicPackage` AS `bultoCubico`,`p`.`value` AS `Valor`,`p`.`packagingReturnFk` AS `idCubos_Retorno`,`p`.`lower` AS `Bajan`,`p`.`upload` AS `Suben`,`p`.`base` AS `Base`,`p`.`isBox` AS `box`,`p`.`returnCost` AS `costeRetorno` from `vn`.`packaging` `p` */;
+/*!50001 VIEW `Cubos` AS select `p`.`id` AS `Id_Cubo`,`p`.`volume` AS `Volumen`,`p`.`width` AS `X`,`p`.`depth` AS `Y`,`p`.`height` AS `Z`,`p`.`isPackageReturnable` AS `Retornable`,`p`.`created` AS `odbc_date`,`p`.`itemFk` AS `item_id`,`p`.`price` AS `pvp`,`p`.`cubicPackage` AS `bultoCubico`,`p`.`value` AS `Valor`,`p`.`packagingReturnFk` AS `idCubos_Retorno`,`p`.`lower` AS `Bajan`,`p`.`upload` AS `Suben`,`p`.`base` AS `Base`,`p`.`isBox` AS `box`,`p`.`returnCost` AS `costeRetorno`,`p`.`isActive` AS `isActive` from `vn`.`packaging` `p` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
@@ -89332,25 +88793,7 @@ USE `vn2008`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
-/*!50001 VIEW `Entradas` AS select `e`.`id` AS `Id_Entrada`,`e`.`supplierFk` AS `Id_Proveedor`,`e`.`invoiceNumber` AS `Referencia`,`e`.`reference` AS `reference`,`e`.`isExcludedFromAvailable` AS `Inventario`,`e`.`isConfirmed` AS `Confirmada`,`e`.`isOrdered` AS `Pedida`,`e`.`isRaid` AS `Redada`,`e`.`commission` AS `comision`,`e`.`created` AS `odbc_date`,`e`.`evaNotes` AS `Notas_Eva`,`e`.`travelFk` AS `travel_id`,`e`.`currencyFk` AS `Id_Moneda`,`e`.`companyFk` AS `empresa_id`,`e`.`gestDocFk` AS `gestdoc_id`,`e`.`invoiceInFk` AS `recibida_id`,`e`.`dated` AS `Fecha`,`e`.`isBooked` AS `Anotadoencaja`,`e`.`loadPriority` AS `loadPriority`,`e`.`sub` AS `sub`,`e`.`kop` AS `kop`,`e`.`pro` AS `pro`,`e`.`invoiceAmount` AS `invoiceAmount`,`e`.`buyerFk` AS `buyerFk`,`e`.`typeFk` AS `typeFk` from `vn`.`entry` `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 `Entradas_Auto`
---
-
-/*!50001 DROP VIEW IF EXISTS `Entradas_Auto`*/;
-/*!50001 SET @saved_cs_client = @@character_set_client */;
-/*!50001 SET @saved_cs_results = @@character_set_results */;
-/*!50001 SET @saved_col_connection = @@collation_connection */;
-/*!50001 SET character_set_client = utf8mb4 */;
-/*!50001 SET character_set_results = utf8mb4 */;
-/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
-/*!50001 CREATE ALGORITHM=UNDEFINED */
-/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
-/*!50001 VIEW `Entradas_Auto` AS select `ev`.`entryFk` AS `Id_Entrada` from `vn`.`entryVirtual` `ev` */;
+/*!50001 VIEW `Entradas` AS select `e`.`id` AS `Id_Entrada`,`e`.`supplierFk` AS `Id_Proveedor`,`e`.`invoiceNumber` AS `Referencia`,`e`.`reference` AS `reference`,`e`.`isExcludedFromAvailable` AS `Inventario`,`e`.`isConfirmed` AS `Confirmada`,`e`.`isOrdered` AS `Pedida`,`e`.`commission` AS `comision`,`e`.`created` AS `odbc_date`,`e`.`evaNotes` AS `Notas_Eva`,`e`.`travelFk` AS `travel_id`,`e`.`currencyFk` AS `Id_Moneda`,`e`.`companyFk` AS `empresa_id`,`e`.`gestDocFk` AS `gestdoc_id`,`e`.`invoiceInFk` AS `recibida_id`,`e`.`dated` AS `Fecha`,`e`.`isBooked` AS `Anotadoencaja`,`e`.`loadPriority` AS `loadPriority`,`e`.`sub` AS `sub`,`e`.`kop` AS `kop`,`e`.`pro` AS `pro`,`e`.`invoiceAmount` AS `invoiceAmount`,`e`.`buyerFk` AS `buyerFk`,`e`.`typeFk` AS `typeFk` from `vn`.`entry` `e` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
@@ -89656,7 +89099,7 @@ USE `vn2008`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
-/*!50001 VIEW `Rutas` AS select `r`.`id` AS `Id_Ruta`,`r`.`workerFk` AS `Id_Trabajador`,`r`.`created` AS `Fecha`,`r`.`vehicleFk` AS `Id_Vehiculo`,`r`.`agencyModeFk` AS `Id_Agencia`,`r`.`time` AS `Hora`,`r`.`isOk` AS `ok`,`r`.`kmStart` AS `km_start`,`r`.`kmEnd` AS `km_end`,`r`.`started` AS `date_start`,`r`.`finished` AS `date_end`,`r`.`gestdocFk` AS `gestdoc_id`,`r`.`cost` AS `cost`,`r`.`m3` AS `m3`,`r`.`description` AS `description` from `vn`.`route` `r` */;
+/*!50001 VIEW `Rutas` AS select `r`.`id` AS `Id_Ruta`,`r`.`workerFk` AS `Id_Trabajador`,`r`.`dated` AS `Fecha`,`r`.`vehicleFk` AS `Id_Vehiculo`,`r`.`agencyModeFk` AS `Id_Agencia`,`r`.`time` AS `Hora`,`r`.`isOk` AS `ok`,`r`.`kmStart` AS `km_start`,`r`.`kmEnd` AS `km_end`,`r`.`started` AS `date_start`,`r`.`finished` AS `date_end`,`r`.`gestdocFk` AS `gestdoc_id`,`r`.`cost` AS `cost`,`r`.`m3` AS `m3`,`r`.`description` AS `description` from `vn`.`route` `r` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
@@ -90682,7 +90125,7 @@ USE `vn2008`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
-/*!50001 VIEW `entrySource` AS select `e`.`gestDocFk` AS `gestdoc_id`,`e`.`id` AS `Id_Entrada`,`e`.`invoiceNumber` AS `invoiceNumber`,`e`.`reference` AS `reference`,`e`.`isExcludedFromAvailable` AS `Inventario`,`e`.`isConfirmed` AS `Confirmada`,`e`.`isOrdered` AS `Pedida`,`e`.`isRaid` AS `Redada`,`e`.`evaNotes` AS `notas`,`e`.`supplierFk` AS `Id_Proveedor`,`tr`.`shipped` AS `shipment`,`tr`.`landed` AS `landing`,`w2`.`name` AS `wh_in`,`w1`.`name` AS `wh_out`,`am`.`name` AS `Agencia`,`e`.`commission` AS `comision`,`tr`.`warehouseInFk` AS `warehouse_id`,`w1`.`id` AS `warehouse_id_out`,`e`.`isBooked` AS `anotadoencaja`,`e`.`invoiceInFk` AS `invoiceInFk`,`e`.`companyFk` AS `empresa_id`,`e`.`currencyFk` AS `Id_Moneda`,`tr`.`id` AS `TravelFk`,`e`.`sub` AS `sub`,`e`.`kop` AS `kop`,`e`.`pro` AS `pro`,`e`.`invoiceAmount` AS `invoiceAmount`,`w`.`code` AS `buyerCode`,`e`.`typeFk` AS `typeFk`,`w3`.`code` AS `observationWorkerCode` from (((((((`vn`.`entry` `e` left join `vn`.`travel` `tr` on(`e`.`travelFk` = `tr`.`id`)) left join `vn`.`agencyMode` `am` on(`am`.`id` = `tr`.`agencyModeFk`)) left join `vn`.`warehouse` `w1` on(`tr`.`warehouseOutFk` = `w1`.`id`)) left join `vn`.`warehouse` `w2` on(`tr`.`warehouseInFk` = `w2`.`id`)) left join `vn`.`supplier` `s` on(`e`.`supplierFk` = `s`.`id`)) left join `vn`.`worker` `w` on(`w`.`id` = `e`.`buyerFk`)) left join `vn`.`worker` `w3` on(`w3`.`id` = `e`.`observationEditorFk`)) */;
+/*!50001 VIEW `entrySource` AS select `e`.`gestDocFk` AS `gestdoc_id`,`e`.`id` AS `Id_Entrada`,`e`.`invoiceNumber` AS `invoiceNumber`,`e`.`reference` AS `reference`,`e`.`isExcludedFromAvailable` AS `Inventario`,`e`.`isConfirmed` AS `Confirmada`,`e`.`isOrdered` AS `Pedida`,`tr`.`isRaid` AS `isRaid`,`tr`.`daysInForward` AS `daysInForward`,`e`.`evaNotes` AS `notas`,`e`.`supplierFk` AS `Id_Proveedor`,`tr`.`shipped` AS `shipment`,`tr`.`landed` AS `landing`,`w2`.`name` AS `wh_in`,`w1`.`name` AS `wh_out`,`am`.`name` AS `Agencia`,`e`.`commission` AS `comision`,`tr`.`warehouseInFk` AS `warehouse_id`,`w1`.`id` AS `warehouse_id_out`,`e`.`isBooked` AS `anotadoencaja`,`e`.`invoiceInFk` AS `invoiceInFk`,`e`.`companyFk` AS `empresa_id`,`e`.`currencyFk` AS `Id_Moneda`,`tr`.`id` AS `TravelFk`,`e`.`sub` AS `sub`,`e`.`kop` AS `kop`,`e`.`pro` AS `pro`,`e`.`invoiceAmount` AS `invoiceAmount`,`w`.`code` AS `buyerCode`,`e`.`typeFk` AS `typeFk`,`w3`.`code` AS `observationWorkerCode` from (((((((`vn`.`entry` `e` left join `vn`.`travel` `tr` on(`e`.`travelFk` = `tr`.`id`)) left join `vn`.`agencyMode` `am` on(`am`.`id` = `tr`.`agencyModeFk`)) left join `vn`.`warehouse` `w1` on(`tr`.`warehouseOutFk` = `w1`.`id`)) left join `vn`.`warehouse` `w2` on(`tr`.`warehouseInFk` = `w2`.`id`)) left join `vn`.`supplier` `s` on(`e`.`supplierFk` = `s`.`id`)) left join `vn`.`worker` `w` on(`w`.`id` = `e`.`buyerFk`)) left join `vn`.`worker` `w3` on(`w3`.`id` = `e`.`observationEditorFk`)) */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
@@ -91240,7 +90683,7 @@ USE `vn2008`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
-/*!50001 VIEW `state` AS select `s`.`id` AS `id`,`s`.`name` AS `name`,`s`.`order` AS `order`,`s`.`alertLevel` AS `alert_level`,`s`.`code` AS `code`,`s`.`sectorProdPriority` AS `sectorProdPriority`,`s`.`nextStateFk` AS `nextStateFk`,`s`.`isPreviousPreparable` AS `isPreviousPreparable`,`s`.`isPicked` AS `isPicked` from `vn`.`state` `s` */;
+/*!50001 VIEW `state` AS select `s`.`id` AS `id`,`s`.`name` AS `name`,`s`.`order` AS `order`,`s`.`alertLevel` AS `alert_level`,`s`.`code` AS `code`,`s`.`nextStateFk` AS `nextStateFk`,`s`.`isPreviousPreparable` AS `isPreviousPreparable`,`s`.`isPicked` AS `isPicked` from `vn`.`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 */;
@@ -91402,7 +90845,7 @@ USE `vn2008`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
-/*!50001 VIEW `travel` AS select `t`.`id` AS `id`,`t`.`shipped` AS `shipment`,`t`.`shipmentHour` AS `shipment_hour`,`t`.`landed` AS `landing`,`t`.`landingHour` AS `landing_hour`,`t`.`warehouseInFk` AS `warehouse_id`,`t`.`warehouseOutFk` AS `warehouse_id_out`,`t`.`agencyModeFk` AS `agency_id`,`t`.`ref` AS `ref`,`t`.`isDelivered` AS `delivered`,`t`.`isReceived` AS `received`,`t`.`m3` AS `m3`,`t`.`kg` AS `kg`,`t`.`cargoSupplierFk` AS `cargoSupplierFk`,`t`.`totalEntries` AS `totalEntries`,`t`.`appointment` AS `appointment`,`t`.`awbFk` AS `awbFk` from `vn`.`travel` `t` */;
+/*!50001 VIEW `travel` AS select `t`.`id` AS `id`,`t`.`shipped` AS `shipment`,`t`.`shipmentHour` AS `shipment_hour`,`t`.`landed` AS `landing`,`t`.`landingHour` AS `landing_hour`,`t`.`warehouseInFk` AS `warehouse_id`,`t`.`warehouseOutFk` AS `warehouse_id_out`,`t`.`agencyModeFk` AS `agency_id`,`t`.`ref` AS `ref`,`t`.`isDelivered` AS `delivered`,`t`.`isReceived` AS `received`,`t`.`m3` AS `m3`,`t`.`kg` AS `kg`,`t`.`cargoSupplierFk` AS `cargoSupplierFk`,`t`.`totalEntries` AS `totalEntries`,`t`.`appointment` AS `appointment`,`t`.`awbFk` AS `awbFk`,`t`.`isRaid` AS `isRaid`,`t`.`daysInForward` AS `daysInForward` from `vn`.`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 */;
@@ -91438,7 +90881,7 @@ USE `vn2008`;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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`,`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`.`isFeedStock` AS `fuente`,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 ((((((((`vn2008`.`Compres` `C` join `vn2008`.`Entradas` `E` on(`C`.`Id_Entrada` = `E`.`Id_Entrada`)) join `vn2008`.`travel` `TR` on(`TR`.`id` = `E`.`travel_id`)) join `vn`.`warehouse` `W_IN` on(`W_IN`.`id` = `TR`.`warehouse_id`)) join `vn`.`warehouse` `W_OUT` on(`W_OUT`.`id` = `TR`.`warehouse_id_out`)) join `vn2008`.`Articles` `A` on(`C`.`Id_Article` = `A`.`Id_Article`)) join `vn2008`.`Tipos` `TP` on(`A`.`tipo_id` = `TP`.`tipo_id`)) join `vn2008`.`reinos` `RN` on(`RN`.`id` = `TP`.`reino_id`)) join `vn2008`.`Cubos` `cb` on(`cb`.`Id_Cubo` = `C`.`Id_Cubo`)) where `W_IN`.`isFeedStock` = 0 and `E`.`Inventario` = 0 and `E`.`Redada` = 0 */;
+/*!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`,`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`.`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`.`isFeedStock` AS `fuente`,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 ((((((((`vn2008`.`Compres` `C` join `vn2008`.`Entradas` `E` on(`C`.`Id_Entrada` = `E`.`Id_Entrada`)) join `vn2008`.`travel` `TR` on(`TR`.`id` = `E`.`travel_id`)) join `vn`.`warehouse` `W_IN` on(`W_IN`.`id` = `TR`.`warehouse_id`)) join `vn`.`warehouse` `W_OUT` on(`W_OUT`.`id` = `TR`.`warehouse_id_out`)) join `vn2008`.`Articles` `A` on(`C`.`Id_Article` = `A`.`Id_Article`)) join `vn2008`.`Tipos` `TP` on(`A`.`tipo_id` = `TP`.`tipo_id`)) join `vn2008`.`reinos` `RN` on(`RN`.`id` = `TP`.`reino_id`)) join `vn2008`.`Cubos` `cb` on(`cb`.`Id_Cubo` = `C`.`Id_Cubo`)) where `W_IN`.`isFeedStock` = 0 and `E`.`Inventario` = 0 and `TR`.`isRaid` = 0 */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
@@ -91506,4 +90949,4 @@ USE `vn2008`;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
--- Dump completed on 2024-09-18 9:32:42
+-- Dump completed on 2024-12-10 8:17:51
diff --git a/db/dump/.dump/triggers.sql b/db/dump/.dump/triggers.sql
index b0879a9c5..3299aea37 100644
--- a/db/dump/.dump/triggers.sql
+++ b/db/dump/.dump/triggers.sql
@@ -867,17 +867,17 @@ BEGIN
UPDATE vn.buy b
JOIN vn.entry e ON e.id = b.entryFk
- JOIN vn.travel tr ON tr.id = e.travelFk
- JOIN vn.agencyMode am ON am.id = tr.agencyModeFk
+ JOIN vn.travel tr ON tr.id = e.travelFk
+ JOIN vn.agencyMode am ON am.id = tr.agencyModeFk
JOIN vn.item i ON i.id = b.itemFk
JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID
SET b.quantity = NEW.NumberOfItemsPerCask * NEW.NumberOfUnits,
b.stickers = NEW.NumberOfUnits
WHERE i.supplyResponseFk = NEW.ID
AND am.name = 'LOGIFLORA'
- AND e.isRaid
+ AND tr.isRaid
AND tr.landed >= util.VN_CURDATE();
-
+
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -1128,6 +1128,28 @@ DELIMITER ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
+/*!50003 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+DELIMITER ;;
+/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`orderRow_afterInsert`
+ AFTER INSERT ON `orderRow`
+ FOR EACH ROW
+BEGIN
+ UPDATE `order`
+ SET rowUpdated = util.VN_NOW()
+ WHERE id = 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 */ ;
--
-- Current Database: `pbx`
@@ -1438,6 +1460,9 @@ DELIMITER ;;
FOR EACH ROW
BEGIN
SET NEW.editorFk = account.myUser_getId();
+ IF NEW.`property` = '*' THEN
+ CALL util.throw('The property field cannot be *');
+ END IF;
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -1978,6 +2003,7 @@ BEGIN
DECLARE vIsEqualizated BOOL;
SET NEW.editorFk = account.myUser_getId();
+ SET NEW.geoFk = address_getGeo(NEW.id);
IF (NEW.phone <> '') THEN
CALL pbx.phone_isValid(NEW.phone);
@@ -2014,7 +2040,6 @@ DELIMITER ;;
BEFORE UPDATE ON `address`
FOR EACH ROW
BEGIN
-
SET NEW.editorFk = account.myUser_getId();
IF !(NEW.phone <=> OLD.phone) AND (NEW.phone <> '') THEN
@@ -2025,6 +2050,11 @@ BEGIN
CALL pbx.phone_isValid(NEW.mobile);
END IF;
+ IF NOT (NEW.provinceFk <=> OLD.provinceFk)
+ OR (NEW.postalCode <=> OLD.postalCode) THEN
+
+ SET NEW.geoFk = address_getGeo(NEW.id);
+ END IF;
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -2432,11 +2462,21 @@ DELIMITER ;;
AFTER UPDATE ON `business`
FOR EACH ROW
BEGIN
+ DECLARE vIsActive BOOL;
+ DECLARE vExtension VARCHAR(10);
+
CALL worker_updateBusiness(NEW.workerFk);
IF NOT (OLD.workerFk <=> NEW.workerFk) THEN
CALL worker_updateBusiness(OLD.workerFk);
END IF;
+
+ IF NOT (OLD.departmentFk <=> NEW.departmentFk) THEN
+ SELECT COUNT(*) INTO vIsActive FROM worker WHERE businessFk = NEW.id;
+ IF vIsActive THEN
+ CALL queueMember_updateQueue(NEW.id);
+ END IF;
+ END IF;
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -3391,8 +3431,10 @@ DELIMITER ;;
BEFORE INSERT ON `client`
FOR EACH ROW
BEGIN
-
SET NEW.editorFk = account.myUser_getId();
+ SET NEW.accountingAccount = 4300000000 + NEW.id;
+ SET NEW.lastSalesPersonFk = NEW.salesPersonFk;
+ SET NEW.geoFk = client_getGeo(NEW.id);
IF (NEW.phone <> '') THEN
CALL pbx.phone_isValid(NEW.phone);
@@ -3401,10 +3443,6 @@ BEGIN
IF (NEW.mobile <> '') THEN
CALL pbx.phone_isValid(NEW.mobile);
END IF;
-
- SET NEW.accountingAccount = 4300000000 + NEW.id;
-
- SET NEW.lastSalesPersonFk = NEW.salesPersonFk;
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -3518,6 +3556,12 @@ BEGIN
IF NOT (NEW.businessTypeFk <=> OLD.businessTypeFk) AND (NEW.businessTypeFk = 'individual' OR OLD.businessTypeFk = 'individual') THEN
SET NEW.isTaxDataChecked = 0;
END IF;
+
+ IF NOT (NEW.provinceFk <=> OLD.provinceFk)
+ OR (NEW.postcode <=> OLD.postcode) THEN
+
+ SET NEW.geoFk = client_getGeo(NEW.id);
+ END IF;
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -4306,35 +4350,13 @@ DELIMITER ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`creditInsurance_beforeInsert`
- BEFORE INSERT ON `creditInsurance`
- FOR EACH ROW
-BEGIN
- IF NEW.creditClassificationFk THEN
- SET NEW.creditClassification = NEW.creditClassificationFk;
- END IF;
-END */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 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;
+ SET creditInsurance = NEW.credit WHERE cc.id = NEW.creditClassificationFk;
END */;;
DELIMITER ;
@@ -4950,7 +4972,7 @@ DELIMITER ;;
BEFORE UPDATE ON `entry`
FOR EACH ROW
BEGIN
- DECLARE vIsVirtual BOOL;
+ DECLARE vIsRaid BOOL;
DECLARE vPrintedCount INT;
DECLARE vHasDistinctWarehouses BOOL;
DECLARE vTotalBuy INT;
@@ -4984,18 +5006,20 @@ BEGIN
IF NEW.travelFk IS NOT NULL THEN
CALL travel_throwAwb(NEW.travelFk);
END IF;
-
- SELECT COUNT(*) > 0 INTO vIsVirtual
- FROM entryVirtual WHERE entryFk = NEW.id;
+
+ SELECT t.isRaid INTO vIsRaid
+ FROM travel t
+ JOIN entry e ON e.travelFk = t.id
+ WHERE e.id = NEW.id;
SELECT NOT (o.warehouseInFk <=> n.warehouseInFk)
- OR NOT (o.warehouseOutFk <=> n.warehouseOutFk)
+ OR NOT (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
+ IF vIsRaid AND vHasDistinctWarehouses THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'A cloned entry cannot be moved to a travel with different warehouses';
END IF;
@@ -5018,7 +5042,10 @@ BEGIN
SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk);
END IF;
- IF NOT (NEW.travelFk <=> OLD.travelFk) OR NOT (NEW.currencyFk <=> OLD.currencyFk) THEN
+ IF NOT (NEW.travelFk <=> OLD.travelFk)
+ OR NOT (NEW.currencyFk <=> OLD.currencyFk)
+ OR NOT (NEW.supplierFk <=> OLD.supplierFk) THEN
+
SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk, NEW.supplierFk);
END IF;
END */;;
@@ -5312,7 +5339,8 @@ BEGIN
SET packages = (SELECT COUNT(counter)-1
FROM expedition e WHERE e.ticketFk = OLD.ticketFk and e.freightItemFk)
WHERE t.id = OLD.ticketFk;
-
+
+ CALL expedition_selfConsumptionPackaging(OLD.id, 'remove');
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -5552,7 +5580,7 @@ DELIMITER ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`host_beforeInsert`
+/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`host_beforeInsert`
BEFORE INSERT ON `host`
FOR EACH ROW
BEGIN
@@ -6419,7 +6447,7 @@ BEGIN
JOIN vn.route r ON r.id = t.routeFk
WHERE r.isOk = FALSE
AND ic.itemFk = NEW.itemFk
- AND r.created >= util.VN_CURDATE()
+ AND r.dated >= util.VN_CURDATE()
GROUP BY r.id;
IF NEW.cm3Delivery = 0 AND NEW.warehouseFk = 60 THEN
CALL mail_insert(
@@ -6543,6 +6571,9 @@ BEGIN
SET NEW.userFk = account.myUser_getId();
END IF;
+ IF NEW.shelvingFk <> OLD.shelvingFk THEN
+ SET NEW.movingState = NULL;
+ END IF;
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -6558,63 +6589,6 @@ DELIMITER ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelving_afterUpdate`
- AFTER UPDATE ON `itemShelving`
- FOR EACH ROW
-BEGIN
- INSERT INTO itemShelvingLog
- SET itemShelvingFk = NEW.id,
- workerFk = account.myUser_getId(),
- accion = 'CAMBIO',
- itemFk = NEW.itemFk,
- shelvingFk = NEW.shelvingFk,
- visible = NEW.visible,
- `grouping` = NEW.`grouping`,
- packing = NEW.packing,
- available = NEW.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 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelving_beforeDelete`
- BEFORE DELETE ON `itemShelving`
- FOR EACH ROW
-INSERT INTO vn.itemShelvingLog(itemShelvingFk,
- workerFk,
- accion,
- shelvingFk,
- itemFk)
- VALUES( OLD.id,
- account.myUser_getId(),
- 'ELIMINADO',
- OLD.shelvingFk,
- OLD.itemFk) */;;
-DELIMITER ;
-/*!50003 SET sql_mode = @saved_sql_mode */ ;
-/*!50003 SET character_set_client = @saved_cs_client */ ;
-/*!50003 SET character_set_results = @saved_cs_results */ ;
-/*!50003 SET collation_connection = @saved_col_connection */ ;
-/*!50003 SET @saved_cs_client = @@character_set_client */ ;
-/*!50003 SET @saved_cs_results = @@character_set_results */ ;
-/*!50003 SET @saved_col_connection = @@collation_connection */ ;
-/*!50003 SET character_set_client = utf8mb4 */ ;
-/*!50003 SET character_set_results = utf8mb4 */ ;
-/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelving_afterDelete`
AFTER DELETE ON `itemShelving`
FOR EACH ROW
@@ -6643,11 +6617,11 @@ DELIMITER ;;
AFTER INSERT ON `itemShelvingSale`
FOR EACH ROW
BEGIN
-
UPDATE sale s
JOIN operator o ON o.workerFk = account.myUser_getId()
- SET s.isPicked = IF(o.isOnReservationMode, s.isPicked, TRUE)
- WHERE id = NEW.saleFk;
+ JOIN sector se ON se.id = o.sectorFk
+ SET s.isPicked = IF(IFNULL(se.isOnReservationMode, o.isOnReservationMode), s.isPicked, TRUE)
+ WHERE s.id = NEW.saleFk;
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -6863,10 +6837,31 @@ DELIMITER ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
+/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemType_beforeInsert`
+ BEFORE INSERT ON `itemType`
+ FOR EACH ROW
+BEGIN
+ SET NEW.editorFk = account.myUser_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 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemType_beforeUpdate`
BEFORE UPDATE ON `itemType`
FOR EACH ROW
BEGIN
+ SET NEW.editorFk = account.myUser_getId();
IF NEW.itemPackingTypeFk = '' THEN
SET NEW.itemPackingTypeFk = NULL;
@@ -6893,6 +6888,30 @@ DELIMITER ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
+/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemType_afterDelete`
+ AFTER DELETE ON `itemType`
+ FOR EACH ROW
+BEGIN
+ INSERT INTO itemTypeLog
+ SET `action` = 'delete',
+ `changedModel` = 'ItemType',
+ `changedModelId` = OLD.id,
+ `userFk` = account.myUser_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 SET @saved_cs_client = @@character_set_client */ ;
+/*!50003 SET @saved_cs_results = @@character_set_results */ ;
+/*!50003 SET @saved_col_connection = @@collation_connection */ ;
+/*!50003 SET character_set_client = utf8mb4 */ ;
+/*!50003 SET character_set_results = utf8mb4 */ ;
+/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
+/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
+/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
+DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`machine_beforeInsert`
BEFORE INSERT ON `machine`
FOR EACH ROW
@@ -7538,7 +7557,7 @@ DELIMITER ;;
AFTER DELETE ON `productionConfig`
FOR EACH ROW
BEGIN
- INSERT INTO productionConfig
+ INSERT INTO productionConfigLog
SET `action` = 'delete',
`changedModel` = 'ProductionConfig',
`changedModelId` = OLD.id,
@@ -7925,7 +7944,7 @@ DELIMITER ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`roadmap_beforeInsert`
+/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`roadmap_beforeInsert`
BEFORE INSERT ON `roadmap`
FOR EACH ROW
BEGIN
@@ -7949,7 +7968,7 @@ DELIMITER ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`roadmap_beforeUpdate`
+/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`roadmap_beforeUpdate`
BEFORE UPDATE ON `roadmap`
FOR EACH ROW
BEGIN
@@ -8032,7 +8051,7 @@ BEGIN
SELECT IFNULL(b.workCenterFK, r.defaultWorkCenterFk)
FROM vn.routeConfig r
LEFT JOIN vn.business b ON b.workerFk = vUserFk
- AND NEW.created BETWEEN b.started AND IFNULL(b.ended, NEW.created));
+ AND NEW.dated BETWEEN b.started AND IFNULL(b.ended, NEW.dated));
IF ISNULL(NEW.agencyModeFk) THEN
SELECT r.agencyModeFk INTO vDefaultAgencyModeFk
@@ -8122,18 +8141,18 @@ DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`route_afterUpdate`
AFTER UPDATE ON `route`
FOR EACH ROW
-BEGIN
+BEGIN
IF IFNULL(NEW.gestdocFk,0) <> IFNULL(OLD.gestdocFk,0) AND NEW.gestdocFk > 0 THEN
-- JGF 09/09/14 cuando se añade un gestdoc a una ruta, se le asigna automagicamente a todos sus Tickets
-
+
-- Inserta el gestdoc en todos los tickets de la ruta
INSERT INTO ticketDms(ticketFk,dmsFk)
SELECT id, NEW.gestdocFk FROM ticket WHERE routeFk = NEW.id
ON DUPLICATE KEY UPDATE dmsFk = NEW.gestdocFk;
- -- Update del firmado
- UPDATE ticket t
- JOIN ticketDms tg ON t.id = tg.ticketFk
+ -- Update del firmado
+ UPDATE ticket t
+ JOIN ticketDms tg ON t.id = tg.ticketFk
SET isSigned = 1 WHERE t.routeFk = NEW.id;
END IF;
@@ -8141,7 +8160,8 @@ BEGIN
OR !(NEW.kmEnd <=> OLD.kmEnd)
OR !(NEW.workerFk <=> OLD.workerFk)
OR !(NEW.m3 <=> OLD.m3)
- OR !(NEW.agencyModeFk <=> OLD.agencyModeFk)THEN
+ OR !(NEW.agencyModeFk <=> OLD.agencyModeFk)
+ OR !(NEW.vehicleFk <=> OLD.vehicleFk)THEN
CALL route_calcCommission(NEW.id);
END IF;
@@ -8293,7 +8313,7 @@ BEGIN
JOIN vn.route r ON r.id = t.routeFk
WHERE r.isOk = FALSE
AND s.id = NEW.id
- AND r.created >= util.VN_CURDATE()
+ AND r.dated >= util.VN_CURDATE()
GROUP BY r.id;
END IF;
END */;;
@@ -8401,7 +8421,7 @@ BEGIN
JOIN vn.route r ON r.id = t.routeFk
WHERE r.isOk = FALSE
AND s.id = NEW.id
- AND r.created >= util.VN_CURDATE()
+ AND r.dated >= util.VN_CURDATE()
GROUP BY r.id;
END IF;
@@ -8443,7 +8463,7 @@ BEGIN
JOIN vn.route r ON r.id = t.routeFk
WHERE r.isOk = FALSE
AND s.id = OLD.id
- AND r.created >= util.VN_CURDATE()
+ AND r.dated >= util.VN_CURDATE()
GROUP BY r.id;
END IF;
END */;;
@@ -8604,7 +8624,7 @@ DELIMITER ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`saleGroupDetail_beforeInsert`
+/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`saleGroupDetail_beforeInsert`
BEFORE INSERT ON `saleGroupDetail`
FOR EACH ROW
BEGIN
@@ -8624,7 +8644,7 @@ DELIMITER ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`saleGroupDetail_beforeUpdate`
+/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`saleGroupDetail_beforeUpdate`
BEFORE UPDATE ON `saleGroupDetail`
FOR EACH ROW
BEGIN
@@ -8644,7 +8664,7 @@ DELIMITER ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`saleGroupDetail_afterDelete`
+/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`saleGroupDetail_afterDelete`
AFTER DELETE ON `saleGroupDetail`
FOR EACH ROW
BEGIN
@@ -8925,7 +8945,7 @@ DELIMITER ;;
BEGIN
UPDATE client c
JOIN creditClassification cc ON cc.client = c.id
- JOIN creditInsurance ci ON ci.creditClassification = cc.id
+ JOIN creditInsurance ci ON ci.creditClassificationFk = cc.id
SET creditInsurance = ci.credit * 2 WHERE ci.id = NEW.creditInsurance;
END */;;
DELIMITER ;
@@ -8949,12 +8969,12 @@ BEGIN
IF NEW.dateLeaving IS NOT NULL THEN
UPDATE client c
JOIN creditClassification cc ON cc.client = c.id
- JOIN creditInsurance ci ON ci.creditClassification = cc.id
+ JOIN creditInsurance ci ON ci.creditClassificationFk = cc.id
SET creditInsurance = ci.credit WHERE ci.id = OLD.creditInsurance;
ELSE
UPDATE client c
JOIN creditClassification cc ON cc.client = c.id
- JOIN creditInsurance ci ON ci.creditClassification = cc.id
+ JOIN creditInsurance ci ON ci.creditClassificationFk = cc.id
SET creditInsurance = ci.credit * 2 WHERE ci.id = OLD.creditInsurance;
END IF;
END */;;
@@ -8978,7 +8998,7 @@ DELIMITER ;;
BEGIN
UPDATE client c
JOIN creditClassification cc ON cc.client = c.id
- JOIN creditInsurance ci ON ci.creditClassification = cc.id
+ JOIN creditInsurance ci ON ci.creditClassificationFk = cc.id
SET creditInsurance = ci.credit WHERE ci.id = OLD.creditInsurance;
END */;;
DELIMITER ;
@@ -9040,6 +9060,7 @@ DELIMITER ;;
FOR EACH ROW
BEGIN
SET NEW.editorFk = account.myUser_getId();
+ SET NEW.geoFk = supplier_getGeo(NEW.id);
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -9134,6 +9155,11 @@ BEGIN
SET NEW.isPayMethodChecked = FALSE;
END IF;
+ IF NOT (NEW.provinceFk <=> OLD.provinceFk)
+ OR (NEW.postCode <=> OLD.postCode) THEN
+
+ SET NEW.geoFk = supplier_getGeo(NEW.id);
+ END IF;
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -9544,7 +9570,7 @@ BEGIN
FROM `route`
WHERE NOT isOk
AND id IN (OLD.routeFk, NEW.routeFk)
- AND created >= util.VN_CURDATE()
+ AND dated >= util.VN_CURDATE()
GROUP BY id;
END IF;
@@ -9567,7 +9593,7 @@ BEGIN
JOIN vn.route r ON r.id = t.routeFk
WHERE r.isOk = FALSE
AND t.id = NEW.id
- AND r.created >= util.VN_CURDATE()
+ AND r.dated >= util.VN_CURDATE()
GROUP BY r.id;
SET NEW.shipped = DATE_FORMAT(NEW.shipped, '2000-%m-%d %T');
SET NEW.landed = DATE_FORMAT(NEW.landed, '2000-%m-%d %T');
@@ -9646,7 +9672,7 @@ BEGIN
FROM vn.route r
WHERE r.isOk = FALSE
AND r.id = OLD.routeFk
- AND r.created >= util.VN_CURDATE()
+ AND r.dated >= util.VN_CURDATE()
GROUP BY r.id;
DELETE FROM sale WHERE ticketFk = OLD.id;
@@ -9977,6 +10003,8 @@ DELIMITER ;;
BEFORE INSERT ON `ticketRefund`
FOR EACH ROW
BEGIN
+ CALL ticketRefund_upsert(NEW.refundTicketFk, NEW.originalTicketFk);
+
SET NEW.editorFk = account.myUser_getId();
END */;;
DELIMITER ;
@@ -9997,6 +10025,8 @@ DELIMITER ;;
BEFORE UPDATE ON `ticketRefund`
FOR EACH ROW
BEGIN
+ CALL ticketRefund_upsert(NEW.refundTicketFk, NEW.originalTicketFk);
+
SET NEW.editorFk = account.myUser_getId();
END */;;
DELIMITER ;
@@ -10451,28 +10481,6 @@ DELIMITER ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`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_unicode_ci */ ;
-/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
-/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
-DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`town_afterUpdate`
AFTER UPDATE ON `town`
FOR EACH ROW
@@ -10530,7 +10538,11 @@ BEGIN
CALL travel_checkDates(NEW.shipped, NEW.landed);
CALL travel_checkWarehouseIsFeedStock(NEW.warehouseInFk);
-
+
+ IF NEW.isRaid IS NOT NULL OR NEW.daysInForward IS NOT NULL THEN
+ CALL travel_checkRaid(NEW.isRaid, NEW.daysInForward);
+ END IF;
+
IF NEW.awbFk IS NOT NULL THEN
CALL travel_throwAwb(NEW.id);
END IF;
@@ -10557,7 +10569,7 @@ BEGIN
SET NEW.editorFk = account.myUser_getId();
- IF NOT (NEW.landed <=> OLD.landed)
+ IF NOT (NEW.landed <=> OLD.landed)
OR NOT (NEW.shipped <=> OLD.shipped) THEN
CALL travel_checkDates(NEW.shipped, NEW.landed);
END IF;
@@ -10571,18 +10583,18 @@ BEGIN
END IF;
IF NOT (NEW.awbFk <=> OLD.awbFk)THEN
- SELECT COUNT(*) INTO vHasAnyInvoiceBooked
+ SELECT COUNT(*) INTO vHasAnyInvoiceBooked
FROM travel t
- JOIN entry e ON e.travelFk = t.id
- JOIN invoiceIn ii ON ii.id = e.invoiceInFk
+ JOIN entry e ON e.travelFk = t.id
+ JOIN invoiceIn ii ON ii.id = e.invoiceInFk
WHERE t.id = NEW.id
- AND ii.isBooked;
-
+ AND ii.isBooked;
+
IF vHasAnyInvoiceBooked THEN
CALL util.throw('The travel has entries with booked invoices');
END IF;
- END IF;
-
+ END IF;
+
IF (NOT(NEW.awbFk <=> OLD.awbFk)) AND NEW.awbFk IS NOT NULL THEN
CALL travel_throwAwb(NEW.id);
END IF;
@@ -10667,6 +10679,15 @@ DELIMITER ;;
FOR EACH ROW
BEGIN
SET NEW.editorFk = account.myUser_getId();
+
+ IF NEW.travelFk IS NULL AND
+ (SELECT COUNT(*) FROM travelThermograph
+ WHERE thermographFk = NEW.thermographFk
+ AND travelFk IS NULL
+ AND id <> NEW.id) > 0
+ THEN
+ CALL util.throw('Duplicate thermographFk without travelFk not allowed.');
+ END IF;
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -10687,6 +10708,15 @@ DELIMITER ;;
FOR EACH ROW
BEGIN
SET NEW.editorFk = account.myUser_getId();
+
+ IF NEW.travelFk IS NULL AND
+ (SELECT COUNT(*) FROM travelThermograph
+ WHERE thermographFk = NEW.thermographFk
+ AND travelFk IS NULL
+ AND id <> NEW.id) > 0
+ THEN
+ CALL util.throw('Duplicate thermographFk without travelFk not allowed.');
+ END IF;
END */;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
@@ -10852,8 +10882,8 @@ DELIMITER ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`workerDocument_beforeInsert`
- BEFORE INSERT ON `workerDocument`
+/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`workerDms_beforeInsert`
+ BEFORE INSERT ON `workerDms`
FOR EACH ROW
BEGIN
SET NEW.editorFk = account.myUser_getId();
@@ -10872,8 +10902,8 @@ DELIMITER ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`workerDocument_beforeUpdate`
- BEFORE UPDATE ON `workerDocument`
+/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`workerDms_beforeUpdate`
+ BEFORE UPDATE ON `workerDms`
FOR EACH ROW
BEGIN
SET NEW.editorFk = account.myUser_getId();
@@ -10892,13 +10922,13 @@ DELIMITER ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
-/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`workerDocument_afterDelete`
- AFTER DELETE ON `workerDocument`
+/*!50003 CREATE*/ /*!50017 DEFINER=`vn`@`localhost`*/ /*!50003 TRIGGER `vn`.`workerDms_afterDelete`
+ AFTER DELETE ON `workerDms`
FOR EACH ROW
BEGIN
INSERT INTO workerLog
SET `action` = 'delete',
- `changedModel` = 'WorkerDocument',
+ `changedModel` = 'WorkerDms',
`changedModelId` = OLD.id,
`userFk` = account.myUser_getId();
END */;;
@@ -11458,4 +11488,4 @@ USE `vn2008`;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
--- Dump completed on 2024-09-18 9:32:59
+-- Dump completed on 2024-12-10 8:18:11
diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql
index a418876b0..1f85402f0 100644
--- a/db/dump/fixtures.before.sql
+++ b/db/dump/fixtures.before.sql
@@ -185,6 +185,7 @@ INSERT INTO `vn`.`warehouse`(`id`, `name`, `code`, `isComparative`, `isInventory
(3, 'Warehouse Three', NULL, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0),
(4, 'Warehouse Four', NULL, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1),
(5, 'Warehouse Five', NULL, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0),
+ (6, 'Warehouse six', 'vnh', 1, 1, 1, 1, 0, 0, 1, 1, 0, 0),
(13, 'Inventory', 'inv', 1, 1, 1, 0, 0, 0, 1, 0, 0, 0),
(60, 'Algemesi', NULL, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0);
@@ -387,23 +388,23 @@ INSERT INTO `vn`.`contactChannel`(`id`, `name`)
(4, 'GCN Channel'),
(5, 'The Newspaper');
-INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city`,`postcode`,`phone`,`mobile`,`isRelevant`,`email`,`iban`,`dueDay`,`accountingAccount`,`isEqualizated`,`provinceFk`,`hasToInvoice`,`credit`,`countryFk`,`isActive`,`gestdocFk`,`quality`,`payMethodFk`,`created`,`isToBeMailed`,`contactChannelFk`,`hasSepaVnl`,`hasCoreVnl`,`hasCoreVnh`,`riskCalculated`, `hasToInvoiceByAddress`,`isTaxDataChecked`,`isFreezed`,`creditInsurance`,`isCreatedAsServed`,`hasInvoiceSimplified`,`salesPersonFk`,`isVies`,`businessTypeFk`,`typeFk`)
+INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city`,`postcode`,`phone`,`mobile`,`isRelevant`,`email`,`iban`,`dueDay`,`accountingAccount`,`isEqualizated`,`provinceFk`,`hasToInvoice`,`credit`,`countryFk`,`isActive`,`quality`,`payMethodFk`,`created`,`isToBeMailed`,`contactChannelFk`,`hasSepaVnl`,`hasCoreVnl`,`hasCoreVnh`,`riskCalculated`, `hasToInvoiceByAddress`,`isTaxDataChecked`,`isFreezed`,`creditInsurance`,`isCreatedAsServed`,`hasInvoiceSimplified`,`salesPersonFk`,`isVies`,`businessTypeFk`,`typeFk`)
VALUES
- (1101, 'Bruce Wayne', '84612325V', 'BATMAN', 'Alfred', '1007 MOUNTAIN DRIVE, GOTHAM', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceWayne@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal'),
- (1102, 'Petter Parker', '87945234L', 'SPIDER MAN', 'Aunt May', '20 INGRAM STREET, QUEENS, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'PetterParker@mydomain.com', NULL, 0, 1234567890, 0, 2, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal'),
- (1103, 'Clark Kent', '06815934E', 'SUPER MAN', 'lois lane', '344 CLINTON STREET, APARTAMENT 3-D', 'Gotham', 46460, 1111111111, 222222222, 1, 'ClarkKent@mydomain.com', NULL, 0, 1234567890, 0, 3, 1, 0, 19, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal'),
- (1104, 'Tony Stark', '06089160W', 'IRON MAN', 'Pepper Potts', '10880 MALIBU POINT, 90265', 'Gotham', 46460, 1111111111, 222222222, 1, 'TonyStark@mydomain.com', NULL, 0, 1234567890, 0, 2, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal'),
- (1105, 'Max Eisenhardt', '251628698', 'MAGNETO', 'Rogue', 'UNKNOWN WHEREABOUTS', 'Gotham', 46460, 1111111111, 222222222, 1, 'MaxEisenhardt@mydomain.com', NULL, 0, 1234567890, 0, 3, 1, 300, 8, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, NULL, 0, 0, 18, 0, 'florist','normal'),
- (1106, 'DavidCharlesHaller', '53136686Q', 'LEGION', 'Charles Xavier', 'CITY OF NEW YORK, NEW YORK, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'DavidCharlesHaller@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 0, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 19, 0, 'florist','normal'),
- (1107, 'Hank Pym', '09854837G', 'ANT MAN', 'Hawk', 'ANTHILL, SAN FRANCISCO, CALIFORNIA', 'Gotham', 46460, 1111111111, 222222222, 1, 'HankPym@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 0, 0, NULL, 0, 0, 19, 0, 'florist','normal'),
- (1108, 'Charles Xavier', '22641921P', 'PROFESSOR X', 'Beast', '3800 VICTORY PKWY, CINCINNATI, OH 45207, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'CharlesXavier@mydomain.com', NULL, 0, 1234567890, 0, 5, 1, 300, 13, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, NULL, 0, 0, 19, 0, 'florist','normal'),
- (1109, 'Bruce Banner', '16104829E', 'HULK', 'Black widow', 'SOMEWHERE IN NEW YORK', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceBanner@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 0, 0, NULL, 0, 0, 9, 0, 'florist','normal'),
- (1110, 'Jessica Jones', '58282869H', 'JESSICA JONES', 'Luke Cage', 'NYCC 2015 POSTER', 'Gotham', 46460, 1111111111, 222222222, 1, 'JessicaJones@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, NULL, 1, 'florist','normal'),
- (1111, 'Missing', NULL, 'MISSING MAN', 'Anton', 'THE SPACE, UNIVERSE FAR AWAY', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 0, 1, 0, NULL, 1, 0, NULL, 0, 'others','loses'),
- (1112, 'Trash', NULL, 'GARBAGE MAN', 'Unknown name', 'NEW YORK CITY, UNDERGROUND', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 0, 1, 0, NULL, 1, 0, NULL, 0, 'others','loses');
+ (1101, 'Bruce Wayne', '84612325V', 'BATMAN', 'Alfred', '1007 MOUNTAIN DRIVE, GOTHAM', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceWayne@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal'),
+ (1102, 'Petter Parker', '87945234L', 'SPIDER MAN', 'Aunt May', '20 INGRAM STREET, QUEENS, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'PetterParker@mydomain.com', NULL, 0, 1234567890, 0, 2, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal'),
+ (1103, 'Clark Kent', '06815934E', 'SUPER MAN', 'lois lane', '344 CLINTON STREET, APARTAMENT 3-D', 'Gotham', 46460, 1111111111, 222222222, 1, 'ClarkKent@mydomain.com', NULL, 0, 1234567890, 0, 3, 1, 0, 19, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal'),
+ (1104, 'Tony Stark', '06089160W', 'IRON MAN', 'Pepper Potts', '10880 MALIBU POINT, 90265', 'Gotham', 46460, 1111111111, 222222222, 1, 'TonyStark@mydomain.com', NULL, 0, 1234567890, 0, 2, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 18, 0, 'florist','normal'),
+ (1105, 'Max Eisenhardt', '251628698', 'MAGNETO', 'Rogue', 'UNKNOWN WHEREABOUTS', 'Gotham', 46460, 1111111111, 222222222, 1, 'MaxEisenhardt@mydomain.com', NULL, 0, 1234567890, 0, 3, 1, 300, 8, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, NULL, 0, 0, 18, 0, 'florist','normal'),
+ (1106, 'DavidCharlesHaller', '53136686Q', 'LEGION', 'Charles Xavier', 'CITY OF NEW YORK, NEW YORK, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'DavidCharlesHaller@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 0, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, 19, 0, 'florist','normal'),
+ (1107, 'Hank Pym', '09854837G', 'ANT MAN', 'Hawk', 'ANTHILL, SAN FRANCISCO, CALIFORNIA', 'Gotham', 46460, 1111111111, 222222222, 1, 'HankPym@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 0, 0, NULL, 0, 0, 19, 0, 'florist','normal'),
+ (1108, 'Charles Xavier', '22641921P', 'PROFESSOR X', 'Beast', '3800 VICTORY PKWY, CINCINNATI, OH 45207, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'CharlesXavier@mydomain.com', NULL, 0, 1234567890, 0, 5, 1, 300, 13, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, NULL, 0, 0, 19, 0, 'florist','normal'),
+ (1109, 'Bruce Banner', '16104829E', 'HULK', 'Black widow', 'SOMEWHERE IN NEW YORK', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceBanner@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 0, 0, NULL, 0, 0, 9, 0, 'florist','normal'),
+ (1110, 'Jessica Jones', '58282869H', 'JESSICA JONES', 'Luke Cage', 'NYCC 2015 POSTER', 'Gotham', 46460, 1111111111, 222222222, 1, 'JessicaJones@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, NULL, 1, 'florist','normal'),
+ (1111, 'Missing', NULL, 'MISSING MAN', 'Anton', 'THE SPACE, UNIVERSE FAR AWAY', 'Gotham', 46460, 1111111111, 222222222, 0, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 0, 1, 0, NULL, 1, 0, NULL, 0, 'others','loses'),
+ (1112, 'Trash', NULL, 'GARBAGE MAN', 'Unknown name', 'NEW YORK CITY, UNDERGROUND', 'Gotham', 46460, 1111111111, 222222222, 0, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 0, 1, 0, NULL, 1, 0, NULL, 0, 'others','loses');
-INSERT INTO `vn`.`client`(`id`, `name`, `fi`, `socialName`, `contact`, `street`, `city`, `postcode`, `isRelevant`, `email`, `iban`,`dueDay`,`accountingAccount`, `isEqualizated`, `provinceFk`, `hasToInvoice`, `credit`, `countryFk`, `isActive`, `gestdocFk`, `quality`, `payMethodFk`,`created`, `isTaxDataChecked`)
- SELECT id, name, CONCAT(RPAD(CONCAT(id,9),8,id),'A'), UPPER(CONCAT(name, 'Social')), CONCAT(name, 'Contact'), CONCAT(name, 'Street'), 'GOTHAM', 46460, 1, CONCAT(name,'@mydomain.com'), NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5, util.VN_CURDATE(), 1
+INSERT INTO `vn`.`client`(`id`, `name`, `fi`, `socialName`, `contact`, `street`, `city`, `postcode`, `isRelevant`, `email`, `iban`,`dueDay`,`accountingAccount`, `isEqualizated`, `provinceFk`, `hasToInvoice`, `credit`, `countryFk`, `isActive`, `quality`, `payMethodFk`,`created`, `isTaxDataChecked`)
+ SELECT id, name, CONCAT(RPAD(CONCAT(id,9),8,id),'A'), UPPER(CONCAT(name, 'Social')), CONCAT(name, 'Contact'), UPPER(CONCAT(name, 'Street')), 'GOTHAM', 46460, 0, CONCAT(name,'@mydomain.com'), NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1
FROM `account`.`role` `r`
WHERE `r`.`hasLogin` = 1;
@@ -427,10 +428,10 @@ INSERT INTO `vn`.`clientConfig`(`id`, `riskTolerance`, `maxCreditRows`, `maxPric
INSERT INTO `vn`.`address`(`id`, `nickname`, `street`, `city`, `postalCode`, `provinceFk`, `phone`, `mobile`, `isActive`, `clientFk`, `agencyModeFk`, `longitude`, `latitude`, `isEqualizated`, `isDefaultAddress`, `customsAgentFk`)
VALUES
- (1, 'Bruce Wayne', '1007 Mountain Drive, Gotham', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1101, 2, NULL, NULL, 0, 1, 1),
- (2, 'Petter Parker', '20 Ingram Street', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1102, 2, NULL, NULL, 0, 1, NULL),
- (3, 'Clark Kent', '344 Clinton Street', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1103, 2, NULL, NULL, 0, 1, NULL),
- (4, 'Tony Stark', '10880 Malibu Point', 'Gotham', 46460, 1, 1111111111, 222222222, 1 , 1104, 2, NULL, NULL, 0, 1, NULL),
+ (1, 'Bruce Wayne', '1007 Mountain Drive, Gotham', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1101, 2, -74.1111111, 10.1111111, 0, 1, 1),
+ (2, 'Petter Parker', '20 Ingram Street', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1102, 2, -74.2222222, 10.2222222, 0, 1, NULL),
+ (3, 'Clark Kent', '344 Clinton Street', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1103, 2, -74.3333333, 10.3333333, 0, 1, NULL),
+ (4, 'Tony Stark', '10880 Malibu Point', 'Gotham', 46460, 1, 1111111111, 222222222, 1 , 1104, 2, -74.4444444, 10.4444444, 0, 1, NULL),
(5, 'Max Eisenhardt', 'Unknown Whereabouts', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1105, 2, NULL, NULL, 0, 1, NULL),
(6, 'DavidCharlesHaller', 'Evil hideout', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1106, 2, NULL, NULL, 0, 1, NULL),
(7, 'Hank Pym', 'Anthill', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1107, 2, NULL, NULL, 0, 1, NULL),
@@ -461,7 +462,7 @@ INSERT INTO `vn`.`address`(`id`, `nickname`, `street`, `city`, `postalCode`, `pr
(120, 'Somewhere in Montortal', 'address 20', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1109, 2, NULL, NULL, 0, 0, NULL),
(121, 'the bat cave', 'address 21', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1101, 2, NULL, NULL, 0, 0, NULL),
(122, 'NY roofs', 'address 22', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1102, 2, NULL, NULL, 0, 0, NULL),
- (123, 'The phone box', 'address 23', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1103, 2, NULL, NULL, 0, 0, NULL),
+ (123, 'The phone box', 'address 23', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1103, 2, -74.555555, 10.555555, 0, 0, NULL),
(124, 'Stark tower Gotham', 'address 24', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1104, 2, NULL, NULL, 0, 0, NULL),
(125, 'The plastic cell', 'address 25', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1105, 2, NULL, NULL, 0, 0, NULL),
(126, 'Many places', 'address 26', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1106, 2, NULL, NULL, 0, 0, NULL),
@@ -545,7 +546,8 @@ INSERT INTO `vn`.`observationType`(`id`,`description`, `code`)
(6, 'Weight', 'weight'),
(7, 'InvoiceOut', 'invoiceOut'),
(8, 'DropOff', 'dropOff'),
- (9, 'Sustitución', 'substitution');
+ (9, 'Sustitución', 'substitution'),
+ (10, 'Finance', 'finance');
INSERT INTO `vn`.`addressObservation`(`id`,`addressFk`,`observationTypeFk`,`description`)
VALUES
@@ -630,14 +632,21 @@ INSERT INTO vn.invoiceOutConfig
SET id = 1,
parallelism = 8;
-INSERT INTO `vn`.`invoiceOutSerial` (`code`, `description`, `isTaxed`, `taxAreaFk`, `isCEE`, `type`)
+INSERT INTO `vn`.`invoiceOutSerial`
+ (`code`,`description`, `isTaxed`, `taxAreaFk`, `isCEE`, `type`)
VALUES
- ('A', 'Global nacional', 1, 'NATIONAL', 0, 'global'),
- ('T', 'Española rapida', 1, 'NATIONAL', 0, 'quick'),
- ('V', 'Intracomunitaria global', 0, 'CEE', 1, 'global'),
- ('M', 'Múltiple nacional', 1, 'NATIONAL', 0, 'multiple'),
- ('R', 'Rectificativa', 1, 'NATIONAL', 0, NULL),
- ('E', 'Exportación rápida', 0, 'WORLD', 0, 'quick');
+ ('A', 'Global nacional', 1, 'NATIONAL', 0, 'global'),
+ ('T', 'Española rapida', 1, 'NATIONAL', 0, 'quick'),
+ ('V', 'Intracomunitaria global', 0, 'CEE', 1, 'global'),
+ ('M', 'Múltiple nacional', 1, 'NATIONAL', 0, 'multiple'),
+ ('R', 'Rectificativa', 1, 'NATIONAL', 0, NULL),
+ ('E', 'Exportación rápida', 0, 'WORLD', 0, 'quick'),
+ ('H', 'Intracomunitaria rápida', 0, 'CEE', 1, 'quick'),
+ ('P', 'Factura simplificada', 1, 'NATIONAL', 0, NULL),
+ ('PE', 'COOPERATIE FLORAHOLLAND UA', 0, 'CEE', 1, NULL),
+ ('S', 'Simplificada', 1, 'NATIONAL', 0, NULL),
+ ('X', 'Exportación global', 0, 'WORLD', 0, 'global'),
+ ('N', 'Múltiple Intracomunitaria', 0, 'CEE', 1, 'multiple');
INSERT INTO `vn`.`invoiceOut`(`id`, `serial`, `amount`, `issued`,`clientFk`, `created`, `companyFk`, `dued`, `booked`, `bankFk`, `hasPdf`, `customsAgentFk`, `incotermsFk`)
VALUES
@@ -736,15 +745,15 @@ INSERT INTO `vn`.`zoneClosure` (`zoneFk`, `dated`, `hour`)
INSERT INTO `vn`.`zoneConfig` (`id`, `scope`) VALUES (1, '1');
-INSERT INTO `vn`.`route`(`id`, `time`, `workerFk`, `created`, `vehicleFk`, `agencyModeFk`, `description`, `m3`, `cost`, `started`, `finished`, `zoneFk`)
+INSERT INTO `vn`.`route`(`id`, `time`, `workerFk`, `created`, `vehicleFk`, `agencyModeFk`, `description`, `m3`, `cost`, `started`, `finished`, `zoneFk`, `dated`)
VALUES
- (1, '1899-12-30 12:15:00', 56, util.VN_CURDATE(), 1, 1, 'first route', 1.8, 10, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1),
- (2, '1899-12-30 13:20:00', 56, util.VN_CURDATE(), 1, 2, 'second route', 0.2, 20, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 9),
- (3, '1899-12-30 14:30:00', 56, util.VN_CURDATE(), 2, 3, 'third route', 0.5, 30, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 10),
- (4, '1899-12-30 15:45:00', 56, util.VN_CURDATE(), 3, 4, 'fourth route', 0, 40, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 12),
- (5, '1899-12-30 16:00:00', 56, util.VN_CURDATE(), 4, 5, 'fifth route', 0.1, 50, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 13),
- (6, NULL, 57, util.VN_CURDATE(), 5, 7, 'sixth route', 1.7, 60, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 3),
- (7, NULL, 57, util.VN_CURDATE(), 6, 8, 'seventh route', 0, 70, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 5);
+ (1, '1899-12-30 12:15:00', 56, util.VN_CURDATE(), 1, 1, 'first route', 1.8, 10, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1, util.VN_CURDATE()),
+ (2, '1899-12-30 13:20:00', 56, util.VN_CURDATE(), 1, 2, 'second route', 0.2, 20, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 9, util.VN_CURDATE()),
+ (3, '1899-12-30 14:30:00', 56, util.VN_CURDATE(), 2, 3, 'third route', 0.5, 30, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 10, util.VN_CURDATE()),
+ (4, '1899-12-30 15:45:00', 56, util.VN_CURDATE(), 3, 4, 'fourth route', 0, 40, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 12, util.VN_CURDATE()),
+ (5, '1899-12-30 16:00:00', 56, util.VN_CURDATE(), 4, 5, 'fifth route', 0.1, 50, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 13, util.VN_CURDATE()),
+ (6, NULL, 57, util.VN_CURDATE(), 5, 7, 'sixth route', 1.7, 60, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 3, util.VN_CURDATE()),
+ (7, NULL, 57, util.VN_CURDATE(), 6, 8, 'seventh route', 0, 70, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 5, util.VN_CURDATE());
INSERT INTO `vn`.`ticket`(`id`, `priority`, `agencyModeFk`,`warehouseFk`,`routeFk`, `shipped`, `landed`, `clientFk`,`nickname`, `addressFk`, `refFk`, `isDeleted`, `zoneFk`, `zonePrice`, `zoneBonus`, `created`, `weight`, `cmrFk`, `problem`, `risk`)
VALUES
@@ -965,26 +974,30 @@ INSERT INTO `vn`.`itemFamily`(`code`, `description`)
('SER', 'Services'),
('VT', 'Sales');
-INSERT INTO `vn`.`item`(`id`, `typeFk`, `stems`, `originFk`, `description`, `producerFk`, `intrastatFk`, `expenseFk`,
- `comment`, `relevancy`, `image`, `subName`, `minPrice`, `family`, `isFloramondo`, `genericFk`, `itemPackingTypeFk`, `hasMinPrice`, `weightByPiece`)
- VALUES
- (1, 2, 1, 1, NULL, 1, 06021010, 2000000000, NULL, 0, '1', NULL, 0, 'EMB', 0, NULL, 'V', 0, 3),
- (2, 2, 1, 2, NULL, 1, 06021010, 2000000000, NULL, 0, '2', NULL, 0, 'VT', 0, NULL, 'H', 0, 2),
- (3, 1, 1, 3, NULL, 1, 05080000, 4751000000, NULL, 0, '3', NULL, 0, 'VT', 0, NULL, NULL, 0, 5),
- (4, 1, 1, 1, 'Increases block', 1, 05080000, 4751000000, NULL, 0, '4', NULL, 0, 'VT', 0, NULL, NULL, 0, NULL),
- (5, 3, 1, 2, NULL, 2, 06021010, 4751000000, NULL, 0, '5', NULL, 0, 'VT', 0, NULL, NULL, 0, NULL),
- (6, 5, 1, 2, NULL, NULL, 06021010, 4751000000, NULL, 0, '6', NULL, 0, 'VT', 0, NULL, NULL, 0, NULL),
- (7, 5, 1, 2, NULL, NULL, 06021010, 4751000000, NULL, 0, '7', NULL, 0, 'VT', 0, NULL, NULL, 0, NULL),
- (8, 2, 1, 1, NULL, 1, 06021010, 2000000000, NULL, 0, '8', NULL, 0, 'VT', 0, NULL, NULL, 0, NULL),
- (9, 2, 1, 2, NULL, 1, 06021010, 2000000000, NULL, 0, '9', NULL, 0, 'VT', 1, NULL, NULL, 0, NULL),
- (10, 1, 1, 3, NULL, 1, 05080000, 4751000000, NULL, 0, '10', NULL, 0, 'VT', 0, NULL, NULL, 0, NULL),
- (11, 1, 1, 1, NULL, 1, 05080000, 4751000000, NULL, 0, '11', NULL, 0, 'VT', 0, NULL, NULL, 0, NULL),
- (12, 3, 1, 2, NULL, 2, 06021010, 4751000000, NULL, 0, '12', NULL, 0, 'VT', 0, NULL, NULL, 0, NULL),
- (13, 5, 1, 2, NULL, NULL, 06021010, 4751000000, NULL, 0, '13', NULL, 1, 'VT', 1, NULL, NULL, 1, NULL),
- (14, 5, 1, 2, NULL, NULL, 06021010, 4751000000, NULL, 0, '', NULL, 0, 'VT', 1, NULL, NULL, 0, NULL),
- (15, 4, NULL, 1, NULL, NULL, 06021010, 4751000000, NULL, 0, '', NULL, 0, 'EMB', 0, NULL, NULL, 0, NULL),
- (16, 6, NULL, 1, NULL, NULL, 06021010, 4751000000, NULL, 0, '', NULL, 0, 'EMB', 0, NULL, NULL, 0, NULL),
- (71, 6, NULL, 1, NULL, NULL, 06021010, 4751000000, NULL, 0, '', NULL, 0, 'VT', 0, NULL, NULL, 0, NULL);
+INSERT INTO `vn`.`item`(
+ `id`, `typeFk`, `stems`, `originFk`, `description`, `producerFk`, `intrastatFk`, `expenseFk`,
+ `comment`, `relevancy`, `image`, `subName`, `minPrice`, `family`, `isFloramondo`, `genericFk`,
+ `itemPackingTypeFk`, `hasMinPrice`, `weightByPiece`, `isCustomInspectionRequired`
+)
+VALUES
+ (1, 2, 1, 1, NULL, 1, 06021010, 2000000000, NULL, 0, '1', NULL, 0, 'EMB', 0, NULL, 'V', 0, 3, 1),
+ (2, 2, 1, 2, NULL, 1, 06021010, 2000000000, NULL, 0, '2', NULL, 0, 'VT', 0, NULL, 'H', 0, 2, 1),
+ (3, 1, 1, 3, NULL, 1, 05080000, 4751000000, NULL, 0, '3', NULL, 0, 'VT', 0, NULL, NULL, 0, 5, 0),
+ (4, 1, 1, 1, 'Increases block', 1, 05080000, 4751000000, NULL, 0, '4', NULL, 0, 'VT', 0, NULL, NULL, 0, NULL, 0),
+ (5, 3, 1, 2, NULL, 2, 06021010, 4751000000, NULL, 0, '5', NULL, 0, 'VT', 0, NULL, NULL, 0, NULL, 0),
+ (6, 5, 1, 2, NULL, NULL, 06021010, 4751000000, NULL, 0, '6', NULL, 0, 'VT', 0, NULL, NULL, 0, NULL, 0),
+ (7, 5, 1, 2, NULL, NULL, 06021010, 4751000000, NULL, 0, '7', NULL, 0, 'VT', 0, NULL, NULL, 0, NULL, 0),
+ (8, 2, 1, 1, NULL, 1, 06021010, 2000000000, NULL, 0, '8', NULL, 0, 'VT', 0, NULL, NULL, 0, NULL, 0),
+ (9, 2, 1, 2, NULL, 1, 06021010, 2000000000, NULL, 0, '9', NULL, 0, 'VT', 1, NULL, NULL, 0, NULL, 0),
+ (10, 1, 1, 3, NULL, 1, 05080000, 4751000000, NULL, 0, '10', NULL, 0, 'VT', 0, NULL, NULL, 0, NULL, 0),
+ (11, 1, 1, 1, NULL, 1, 05080000, 4751000000, NULL, 0, '11', NULL, 0, 'VT', 0, NULL, NULL, 0, NULL, 0),
+ (12, 3, 1, 2, NULL, 2, 06021010, 4751000000, NULL, 0, '12', NULL, 0, 'VT', 0, NULL, NULL, 0, NULL, 0),
+ (13, 5, 1, 2, NULL, NULL, 06021010, 4751000000, NULL, 0, '13', NULL, 1, 'VT', 1, NULL, NULL, 1, NULL, 0),
+ (14, 5, 1, 2, NULL, NULL, 06021010, 4751000000, NULL, 0, '', NULL, 0, 'VT', 1, NULL, NULL, 0, NULL, 0),
+ (15, 4, NULL, 1, NULL, NULL, 06021010, 4751000000, NULL, 0, '', NULL, 0, 'EMB', 0, NULL, NULL, 0, NULL, 0),
+ (16, 6, NULL, 1, NULL, NULL, 06021010, 4751000000, NULL, 0, '', NULL, 0, 'EMB', 0, NULL, NULL, 0, NULL, 0),
+ (71, 6, NULL, 1, NULL, NULL, 06021010, 4751000000, NULL, 0, '', NULL, 0, 'VT', 0, NULL, NULL, 0, NULL, 0);
+
-- Update the taxClass after insert of the items
UPDATE `vn`.`itemTaxCountry` SET `taxClassFk` = 2
@@ -1245,9 +1258,9 @@ INSERT INTO `vn`.`saleComponent`(`saleFk`, `componentFk`, `value`)
INSERT INTO `vn`.`itemShelving` (`itemFk`, `shelvingFk`, `visible`, `grouping`, `packing`,`buyFk`, `userFk`)
VALUES
- (2, 'GVC', 1, 1, 1, 2,1106),
- (4, 'HEJ', 1, 1, 1, NULL,1106),
- (1, 'UXN', 2, 12, 12, NULL,1106);
+ (2, 11, 1, 1, 1, 2,1106),
+ (4, 12, 1, 1, 1, NULL,1106),
+ (1, 13, 2, 12, 12, NULL,1106);
INSERT INTO `vn`.`itemShelvingSale` (`itemShelvingFk`, `saleFk`, `quantity`, `created`, `userFk`)
VALUES
@@ -1496,32 +1509,33 @@ INSERT INTO `vn`.`awb` (id, code, package, weight, created, amount, transitoryFk
(9, '99610289193', 302, 2972, util.VN_CURDATE(), 3871, 442, 1),
(10, '07546500856', 185, 2364, util.VN_CURDATE(), 5321, 442, 1);
-INSERT INTO `vn`.`travel`(`id`,`shipped`, `landed`, `warehouseInFk`, `warehouseOutFk`, `agencyModeFk`, `m3`, `kg`,`ref`, `totalEntries`, `cargoSupplierFk`, `awbFK`)
- VALUES (1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), 1, 2, 1, 100.00, 1000, 'first travel', 1, 1, 1),
- (2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 2, 1, 150.00, 2000, 'second travel', 2, 2, 2),
- (3, util.VN_CURDATE(), util.VN_CURDATE(), 1, 2, 1, 0.00, 0.00, 'third travel', 1, 1, 3),
- (4, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 3, 1, 50.00, 500, 'fourth travel', 0, 2, 4),
- (5, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 3, 3, 1, 50.00, 500, 'fifth travel', 1, 1, 5),
- (6, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 4, 4, 1, 50.00, 500, 'sixth travel', 1, 2, 6),
- (7, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 4, 1, 50.00, 500, 'seventh travel', 2, 1, 7),
- (8, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 1, 1, 50.00, 500, 'eight travel', 1, 2, 10),
- (10, DATE_ADD(util.VN_CURDATE(), INTERVAL +5 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL +5 DAY), 5, 1, 1, 50.00, 500, 'nineth travel', 1, 2, 10),
- (11, util.VN_CURDATE() - INTERVAL 1 DAY , util.VN_CURDATE(), 6, 3, 0, 50.00, 500, 'eleventh travel', 1, 2, 4),
- (12, util.VN_CURDATE() , util.VN_CURDATE() + INTERVAL 1 DAY, 6, 3, 0, 50.00, 500, 'eleventh travel', 1, 2, 4);
+INSERT INTO `vn`.`travel`(`id`,`shipped`, `landed`, `warehouseInFk`, `warehouseOutFk`, `agencyModeFk`, `m3`, `kg`,`ref`, `totalEntries`, `cargoSupplierFk`, `awbFK`, `isRaid`, `daysInForward`)
+ VALUES (1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), 1, 2, 1, 100.00, 1000, 'first travel', 1, 1, 1, FALSE, NULL),
+ (2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 2, 1, 150.00, 2000, 'second travel', 2, 2, 2, FALSE, NULL),
+ (3, util.VN_CURDATE(), util.VN_CURDATE(), 1, 2, 1, 0.00, 0.00, 'third travel', 1, 1, 3, FALSE, NULL),
+ (4, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 3, 1, 50.00, 500, 'fourth travel', 0, 2, 4, FALSE, NULL),
+ (5, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 3, 3, 1, 50.00, 500, 'fifth travel', 1, 1, 5, FALSE, NULL),
+ (6, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 4, 4, 1, 50.00, 500, 'sixth travel', 1, 2, 6, FALSE,NULL),
+ (7, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 4, 1, 50.00, 500, 'seventh travel', 2, 1, 7, TRUE, 2),
+ (8, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 1, 1, 50.00, 500, 'eight travel', 1, 2, 10, FALSE, NULL),
+ (10, DATE_ADD(util.VN_CURDATE(), INTERVAL +5 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL +5 DAY), 5, 1, 1, 50.00, 500, 'nineth travel', 1, 2, 10, TRUE, 2),
+ (11, util.VN_CURDATE() - INTERVAL 1 DAY , util.VN_CURDATE(), 6, 3, 0, 50.00, 500, 'eleventh travel', 1, 2, 4, FALSE, NULL),
+ (12, util.VN_CURDATE() , util.VN_CURDATE() + INTERVAL 1 DAY, 6, 3, 0, 50.00, 500, 'eleventh travel', 1, 2, 4, FALSE, NULL);
-INSERT INTO `vn`.`entry`(`id`, `supplierFk`, `created`, `travelFk`, `isConfirmed`, `companyFk`, `invoiceNumber`, `reference`, `isExcludedFromAvailable`, `isRaid`, `evaNotes`)
- VALUES
- (1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 1, 442, 'IN2001', 'Movement 1', 0, 0, ''),
- (2, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2, 0, 442, 'IN2002', 'Movement 2', 0, 0, 'observation two'),
- (3, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 3, 0, 442, 'IN2003', 'Movement 3', 0, 0, 'observation three'),
- (4, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2, 0, 69, 'IN2004', 'Movement 4', 0, 0, 'observation four'),
- (5, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 0, 442, 'IN2005', 'Movement 5', 0, 0, 'observation five'),
- (6, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 6, 0, 442, 'IN2006', 'Movement 6', 0, 0, 'observation six'),
- (7, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2007', 'Movement 7', 0, 0, 'observation seven'),
- (8, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2008', 'Movement 8', 1, 1, ''),
- (9, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL +2 DAY), 10, 0, 442, 'IN2009', 'Movement 9', 1, 1, ''),
- (10, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL +2 DAY), 10, 0, 442, 'IN2009', 'Movement 10', 1, 1, ''),
- (99, 69, '2000-12-01 00:00:00.000', 11, 0, 442, 'IN2009', 'Movement 99', 0, 0, '');
+INSERT INTO `vn`.`entry`(`id`, `supplierFk`, `created`, `travelFk`, `isConfirmed`, `companyFk`, `invoiceNumber`, `reference`, `isExcludedFromAvailable`, `evaNotes`, `typeFk`)
+ VALUES
+ (1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 1, 442, 'IN2001', 'Movement 1', 0, '', 'packaging'),
+ (2, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2, 0, 442, 'IN2002', 'Movement 2', 0, 'observation two' , 'product'),
+ (3, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 3, 0, 442, 'IN2003', 'Movement 3', 0, 'observation three', 'product'),
+ (4, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2, 0, 69, 'IN2004', 'Movement 4', 0, 'observation four' , 'product'),
+ (5, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 0, 442, 'IN2005', 'Movement 5', 0, 'observation five' , 'product'),
+ (6, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 6, 0, 442, 'IN2006', 'Movement 6', 0, 'observation six' , 'product'),
+ (7, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2007', 'Movement 7', 0, 'observation seven', 'product'),
+ (8, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2008', 'Movement 8', 1, '', 'product'),
+ (9, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL +2 DAY), 10, 0, 442, 'IN2009', 'Movement 9', 1, '', 'product'),
+ (10, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL +2 DAY), 10, 0, 442, 'IN2009', 'Movement 10',1, '', 'product'),
+ (11, 4, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 1, 442, 'IN2001', 'Movement 11',0, '', 'product'),
+ (99, 69, util.VN_CURDATE() - INTERVAL 1 MONTH, 11, 0, 442, 'IN2009', 'Movement 99',0, '', 'product');
INSERT INTO `vn`.`entryConfig` (`defaultEntry`, `inventorySupplierFk`, `defaultSupplierFk`)
VALUES (2, 4, 1);
@@ -1561,7 +1575,8 @@ INSERT INTO `bs`.`waste`(`buyerFk`, `year`, `week`, `itemFk`, `itemTypeFk`, `sal
(13, 7, 1, 50, 0, 3, 1, 2.000, 2.000, 0.000, 1, 1, 'packing', NULL, 0.00, 99.6, 99.4, 0, 1, 0, 4, util.VN_CURDATE()),
(14, 7, 2, 5, 0, 3, 1, 2.000, 2.000, 0.000, 10, 10, 'grouping', NULL, 0.00, 7.30, 7.00, 0, 1, 0, 4, util.VN_CURDATE()),
(15, 7, 4, 1.25, 0, 3, 1, 2.000, 2.000, 0.000, 10, 10, 'grouping', NULL, 0.00, 1.75, 1.67, 0, 1, 0, 4, util.VN_CURDATE()),
- (16, 99,1,50.0000, 5000, 4, 1, 1.500, 1.500, 0.000, 1, 1, 'packing', NULL, 0.00, 99.60, 99.40, 0, 1, 0, 1.00, '2024-07-30 08:13:51.000');
+ (16, 99,1,50.0000, 5000, 4, 1, 1.500, 1.500, 0.000, 1, 1, 'packing', NULL, 0.00, 99.60, 99.40, 0, 1, 0, 1.00, '2024-07-30 08:13:51.000'),
+ (17, 11, 1, 50, 5000, 4, 1, 1.500, 1.500, 0.000, 1, 1, 'packing', NULL, 0.00, 99.6, 99.4, 0, 1, 0, 1, util.VN_CURDATE() - INTERVAL 2 MONTH);
INSERT INTO `hedera`.`order`(`id`, `date_send`, `customer_id`, `delivery_method_id`, `agency_id`, `address_id`, `company_id`, `note`, `source_app`, `confirmed`,`total`, `date_make`, `first_row_stamp`, `confirm_date`)
VALUES
@@ -1911,7 +1926,7 @@ INSERT INTO `vn`.`claimDestination`(`id`, `description`, `addressFk`)
INSERT INTO `vn`.`claimDevelopment`(`id`, `claimFk`, `claimResponsibleFk`, `workerFk`, `claimReasonFk`, `claimResultFk`, `claimRedeliveryFk`, `claimDestinationFk`)
VALUES
- (1, 1, 1, 21, 1, 1, 2, 5),
+ (1, 1, 1, 21, 7, 1, 2, 5),
(2, 1, 2, 21, 7, 2, 2, 5),
(3, 2, 7, 21, 9, 3, 2, 5),
(4, 3, 7, 21, 15, 8, 2, 5),
@@ -2031,7 +2046,7 @@ INSERT INTO `vn`.`ticketService`(`id`, `description`, `quantity`, `price`, `taxC
INSERT INTO `pbx`.`config` (id,defaultPrefix)
VALUES (1,'0034');
-INSERT INTO `pbx`.`prefix` (country, prefix)
+INSERT IGNORE INTO `pbx`.`prefix` (country, prefix)
VALUES
('es', '0034'),
('fr', '0033'),
@@ -2445,7 +2460,7 @@ INSERT INTO `vn`.`workerTimeControl`(`userFk`, `timed`, `manual`, `direction`, `
INSERT INTO `vn`.`dmsType`
(`id`, `name`, `readRoleFk`, `writeRoleFk`, `code`)
VALUES
- (1, 'Facturas Recibidas', NULL, NULL, 'invoiceIn'),
+ (1, 'Facturas Recibidas', 1, 1, 'invoiceIn'),
(2, 'Doc oficial', NULL, NULL, 'officialDoc'),
(3, 'Laboral', 37, 37, 'hhrrData'),
(4, 'Albaranes recibidos', NULL, NULL, 'deliveryNote'),
@@ -2467,7 +2482,8 @@ INSERT INTO `vn`.`dmsType`
(20, 'Reclamación', 1, 1, 'claim'),
(21, 'Entrada', 1, 1, 'entry'),
(22, 'Proveedor', 1, 1, 'supplier'),
- (23, 'Termografos', 35, 35, 'thermograph');
+ (23, 'Termografos', 35, 35, 'thermograph'),
+ (24, 'Sello de calidad', 1, 1, 'qualitySeal');
INSERT INTO `vn`.`dms`(`id`, `dmsTypeFk`, `file`, `contentType`, `workerFk`, `warehouseFk`, `companyFk`, `hardCopyNumber`, `hasFile`, `reference`, `description`, `created`)
VALUES
@@ -2511,10 +2527,6 @@ INSERT INTO `vn`.`queuePriority`(`id`, `priority`, `code`)
(2, 'Normal', 'normal'),
(3, 'Baja', 'low');
-INSERT INTO `vn`.`workerTimeControlParams` (`id`, `dayBreak`, `weekBreak`, `weekScope`, `dayWorkMax`, `dayStayMax`, `weekMaxBreak`, `weekMaxScope`, `askInOut`)
- VALUES
- (1, 43200, 129600, 734400, 43200, 50400, 259200, 1296000, 36000);
-
INSERT IGNORE INTO `vn`.`greugeConfig` (`id`, `freightPickUpPrice`) VALUES ('1', '11');
INSERT INTO `vn`.`thermograph`(`id`, `model`)
@@ -2833,12 +2845,6 @@ INSERT INTO `vn`.`machine` (`plate`, `maker`, `model`, `warehouseFk`, `departmen
('RE-001', 'STILL', 'LTX-20', 60, 23, 'ELECTRIC TOW', 'Drag cars', 2020, 103, 442),
('RE-002', 'STILL', 'LTX-20', 60, 23, 'ELECTRIC TOW', 'Drag cars', 2020, 103, 442);
-INSERT INTO `vn`.`machineWorker` (`workerFk`, `machineFk`, `inTimed`, `outTimed`)
- VALUES
- (1106, 1, util.VN_CURDATE(), util.VN_CURDATE()),
- (1106, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL +1 DAY)),
- (1106, 2, util.VN_CURDATE(), NULL),
- (1106, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL +1 DAY));
INSERT INTO `vn`.`zoneExclusion` (`id`, `zoneFk`, `dated`, `created`, `userFk`)
VALUES
@@ -2909,7 +2915,8 @@ INSERT INTO `util`.`notification` (`id`, `name`, `description`)
(6, 'book-entry-deleted', 'accounting entries deleted'),
(7, 'zone-included','An email to notify zoneCollisions'),
(8, 'backup-printer-selected','A backup printer has been selected'),
- (9, 'mrw-deadline','The MRW deadline has passed');
+ (9, 'mrw-deadline','The MRW deadline has passed'),
+ (10,'invoice-ticket-closure','Tickets not invoiced during the nightly closure ticket process');
TRUNCATE `util`.`notificationAcl`;
INSERT INTO `util`.`notificationAcl` (`notificationFk`, `roleFk`)
@@ -2950,9 +2957,9 @@ INSERT INTO `vn`.`routeConfig` (`id`, `defaultWorkCenterFk`)
VALUES
(1, 9);
-INSERT INTO `vn`.`productionConfig` (`isPreviousPreparationRequired`, `ticketPrintedMax`, `ticketTrolleyMax`, `rookieDays`, `notBuyingMonths`, `id`, `isZoneClosedByExpeditionActivated`, `maxNotReadyCollections`, `minTicketsToCloseZone`, `movingTicketDelRoute`, `defaultZone`, `defautlAgencyMode`, `hasUniqueCollectionTime`, `maxCollectionWithoutUser`, `pendingCollectionsOrder`, `pendingCollectionsAge`, `backupPrinterNotificationDelay`)
+INSERT INTO `vn`.`productionConfig` (`isPreviousPreparationRequired`, `ticketPrintedMax`, `ticketTrolleyMax`, `rookieDays`, `notBuyingMonths`, `id`, `isZoneClosedByExpeditionActivated`, `maxNotReadyCollections`, `minTicketsToCloseZone`, `movingTicketDelRoute`, `defaultZone`, `defautlAgencyMode`, `hasUniqueCollectionTime`, `maxCollectionWithoutUser`, `pendingCollectionsOrder`, `pendingCollectionsAge`, `backupPrinterNotificationDelay`, `clientSelfConsumptionFk`, `addressSelfConsumptionFk`)
VALUES
- (0, 8, 80, 0, 0, 1, 0, 15, 25, -1, 697, 1328, 0, 1, 8, 6, 3600);
+ (0, 8, 80, 0, 0, 1, 0, 15, 25, -1, 697, 1328, 0, 1, 8, 6, 3600, 1112, 12);
INSERT INTO `vn`.`collection` (`id`, `created`, `workerFk`, `stateFk`, `itemPackingTypeFk`, `saleTotalCount`, `salePickedCount`, `trainFk`, `sectorFk`, `wagons`)
VALUES
@@ -3190,7 +3197,7 @@ UPDATE vn.department
SET workerFk = null;
INSERT INTO vn.packaging
- VALUES('--', 2745600.00, 100.00, 120.00, 220.00, 0.00, 1, '2001-01-01 00:00:00.000', NULL, NULL, NULL, 0.00, 16, 0.00, 0, NULL, 0.00, NULL, NULL, 0, NULL, 0, 0,0);
+ VALUES('--', 2745600.00, 100.00, 120.00, 220.00, 0.00, 1, '2001-01-01 00:00:00.000', NULL, NULL, NULL, 0.00, 16, 0.00, 0, NULL, 0.00, NULL, NULL, 0, NULL, 0, 0,0,1);
INSERT IGNORE INTO vn.intrastat
@@ -3420,7 +3427,7 @@ INSERT INTO vn.buy
INSERT INTO vn.itemShelving
SET id = 9931,
itemFk = 999993,
- shelvingFk = 'NCC',
+ shelvingFk = 16,
visible = 10,
`grouping` = 5,
packing = 10;
@@ -3747,7 +3754,7 @@ INSERT vn.sale
USE vn;
DELETE ish.* FROM vn.itemShelving ish
- JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.shelving sh ON sh.id = ish.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
JOIN vn.sector s ON s.id = p.sectorFk
JOIN vn.warehouse w ON w.id = s.warehouseFk
@@ -3756,22 +3763,23 @@ DELETE ish.* FROM vn.itemShelving ish
INSERT INTO vn.itemShelving
(itemFk, shelvingFk, visible, created, `grouping`, packing, packagingFk, userFk, isChecked)
VALUES
- (999991, 'NAA', 8, '2023-09-20', 1, 20, NULL, 103, NULL),
- (999998, 'NAA', 80, '2023-09-20', 10, 30, NULL, 103, NULL),
- (1000001, 'NAA', 6, '2023-09-20', 3, 50, NULL, 103, NULL),
- (1000000, 'NBB', 50, '2023-09-18', 25, 500, NULL, 103, NULL),
- (999993, 'NBB', 25, '2023-09-18', NULL, 10, NULL, 103, NULL),
- (999999, 'NBB', 30, '2023-09-18', 10, 500, NULL, 103, NULL),
- (999993, 'NCC', 25, '2023-09-20', 5, 10, NULL, 103, NULL),
- (999997, 'NCC', 10, '2023-09-20', NULL, 100, NULL, 103, NULL),
- (999999, 'NCC', 40, '2023-09-20', 10, 500, NULL, 103, NULL),
- (999995, 'NDD', 10, '2023-09-19', NULL, 20, NULL, 103, NULL),
- (999994, 'NDD', 48, '2023-09-19', 4, 20, NULL, 103, NULL),
- (1000001, 'NEE', 6, '2023-09-21', 3, 50, NULL, 103, NULL),
- (999992, 'NEE', 50, '2023-09-21', NULL, 1, NULL, 103, NULL),
- (1000000, 'NEE', 25, '2023-09-21', 25, 500, NULL, 103, NULL),
- (999996, 'PAA', 5, '2023-09-27', 1, 5, NULL, 103, NULL),
- (999997, 'PCC', 10, '2023-09-27', 5, 100, NULL, 103, NULL);
+ (999991, 14, 8, '2023-09-20', 1, 20, NULL, 103, NULL),
+ (999998, 14, 80, '2023-09-20', 10, 30, NULL, 103, NULL),
+ (1000001, 14, 6, '2023-09-20', 3, 50, NULL, 103, NULL),
+ (1000000, 15, 50, '2023-09-18', 25, 500, NULL, 103, NULL),
+ (999993, 15, 25, '2023-09-18', NULL, 10, NULL, 103, NULL),
+ (999999, 15, 30, '2023-09-18', 10, 500, NULL, 103, NULL),
+ (999993, 16, 25, '2023-09-20', 5, 10, NULL, 103, NULL),
+ (999997, 16, 10, '2023-09-20', NULL, 100, NULL, 103, NULL),
+ (999999, 16, 40, '2023-09-20', 10, 500, NULL, 103, NULL),
+ (999995, 17, 10, '2023-09-19', NULL, 20, NULL, 103, NULL),
+ (999994, 17, 48, '2023-09-19', 4, 20, NULL, 103, NULL),
+ (1000001, 18, 6, '2023-09-21', 3, 50, NULL, 103, NULL),
+ (999992, 18, 50, '2023-09-21', NULL, 1, NULL, 103, NULL),
+ (1000000, 18, 25, '2023-09-21', 25, 500, NULL, 103, NULL),
+ (999996, 19, 5, '2023-09-27', 1, 5, NULL, 103, NULL),
+ (999997, 21, 10, '2023-09-27', 5, 100, NULL, 103, NULL),
+ (1000000, 16, 25, '2023-08-21',25, 500, NULL, NULL, NULL);
-- Previous for Bolas de madera
INSERT IGNORE INTO vn.sectorCollection
@@ -3821,8 +3829,6 @@ UPDATE vn.collection
UPDATE vn.sale
SET isPicked =FALSE;
-INSERT INTO vn.machineWorkerConfig(id, maxHours)
- VALUES(1, 12);
INSERT INTO vn.workerAppTester(workerFk) VALUES(66);
@@ -3830,9 +3836,6 @@ INSERT INTO `vn`.`machine` (`plate`, `maker`, `model`, `warehouseFk`, `departmen
VALUES
('RE-003', 'IRON', 'JPH-24', 60, 23, 'ELECTRIC TOW', 'Drag cars', 2020, 103, 442);
-
-INSERT INTO vn.machineWorker(workerFk,machineFk,inTimed) VALUES (104,1,'2001-01-01 10:00:00.00.000');
-
UPDATE vn.buy SET itemOriginalFk = 1 WHERE id = 1;
UPDATE vn.saleTracking SET stateFk = 26 WHERE id = 5;
@@ -3941,6 +3944,11 @@ INSERT INTO vn.medicalReview
(id, workerFk, centerFk, `date`, `time`, isFit, amount, invoice, remark)
VALUES(3, 9, 2, '2000-01-01', '8:00', 1, 150.0, NULL, NULL);
+INSERT INTO vn.stockBought (workerFk, bought, reserve, dated)
+ VALUES(35, 1.00, 1.00, '2001-01-01');
+INSERT INTO vn.auctionConfig (id,conversionCoefficient,warehouseFk)
+ VALUES (1,0.6,6);
+
INSERT INTO vn.payrollComponent
(id, name, isSalaryAgreed, isVariable, isException)
VALUES
@@ -3961,7 +3969,7 @@ VALUES(1, '');
INSERT INTO dipole.expedition_PrintOut (expeditionFk, ticketFk, addressFk, street, postalCode, city, shopName, isPrinted, created, printerFk, routeFk, parkingCode,
truckName, clientFk, phone, province, agency, m3, workerCode, itemFk, quantity, longName, shelvingFk, comments)
-VALUES(1, 1, 0, ' ', ' ', ' ', ' ', 0, '2001-01-01 00:00:00', 1, 0, ' ', ' ', 0, NULL, '', NULL, 0.000, NULL, 10, NULL, NULL, 'NCC', NULL);
+VALUES(1, 1, 0, ' ', ' ', ' ', ' ', 0, '2001-01-01 00:00:00', 1, 0, ' ', ' ', 0, NULL, '', NULL, 0.000, NULL, 10, NULL, 'Ranged Reinforced weapon sniper rifle 700mm' , 'NCC', NULL);
INSERT INTO vn.accountDetail
(id, value, accountDetailTypeFk, supplierAccountFk)
@@ -3982,3 +3990,66 @@ VALUES
INSERT IGNORE INTO ormConfig
SET id =1,
selectLimit = 1000;
+
+INSERT INTO pbx.queueMultiConfig
+ SET id = 'ring',
+ strategy = 20,
+ timeout = 2,
+ retry = 0,
+ weight = 0,
+ maxLen = 0,
+ ringInUse = 0;
+
+INSERT INTO pbx.queue (description, name, config)
+ VALUES ('X-men', '1000', 1),
+ ('Avengers', '2000', 1);
+
+INSERT IGNORE INTO pbx.queueMember
+ SET queue = '1000',
+ extension = '1010';
+
+UPDATE vn.department SET pbxQueue = '1000' WHERE name = "CAMARA";
+UPDATE vn.department SET pbxQueue = '2000' WHERE name = "VENTAS";
+
+INSERT INTO vn.workerRelatives (workerFk, isDescendant, disabilityGradeFk, birthed, adoptionYear, isDependend, isJointCustody, updated)
+ VALUES
+ (1106, 1, NULL, 0, NULL, 0, 0, '2024-10-29 08:42:44.000');
+INSERT INTO vn.routeAction (id, name, price, isMainlineDelivered) VALUES(1, 'Pintar traje', 50.00, 0);
+INSERT INTO vn.routeComplement (id, dated, workerFk, price, routeActionFk) VALUES(1, util.VN_CURDATE(), 9, 50.00, 1);
+
+
+INSERT INTO srt.buffer (id, x, y, `size`, `length`, stateFk, typeFk, isActive, code, stratus, hasWorkerWaiting, reserve, routeFk, dayMinute, lastUnloaded, hasStrapper, typeDefaultFk, motors, editorFk)
+ VALUES (0, 0, 0, 0, NULL, 3, 1, 0, 'ENT', 0, 0, NULL, NULL, NULL, NULL, 0, 1, 1, NULL),
+ (1, 0, 9900, 0, NULL, 1, 0, 0, 'NOK', 0, 0, NULL, NULL, NULL, NULL, 0, 1, 1, NULL),
+ (2, 0, 0, 450, 13000, 1, 0, 1, '01A', 1, 1, NULL, NULL, NULL, NULL, 0, 1, 1, NULL),
+ (3, 1400, 0, 450, 13000, 1, 0, 1, '01B', 1, 0, NULL, NULL, NULL, NULL, 0, 1, 1, NULL),
+ (4, 0, 500, 500, 13000, 1, 4, 1, '02A', 2, 1, NULL, NULL, NULL, NULL, 1, 4, 13, NULL),
+ (5, 1400, 500, 500, 13000, 1, 4, 1, '02B', 2, 1, NULL, NULL, NULL, NULL, 1, 4, 13, NULL),
+ (6, 0, 1000, 500, 13000, 1, 1, 1, '03A', 3, 0, NULL, NULL, NULL, NULL, 0, 1, 1, NULL),
+ (7, 1400, 1000, 500, 13000, 1, 1, 1, '03B', 3, 0, NULL, NULL, NULL, NULL, 0, 1, 1, NULL),
+ (8, 0, 1500, 500, 13000, 1, 0, 1, '04A', 4, 0, NULL, NULL, NULL, NULL, 0, 1, 1, NULL),
+ (9, 1400, 1500, 500, 13000, 1, 1, 1, '04B', 4, 0, NULL, NULL, NULL, NULL, 0, 1, 1, NULL),
+ (10, 0, 2000, 500, 13000, 1, 1, 1, '05A', 5, 0, NULL, NULL, NULL, NULL, 0, 1, 1, NULL);
+
+INSERT IGNORE INTO vn.saySimpleCountry (countryFk, channel)
+ VALUES (19, '1169'),
+ (8, '1183'),
+ (1, '1320');
+
+INSERT IGNORE INTO vn.saySimpleConfig (url, defaultChannel)
+ VALUES ('saysimle-url-mock', '1819');
+
+INSERT INTO vn.workerIrpf (workerFk,spouseNif, geographicMobilityDate)
+ VALUES (1106,'26493101E','2019-09-20');
+
+INSERT INTO vn.referenceRate (currencyFk, dated, value)
+ VALUES (2, '2000-12-01', 1.0495),
+ (2, '2001-01-01', 1.0531),
+ (2, '2001-02-01', 7.6347);
+
+INSERT IGNORE INTO vn.osrmConfig (id,url,tolerance)
+ VALUES (1,'https://router.project-osrm.org', 0.002);
+
+INSERT IGNORE INTO vn.inventoryConfig
+ SET id = 1,
+ supplierFk = 4;
diff --git a/db/routines/account/views/myUser.sql b/db/routines/account/views/myUser.sql
index f520d893b..8d927dc0f 100644
--- a/db/routines/account/views/myUser.sql
+++ b/db/routines/account/views/myUser.sql
@@ -7,8 +7,7 @@ AS SELECT `u`.`id` AS `id`,
`u`.`email` AS `email`,
`u`.`nickname` AS `nickname`,
`u`.`lang` AS `lang`,
- `u`.`role` AS `role`,
- `u`.`recoverPass` AS `recoverPass`
+ `u`.`role` AS `role`
FROM `account`.`user` `u`
WHERE `u`.`name` = `myUser_getName`()
WITH CASCADED CHECK OPTION
diff --git a/db/routines/bi/procedures/rutasAnalyze.sql b/db/routines/bi/procedures/rutasAnalyze.sql
index e277968bf..1f103bde0 100644
--- a/db/routines/bi/procedures/rutasAnalyze.sql
+++ b/db/routines/bi/procedures/rutasAnalyze.sql
@@ -19,14 +19,14 @@ BEGIN
bultos)
SELECT r.id,
r.agencyModeFk,
- r.created,
+ r.dated,
SUM(sv.volume / ebv.m3)
FROM vn.route r
JOIN vn.ticket t ON t.routeFk = r.id
LEFT JOIN vn.`zone` z ON z.id = t.zoneFk
JOIN vn.saleVolume sv ON sv.ticketFk = t.id
JOIN vn.expeditionBoxVol ebv ON ebv.code = 'transportBox'
- WHERE r.created BETWEEN vDatedFrom AND vDatedTo
+ WHERE r.dated BETWEEN vDatedFrom AND vDatedTo
AND z.isVolumetric
GROUP BY r.id;
@@ -38,12 +38,12 @@ BEGIN
Bultos)
SELECT r.id,
r.agencyModeFk,
- r.created,
+ r.dated,
SUM(t.packages)
FROM vn.route r
JOIN vn.ticket t ON t.routeFk = r.id
LEFT JOIN vn.`zone` z ON z.id = t.zoneFk
- WHERE r.created BETWEEN vDatedFrom AND vDatedTo
+ WHERE r.dated BETWEEN vDatedFrom AND vDatedTo
AND NOT z.isVolumetric
GROUP BY r.id
ON DUPLICATE KEY UPDATE Bultos = Bultos + VALUES(Bultos);
@@ -60,7 +60,7 @@ BEGIN
JOIN vn.component c ON c.id = sc.componentFk
JOIN vn.componentType ct ON ct.id = c.typeFk
WHERE ct.code = 'freight'
- AND r.created BETWEEN vDatedFrom AND vDatedTo
+ AND r.dated BETWEEN vDatedFrom AND vDatedTo
GROUP BY r.id
) sub ON sub.routeFk = r.Id_Ruta
SET r.practico = IFNULL(sub.totalPractice / r.Bultos, 0);
@@ -77,7 +77,7 @@ BEGIN
JOIN vn.address ad ON ad.id = t.addressFk
JOIN vn.client c ON c.id = ad.clientFk
LEFT JOIN vn.`zone` z ON z.id = t.zoneFk
- WHERE r.created BETWEEN vDatedFrom AND vDatedTo
+ WHERE r.dated BETWEEN vDatedFrom AND vDatedTo
AND NOT z.isVolumetric
GROUP BY t.routeFk
) sub ON r.Id_Ruta = sub.routeFk
@@ -93,7 +93,7 @@ BEGIN
JOIN vn.saleVolume sf ON sf.ticketFk = t.id
JOIN vn.client c ON c.id = t.clientFk
JOIN vn.`zone` z ON z.id = t.zoneFk
- WHERE r.created BETWEEN vDatedFrom AND vDatedTo
+ WHERE r.dated BETWEEN vDatedFrom AND vDatedTo
AND z.isVolumetric
GROUP BY t.routeFk
) sub ON r.Id_Ruta = sub.routeFk
@@ -108,7 +108,7 @@ BEGIN
JOIN vn.route r ON r.id = t.routeFk
JOIN vn.greuge g ON g.ticketFk = t.id
JOIN vn.greugeType gt ON gt.id = g.greugeTypeFk
- WHERE r.created BETWEEN vDatedFrom AND vDatedTo
+ WHERE r.dated BETWEEN vDatedFrom AND vDatedTo
AND gt.code = 'freightDifference'
GROUP BY t.routeFk
) sub ON r.Id_Ruta = sub.routeFk
diff --git a/db/routines/bi/views/rotacion.sql b/db/routines/bi/views/rotacion.sql
deleted file mode 100644
index 65a5db923..000000000
--- a/db/routines/bi/views/rotacion.sql
+++ /dev/null
@@ -1,15 +0,0 @@
-CREATE OR REPLACE DEFINER=`root`@`localhost`
- SQL SECURITY DEFINER
- VIEW `bi`.`rotacion`
-AS SELECT `ic`.`itemFk` AS `Id_Article`,
- `ic`.`warehouseFk` AS `warehouse_id`,
- `ic`.`quantity` AS `total`,
- `ic`.`rotation` AS `rotacion`,
- `ic`.`cm3` AS `cm3`,
- `ic`.`storage` AS `almacenaje`,
- `ic`.`handling` AS `manipulacion`,
- `ic`.`extraCharge` AS `auxiliar`,
- `ic`.`wasted` AS `mermas`,
- `ic`.`cm3delivery` AS `cm3reparto`,
- `ic`.`grams` AS `grams`
-FROM `vn`.`itemCost` `ic`
diff --git a/db/routines/bs/procedures/clientNewBorn_recalc.sql b/db/routines/bs/procedures/clientNewBorn_recalc.sql
index 1c89b5745..bb6b02aa7 100644
--- a/db/routines/bs/procedures/clientNewBorn_recalc.sql
+++ b/db/routines/bs/procedures/clientNewBorn_recalc.sql
@@ -6,25 +6,27 @@ BLOCK1: BEGIN
DECLARE vShipped DATE;
DECLARE vPreviousShipped DATE;
DECLARE vDone boolean;
- DECLARE cur cursor for
-
- SELECT clientFk, firstShipped
- FROM bs.clientNewBorn;
+
+ DECLARE cur CURSOR FOR
+ SELECT clientFk, firstShipped
+ FROM bs.clientNewBorn;
DECLARE continue HANDLER FOR NOT FOUND SET vDone = TRUE;
SET vDone := FALSE;
DELETE FROM bs.clientNewBorn WHERE isModified = FALSE;
- INSERT INTO clientNewBorn(clientFk, firstShipped, lastShipped)
- SELECT c.id, MAX(t.shipped), MAX(t.shipped)
- FROM vn.client c
- JOIN vn.ticket t on t.clientFk = c.id
- LEFT JOIN clientNewBorn cb on cb.clientFk = c.id
- WHERE t.shipped BETWEEN TIMESTAMPADD(YEAR, -1, util.VN_CURDATE()) AND util.VN_CURDATE() AND cb.isModified is null
- GROUP BY c.id;
+ INSERT INTO clientNewBorn(clientFk, firstShipped, lastShipped)
+ SELECT c.id, DATE(MAX(t.shipped)), DATE(MAX(t.shipped))
+ FROM vn.client c
+ JOIN vn.ticket t ON t.clientFk = c.id
+ LEFT JOIN clientNewBorn cb ON cb.clientFk = c.id
+ WHERE t.shipped BETWEEN util.VN_CURDATE() - INTERVAL 1 YEAR
+ AND util.VN_CURDATE()
+ AND cb.isModified IS NULL
+ GROUP BY c.id;
+
OPEN cur;
-
LOOP1: LOOP
SET vDone := FALSE;
FETCH cur INTO vClientFk, vShipped;
diff --git a/db/routines/bs/procedures/inventoryDiscrepancyDetail_replace.sql b/db/routines/bs/procedures/inventoryDiscrepancyDetail_replace.sql
index 863005373..b698f0e3e 100644
--- a/db/routines/bs/procedures/inventoryDiscrepancyDetail_replace.sql
+++ b/db/routines/bs/procedures/inventoryDiscrepancyDetail_replace.sql
@@ -32,7 +32,7 @@ BEGIN
CREATE OR REPLACE TEMPORARY TABLE tVisible
SELECT itemFk, SUM(visible) totalVisible
FROM vn.itemShelving ish
- JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.shelving sh ON sh.id = ish.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
JOIN vn.sector sc ON sc.id = p.sectorFk
WHERE sc.warehouseFk = vWarehouseFk
diff --git a/db/routines/cache/procedures/availableNoRaids_refresh.sql b/db/routines/cache/procedures/availableNoRaids_refresh.sql
index 37715d270..447300305 100644
--- a/db/routines/cache/procedures/availableNoRaids_refresh.sql
+++ b/db/routines/cache/procedures/availableNoRaids_refresh.sql
@@ -53,7 +53,7 @@ proc: BEGIN
WHERE t.landed BETWEEN vInventoryDate AND vStartDate
AND t.warehouseInFk = vWarehouse
AND s.name != 'INVENTARIO'
- AND NOT e.isRaid
+ AND NOT t.isRaid
GROUP BY b.itemFk
) c
JOIN vn.item i ON i.id = c.itemFk
diff --git a/db/routines/edi/triggers/supplyResponse_afterUpdate.sql b/db/routines/edi/triggers/supplyResponse_afterUpdate.sql
index 389ef9f1c..f3e5aaefd 100644
--- a/db/routines/edi/triggers/supplyResponse_afterUpdate.sql
+++ b/db/routines/edi/triggers/supplyResponse_afterUpdate.sql
@@ -6,16 +6,16 @@ BEGIN
UPDATE vn.buy b
JOIN vn.entry e ON e.id = b.entryFk
- JOIN vn.travel tr ON tr.id = e.travelFk
- JOIN vn.agencyMode am ON am.id = tr.agencyModeFk
+ JOIN vn.travel tr ON tr.id = e.travelFk
+ JOIN vn.agencyMode am ON am.id = tr.agencyModeFk
JOIN vn.item i ON i.id = b.itemFk
JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID
SET b.quantity = NEW.NumberOfItemsPerCask * NEW.NumberOfUnits,
b.stickers = NEW.NumberOfUnits
WHERE i.supplyResponseFk = NEW.ID
AND am.name = 'LOGIFLORA'
- AND e.isRaid
+ AND tr.isRaid
AND tr.landed >= util.VN_CURDATE();
-
+
END$$
DELIMITER ;
diff --git a/db/routines/hedera/procedures/item_getVisible.sql b/db/routines/hedera/procedures/item_getVisible.sql
index 2f4ef32ab..d5bbe9d76 100644
--- a/db/routines/hedera/procedures/item_getVisible.sql
+++ b/db/routines/hedera/procedures/item_getVisible.sql
@@ -59,7 +59,7 @@ BEGIN
JOIN vn.travel t ON t.id = e.travelFk
WHERE t.landed BETWEEN vDateInv AND vDate
AND t.warehouseInFk = vWarehouse
- AND NOT e.isRaid
+ AND NOT t.isRaid
UNION ALL
SELECT b.itemFk, -b.quantity
FROM vn.buy b
@@ -67,7 +67,7 @@ BEGIN
JOIN vn.travel t ON t.id = e.travelFk
WHERE t.shipped BETWEEN vDateInv AND util.VN_CURDATE()
AND t.warehouseOutFk = vWarehouse
- AND NOT e.isRaid
+ AND NOT t.isRaid
AND t.isDelivered
UNION ALL
SELECT m.itemFk, -m.quantity
diff --git a/db/routines/hedera/procedures/orderRow_updateOverstocking.sql b/db/routines/hedera/procedures/orderRow_updateOverstocking.sql
new file mode 100644
index 000000000..bbfa9432a
--- /dev/null
+++ b/db/routines/hedera/procedures/orderRow_updateOverstocking.sql
@@ -0,0 +1,52 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`vn`@`localhost`
+PROCEDURE `hedera`.`orderRow_updateOverstocking`(vOrderFk INT)
+BEGIN
+/**
+* Set amount = 0 to avoid overbooking sales
+*
+* @param vOrderFk hedera.order.id
+*/
+ DECLARE vCalcFk INT;
+ DECLARE vDone BOOL;
+ DECLARE vWarehouseFk INT;
+
+ DECLARE cWarehouses CURSOR FOR
+ SELECT DISTINCT warehouseFk
+ FROM orderRow
+ WHERE orderFk = vOrderFk
+ AND shipment = util.VN_CURDATE();
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ OPEN cWarehouses;
+ checking: LOOP
+ SET vDone = FALSE;
+
+ FETCH cWarehouses INTO vWarehouseFk;
+
+ IF vDone THEN
+ LEAVE checking;
+ END IF;
+
+ CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, util.VN_CURDATE());
+
+ UPDATE orderRow r
+ JOIN `order` o ON o.id = r.orderFk
+ JOIN orderConfig oc
+ JOIN cache.available a ON a.calc_id = vCalcFk AND a.item_id = r.itemFk
+ SET r.amount = 0
+ WHERE ADDTIME(o.rowUpdated, oc.reserveTime) < util.VN_NOW()
+ AND a.available <= 0
+ AND r.warehouseFk = vWarehouseFk
+ AND r.orderFk = vOrderFk;
+ END LOOP;
+ CLOSE cWarehouses;
+END$$
+DELIMITER ;
diff --git a/db/routines/hedera/procedures/order_confirmWithUser.sql b/db/routines/hedera/procedures/order_confirmWithUser.sql
index 2b033b704..db83cba5c 100644
--- a/db/routines/hedera/procedures/order_confirmWithUser.sql
+++ b/db/routines/hedera/procedures/order_confirmWithUser.sql
@@ -12,6 +12,7 @@ BEGIN
* @param vUser The user identifier
*/
DECLARE vHasRows BOOL;
+ DECLARE vHas0Amount BOOL;
DECLARE vDone BOOL;
DECLARE vWarehouseFk INT;
DECLARE vShipment DATE;
@@ -21,7 +22,6 @@ BEGIN
DECLARE vItemFk INT;
DECLARE vConcept VARCHAR(30);
DECLARE vAmount INT;
- DECLARE vAvailable INT;
DECLARE vPrice DECIMAL(10,2);
DECLARE vSaleFk INT;
DECLARE vRowFk INT;
@@ -31,7 +31,6 @@ BEGIN
DECLARE vClientFk INT;
DECLARE vCompanyFk INT;
DECLARE vAgencyModeFk INT;
- DECLARE vCalcFk INT;
DECLARE vIsTaxDataChecked BOOL;
DECLARE vDates CURSOR FOR
@@ -97,6 +96,20 @@ BEGIN
SELECT employeeFk INTO vUserFk FROM orderConfig;
END IF;
+ CALL orderRow_updateOverstocking(vSelf);
+
+ -- Check if any product has a quantity of 0
+ SELECT EXISTS (
+ SELECT id
+ FROM orderRow
+ WHERE orderFk = vSelf
+ AND amount = 0
+ ) INTO vHas0Amount;
+
+ IF vHas0Amount THEN
+ CALL util.throw('orderLinesWithZero');
+ END IF;
+
START TRANSACTION;
CALL order_checkEditable(vSelf);
diff --git a/db/routines/hedera/procedures/order_getTax.sql b/db/routines/hedera/procedures/order_getTax.sql
index d24ffe7ef..371416c29 100644
--- a/db/routines/hedera/procedures/order_getTax.sql
+++ b/db/routines/hedera/procedures/order_getTax.sql
@@ -9,45 +9,54 @@ BEGIN
* @param vOrder El identificador del pedido
* @return tmp.orderTax Bases imponibles, IVA y recargo de equivalencia
*/
+ -- No poner create or replace, ya que da problemas
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;
+ JOIN `order` o ON o.id = tmpOrder.orderFk;
- CALL vn.addressTaxArea;
+ CALL vn.addressTaxArea();
-- Calcula el IVA y el recargo desglosado.
-
- DROP TEMPORARY TABLE IF EXISTS tmp.orderTax;
- CREATE TEMPORARY TABLE tmp.orderTax
- (INDEX (orderFk))
+ CREATE OR REPLACE TEMPORARY TABLE tmp.orderTax
+ (PRIMARY KEY (orderFk, code, rate))
ENGINE = MEMORY
- SELECT o.id orderFk,
+ WITH orders AS (
+ SELECT tor.orderFk,
+ oro.amount * oro.price total,
+ s.countryFk,
+ ata.areaFk,
+ itc.taxClassFk
+ FROM hedera.orderRow oro
+ JOIN tmp.order tor ON tor.orderFk = oro.orderFk
+ JOIN hedera.`order` o ON o.id = tor.orderFk
+ JOIN vn.item i ON i.id = oro.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
+ HAVING total
+ )
+ SELECT o.orderFk,
tc.code,
- SUM(m.amount * m.price) taxableBase,
+ SUM(o.total) 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
+ FROM orders o
+ JOIN vn.bookingPlanner bp ON bp.countryFk = o.countryFk
+ AND bp.taxAreaFk = o.areaFk
+ AND bp.taxClassFk = o.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;
+ GROUP BY o.orderFk, pgc.code, pgc.rate
+ HAVING taxableBase
+ ORDER BY bp.priority;
+ -- No poner create or replace, ya que da problemas
DROP TEMPORARY TABLE IF EXISTS tmp.orderAmount;
CREATE TEMPORARY TABLE tmp.orderAmount
(INDEX (orderFk))
diff --git a/db/routines/hedera/triggers/orderRow_afterInsert.sql b/db/routines/hedera/triggers/orderRow_afterInsert.sql
new file mode 100644
index 000000000..7196dce10
--- /dev/null
+++ b/db/routines/hedera/triggers/orderRow_afterInsert.sql
@@ -0,0 +1,10 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `hedera`.`orderRow_afterInsert`
+ AFTER INSERT ON `orderRow`
+ FOR EACH ROW
+BEGIN
+ UPDATE `order`
+ SET rowUpdated = util.VN_NOW()
+ WHERE id = NEW.orderFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/sage/procedures/invoiceIn_add.sql b/db/routines/sage/procedures/invoiceIn_add.sql
index 0898d6810..8fdbb9ce3 100644
--- a/db/routines/sage/procedures/invoiceIn_add.sql
+++ b/db/routines/sage/procedures/invoiceIn_add.sql
@@ -4,10 +4,10 @@ BEGIN
/**
* Traslada la info de contabilidad relacionada con las facturas recibidas
*
- * @vInvoiceInFk Factura recibida
- * @vXDiarioFk Id tabla XDiario
+ * @param vInvoiceInFk Factura recibida
+ * @param vXDiarioFk Id tabla XDiario
*/
- DECLARE vInvoiceInOriginalFk INT;
+ DECLARE vInvoiceInOriginalFk INT;
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vBase DOUBLE;
DECLARE vVat DOUBLE;
@@ -25,8 +25,8 @@ BEGIN
DECLARE vIsInformativeExportation BOOL DEFAULT FALSE;
DECLARE vCursor CURSOR FOR
- SELECT it.taxableBase,
- CAST((( it.taxableBase / 100) * t.PorcentajeIva) AS DECIMAL (10,2)),
+ SELECT SUM(it.taxableBase),
+ CAST(SUM((( it.taxableBase / 100) * t.PorcentajeIva)) AS DECIMAL (10,2)),
t.PorcentajeIva,
it.transactionTypeSageFk,
it.taxTypeSageFk,
@@ -39,7 +39,8 @@ BEGIN
JOIN TiposTransacciones tt ON tt.CodigoTransaccion = it.transactionTypeSageFk
LEFT JOIN vn.dua d ON d.id = vInvoiceInFk
WHERE i.id = vInvoiceInFk
- AND d.id IS NULL;
+ AND d.id IS NULL
+ GROUP BY it.taxTypeSageFk;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
@@ -203,32 +204,31 @@ BEGIN
FROM vn.invoiceInCorrection
WHERE correctingFk = vInvoiceInFk;
- IF vInvoiceInOriginalFk THEN
-
+ IF vInvoiceInOriginalFk THEN
UPDATE movContaIVA mci
- JOIN vn.invoiceInRefund iir ON iir.invoiceInRefundFk = vInvoiceInFk
+ JOIN vn.invoiceInCorrection iic ON iic.correctingFk = vInvoiceInFk
+ JOIN vn.siiTypeInvoiceIn st ON st.id = iic.siiTypeInvoiceInFk
JOIN (SELECT issued,
- SUM(sub.taxableBase) taxableBase,
+ SUM(sub.taxableBase) taxableBase,
SUM(ROUND((sub.taxableBase * sub.PorcentajeIva) / 100 , 2)) vat
FROM(SELECT issued,
- SUM(iit.taxableBase) taxableBase,
+ SUM(iit.taxableBase) taxableBase,
ti.PorcentajeIva
- FROM vn.invoiceIn i
+ FROM vn.invoiceIn i
JOIN vn.invoiceInTax iit ON iit.invoiceInFk = i.id
- JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk
+ JOIN TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk
WHERE i.id = vInvoiceInOriginalFk
GROUP BY ti.CodigoIva)sub
)invoiceInOriginal
JOIN ClavesOperacion co ON co.Descripcion = 'Factura rectificativa'
SET mci.TipoRectificativa = iir.refundCategoryFk,
- mci.ClaseAbonoRectificativas = iir.refundType,
+ mci.ClaseAbonoRectificativas = iir.refundType,
mci.FechaFacturaOriginal = invoiceInOriginal.issued,
mci.FechaOperacion = invoiceInOriginal.issued,
mci.BaseImponibleOriginal = invoiceInOriginal.taxableBase,
mci.CuotaIvaOriginal = invoiceInOriginal.vat,
mci.ClaveOperacionFactura = co.ClaveOperacionFactura_
WHERE mci.id = vXDiarioFk;
-
END IF;
END$$
-DELIMITER ;
\ No newline at end of file
+DELIMITER ;
diff --git a/db/routines/sage/procedures/invoiceOut_add.sql b/db/routines/sage/procedures/invoiceOut_add.sql
index 95d6a56dd..f9c6f6b87 100644
--- a/db/routines/sage/procedures/invoiceOut_add.sql
+++ b/db/routines/sage/procedures/invoiceOut_add.sql
@@ -169,6 +169,7 @@ BEGIN
UPDATE movContaIVA mci
JOIN vn.invoiceOut i ON i.id = vInvoiceOutCorrectedFk
JOIN vn.invoiceCorrection ic ON ic.correctedFk = vInvoiceOutCorrectedFk
+ JOIN vn.siiTypeInvoiceOut st ON st.id = ic.siiTypeInvoiceOutFk
JOIN (SELECT SUM(IF(IFNULL(e.vatFk, TRUE), iot.taxableBase, 0)) taxableBase,
SUM(IF(IFNULL(e.vatFk, TRUE), iot.vat, 0)) vat,
SUM(IF(IFNULL(e.vatFk, TRUE), 0, iot.vat)) equ
@@ -177,8 +178,8 @@ BEGIN
WHERE iot.invoiceOutFk = vInvoiceOutCorrectedFk
) tax
JOIN ClavesOperacion co ON co.Descripcion = 'Factura rectificativa'
- SET mci.TipoRectificativa = 2,
- mci.ClaseAbonoRectificativas = 1,
+ SET mci.TipoRectificativa = ic.cplusRectificationTypeFk,
+ mci.ClaseAbonoRectificativas = REGEXP_REPLACE(st.`code`, '[^0-9]', ''),
mci.FechaFacturaOriginal = i.issued,
mci.FechaOperacion = i.issued,
mci.BaseImponibleOriginal = tax.taxableBase,
diff --git a/db/routines/salix/triggers/ACL_beforeInsert.sql b/db/routines/salix/triggers/ACL_beforeInsert.sql
index 94fb51ada..cb0b5761b 100644
--- a/db/routines/salix/triggers/ACL_beforeInsert.sql
+++ b/db/routines/salix/triggers/ACL_beforeInsert.sql
@@ -4,5 +4,8 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `salix`.`ACL_beforeInsert`
FOR EACH ROW
BEGIN
SET NEW.editorFk = account.myUser_getId();
+ IF NEW.`property` = '*' THEN
+ CALL util.throw('The property field cannot be *');
+ END IF;
END$$
DELIMITER ;
diff --git a/db/routines/stock/procedures/log_refreshBuy.sql b/db/routines/stock/procedures/log_refreshBuy.sql
index 488c00a28..874e14072 100644
--- a/db/routines/stock/procedures/log_refreshBuy.sql
+++ b/db/routines/stock/procedures/log_refreshBuy.sql
@@ -6,12 +6,11 @@ BEGIN
DROP TEMPORARY TABLE IF EXISTS tValues;
CREATE TEMPORARY TABLE tValues
ENGINE = MEMORY
- SELECT
- b.id buyFk,
+ SELECT b.id buyFk,
e.id entryFk,
t.id travelFk,
b.itemFk,
- e.isRaid,
+ t.isRaid,
ADDTIME(t.shipped,
IFNULL(t.shipmentHour, '00:00:00')) shipped,
t.warehouseOutFk,
@@ -50,7 +49,7 @@ BEGIN
itemFk,
TIMESTAMPADD(DAY, life, @dated),
quantity,
- IF(isIn, isReceived, isDelivered) AND !isRaid
+ IF(isIn, isReceived, isDelivered) AND NOT isRaid
FROM tValues
WHERE isIn OR !lessThanInventory;
@@ -65,7 +64,7 @@ BEGIN
itemFk,
created,
quantity,
- IF(isIn, isDelivered, isReceived) AND !isRaid
+ IF(isIn, isDelivered, isReceived) AND NOT isRaid
FROM tValues
WHERE !isIn OR !lessThanInventory;
diff --git a/db/routines/vn/events/itemCampaign_add.sql b/db/routines/vn/events/itemCampaign_add.sql
new file mode 100644
index 000000000..efb2aeb11
--- /dev/null
+++ b/db/routines/vn/events/itemCampaign_add.sql
@@ -0,0 +1,8 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`vn`@`localhost` EVENT `vn`.`itemCampaig_add`
+ ON SCHEDULE EVERY 1 DAY
+ STARTS '2024-10-18 03:00:00.000'
+ ON COMPLETION PRESERVE
+ ENABLE
+DO CALL itemCampaign_add()$$
+DELIMITER ;
diff --git a/db/routines/vn/events/raidUpdate.sql b/db/routines/vn/events/raidUpdate.sql
deleted file mode 100644
index c0c6f03c5..000000000
--- a/db/routines/vn/events/raidUpdate.sql
+++ /dev/null
@@ -1,8 +0,0 @@
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` EVENT `vn`.`raidUpdate`
- ON SCHEDULE EVERY 1 DAY
- STARTS '2017-12-29 00:05:00.000'
- ON COMPLETION PRESERVE
- ENABLE
-DO CALL raidUpdate$$
-DELIMITER ;
diff --git a/db/routines/vn/functions/address_getGeo.sql b/db/routines/vn/functions/address_getGeo.sql
index 04155c30c..213eb91c3 100644
--- a/db/routines/vn/functions/address_getGeo.sql
+++ b/db/routines/vn/functions/address_getGeo.sql
@@ -14,9 +14,12 @@ BEGIN
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
+ JOIN postCode p ON p.townFk = t.id
+ AND (p.code = a.postalCode OR a.postalCode IS NULL)
+ JOIN zoneGeo zg ON zg.id = p.geoFk
WHERE a.id = vSelf
- ORDER BY (a.city SOUNDS LIKE t.`name`) DESC
+ ORDER BY (a.city SOUNDS LIKE t.name) DESC,
+ (p.code = a.postalCode) DESC
LIMIT 1;
RETURN vGeoFk;
diff --git a/db/routines/vn/functions/buy_getLastWithoutInventory.sql b/db/routines/vn/functions/buy_getLastWithoutInventory.sql
new file mode 100644
index 000000000..ac19fe416
--- /dev/null
+++ b/db/routines/vn/functions/buy_getLastWithoutInventory.sql
@@ -0,0 +1,32 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`buy_getLastWithoutInventory`(
+ vItemFk INT,
+ vWarehouseFk INT
+)
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+/**
+ * Retorna la última compra que no sea inventario.
+ *
+ * @param vItemFk Id del artículo
+ * @param vWarehouseFk Id del almacén
+ * @return Id de compra
+ */
+ DECLARE vBuyFk INT;
+
+ SELECT b.id INTO vBuyFk
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ WHERE e.id <> (SELECT defaultEntry FROM entryConfig)
+ AND e.supplierFk <> (SELECT supplierFk FROM inventoryConfig)
+ AND e.typeFk <> 'inventory'
+ AND b.itemFk = vItemFk
+ AND (t.warehouseInFk = vWarehouseFk OR t.warehouseInFk IS NULL)
+ ORDER BY ABS(DATEDIFF(util.VN_CURDATE(), t.landed)), e.created DESC
+ LIMIT 1;
+
+ RETURN vBuyFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/buy_getUltimate.sql b/db/routines/vn/functions/buy_getUltimate.sql
new file mode 100644
index 000000000..8f5e9ce59
--- /dev/null
+++ b/db/routines/vn/functions/buy_getUltimate.sql
@@ -0,0 +1,31 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`buy_getUltimate`(
+ vItemFk INT,
+ vWarehouseFk INT,
+ vDated DATE
+)
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+/**
+ * Calcula las últimas compras realizadas hasta una fecha.
+ *
+ * @param vItemFk Id del artículo
+ * @param vWarehouseFk Id del almacén
+ * @param vDated Compras hasta fecha
+ * @return Id de compra
+ */
+ DECLARE vBuyFk INT;
+
+ CALL buy_getUltimate(vItemFk, vWarehouseFk, vDated);
+
+ SELECT buyFk INTO vBuyFk
+ FROM tmp.buyUltimate;
+
+ DROP TEMPORARY TABLE IF EXISTS
+ tmp.buyUltimate,
+ tmp.buyUltimateFromInterval;
+
+ RETURN vBuyFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/client_getGeo.sql b/db/routines/vn/functions/client_getGeo.sql
new file mode 100644
index 000000000..9c2e3212e
--- /dev/null
+++ b/db/routines/vn/functions/client_getGeo.sql
@@ -0,0 +1,27 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`client_getGeo`(vSelf INT)
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+/**
+ * Returns the geo for the passed client.
+ *
+ * @param vSelf The address id
+ * @return The geo id
+ */
+ DECLARE vGeoFk INT;
+
+ SELECT p.geoFk INTO vGeoFk
+ FROM client c
+ JOIN town t ON t.provinceFk = c.provinceFk
+ JOIN postCode p ON p.townFk = t.id
+ AND (p.code = c.postcode OR c.postcode IS NULL)
+ JOIN zoneGeo zg ON zg.id = p.geoFk
+ WHERE c.id = vSelf
+ ORDER BY (c.city SOUNDS LIKE t.name) DESC,
+ (p.code = c.postcode) DESC
+ LIMIT 1;
+
+ RETURN vGeoFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/entry_getCommission.sql b/db/routines/vn/functions/entry_getCommission.sql
index 4a19f4e63..f8c1ce3b4 100644
--- a/db/routines/vn/functions/entry_getCommission.sql
+++ b/db/routines/vn/functions/entry_getCommission.sql
@@ -1,58 +1,54 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`entry_getCommission`(vTravelFk INT,
- vCurrencyFk INT,
- vSupplierFk INT
+ vCurrencyFk INT,
+ vSupplierFk INT
)
RETURNS int(11)
NOT DETERMINISTIC
READS SQL DATA
BEGIN
- DECLARE vCommission INT;
- DECLARE vCurrentCommission INT;
- DECLARE vIsCurrencyUsd INT;
- DECLARE vLastEntryFk INT;
-
- SELECT count(*) INTO vIsCurrencyUsd
- FROM currency c
- WHERE c.code = 'USD' AND id = vCurrencyFk;
-
- IF NOT vIsCurrencyUsd THEN
-
- SELECT e.id INTO vLastEntryFk
- FROM vn.entry e
- JOIN vn.travel tr ON tr.id = e.travelFk
- WHERE e.supplierFk = vSupplierFk
- ORDER BY tr.landed DESC
- LIMIT 1;
-
- IF vLastEntryFk THEN
-
- SELECT commission INTO vCurrentCommission
- FROM vn.entry
- WHERE id = vLastEntryFk;
-
- ELSE
-
- SELECT commission INTO vCurrentCommission
- FROM supplier s
- WHERE s.id = vSupplierFk;
-
- END IF;
-
- RETURN vCurrentCommission;
-
- ELSE
+ DECLARE vCommission INT;
+ DECLARE vCurrentCommission INT;
+ DECLARE vIsNotEUR INT;
+ DECLARE vLastEntryFk INT;
+ DECLARE vLanded INT;
+ SELECT count(*) INTO vIsNotEUR
+ FROM currency c
+ WHERE c.code <> 'EUR' AND id = vCurrencyFk;
+
+ IF vIsNotEUR THEN
SELECT ROUND(-100 * (1 - (1 / r.value))) INTO vCommission
FROM travel t
LEFT JOIN referenceCurrent r ON r.currencyFk = vCurrencyFk AND r.`dated` <= t.shipped
WHERE t.id = vTravelFk
ORDER BY r.`dated` DESC
LIMIT 1;
-
+
RETURN IFNULL(vCommission, 0);
-
- END IF;
-
+ ELSE
+ SELECT landed INTO vLanded
+ FROM travel
+ WHERE id = vTravelFk;
+
+ SELECT e.id INTO vLastEntryFk
+ FROM `entry` e
+ JOIN travel tr ON tr.id = e.travelFk
+ WHERE e.supplierFk = vSupplierFk
+ ORDER BY (vLanded <= tr.landed), tr.landed DESC
+ LIMIT 1;
+
+ IF vLastEntryFk THEN
+ SELECT commission INTO vCurrentCommission
+ FROM `entry`
+ WHERE id = vLastEntryFk;
+ ELSE
+ SELECT commission INTO vCurrentCommission
+ FROM supplier s
+ WHERE s.id = vSupplierFk;
+ END IF;
+
+ RETURN vCurrentCommission;
+ END IF;
END$$
DELIMITER ;
diff --git a/db/routines/vn/functions/hasItemsInSector.sql b/db/routines/vn/functions/hasItemsInSector.sql
index 7a5c4cf60..faf9e8a90 100644
--- a/db/routines/vn/functions/hasItemsInSector.sql
+++ b/db/routines/vn/functions/hasItemsInSector.sql
@@ -9,7 +9,7 @@ BEGIN
SELECT count(*) INTO vItemCount
FROM vn.sale s
JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk
- JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.shelving sh ON sh.id = ish.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
WHERE s.ticketFk = vTicketFk
AND p.sectorFk = vSectorFk;
diff --git a/db/routines/vn/functions/itemsInSector_get.sql b/db/routines/vn/functions/itemsInSector_get.sql
index 254ebe1b5..9043e55cb 100644
--- a/db/routines/vn/functions/itemsInSector_get.sql
+++ b/db/routines/vn/functions/itemsInSector_get.sql
@@ -10,7 +10,7 @@ BEGIN
SELECT count(*) INTO vItemCount
FROM vn.sale s
JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk
- JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.shelving sh ON sh.id = ish.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
WHERE s.ticketFk = vTicketFk
AND p.sectorFk = vSectorFk;
diff --git a/db/routines/vn/functions/routeProposal.sql b/db/routines/vn/functions/routeProposal.sql
index 14b626a39..70a1eaae4 100644
--- a/db/routines/vn/functions/routeProposal.sql
+++ b/db/routines/vn/functions/routeProposal.sql
@@ -26,7 +26,7 @@ BEGIN
JOIN cache.zoneAgencyFriendship zf ON zf.agencyModeFk = r.agencyModeFk
WHERE friendship >= vSignificativeFriendship
AND zf.zoneFk = vZoneFk
- AND r.created = vLanded
+ AND r.dated = vLanded
ORDER BY friendship;
-- Se eliminan aquellas que superan el volumen máximo
diff --git a/db/routines/vn/functions/routeProposal_beta.sql b/db/routines/vn/functions/routeProposal_beta.sql
index d6db4d361..f5c347a5b 100644
--- a/db/routines/vn/functions/routeProposal_beta.sql
+++ b/db/routines/vn/functions/routeProposal_beta.sql
@@ -26,7 +26,7 @@ BEGIN
JOIN cache.zoneAgencyFriendship zf ON zf.agencyModeFk = r.agencyModeFk
WHERE friendship >= vSignificativeFriendship
AND zf.zoneFk = vZoneFk
- AND r.created = vLanded
+ AND r.dated = vLanded
ORDER BY friendship;
-- Se eliminan aquellas que superan el volumen máximo
diff --git a/db/routines/vn/functions/supplier_getGeo.sql b/db/routines/vn/functions/supplier_getGeo.sql
new file mode 100644
index 000000000..86984272c
--- /dev/null
+++ b/db/routines/vn/functions/supplier_getGeo.sql
@@ -0,0 +1,29 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`supplier_getGeo`(vSelf INT)
+ RETURNS int(11)
+ DETERMINISTIC
+BEGIN
+/**
+ * Returns the geo for the passed supplier.
+ *
+ * @param vSelf The address id
+ * @return The geo id
+ */
+ DECLARE vGeoFk INT;
+
+ SELECT p.geoFk INTO vGeoFk
+ FROM supplier s
+ JOIN town t ON t.provinceFk = s.provinceFk
+ JOIN postCode p ON p.townFk = t.id
+ AND (p.code = s.postCode OR s.postCode IS NULL)
+ LEFT JOIN supplierAddress sad ON sad.supplierFk = s.id
+ JOIN zoneGeo zg ON zg.id = p.geoFk
+ WHERE s.id = vSelf
+ ORDER BY (s.city SOUNDS LIKE t.name) DESC,
+ (p.code = s.postCode) DESC,
+ (p.code = sad.postalCode) DESC
+ LIMIT 1;
+
+ RETURN vGeoFk;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/functions/timeWorkerControl_getDirection.sql b/db/routines/vn/functions/timeWorkerControl_getDirection.sql
deleted file mode 100644
index c0f1e67ea..000000000
--- a/db/routines/vn/functions/timeWorkerControl_getDirection.sql
+++ /dev/null
@@ -1,65 +0,0 @@
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`timeWorkerControl_getDirection`(vUserFk INT, vTimed DATETIME)
- RETURNS varchar(6) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
- NOT DETERMINISTIC
- 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 ;
diff --git a/db/routines/vn/functions/workerMachinery_isRegistered.sql b/db/routines/vn/functions/workerMachinery_isRegistered.sql
deleted file mode 100644
index 60f458e9e..000000000
--- a/db/routines/vn/functions/workerMachinery_isRegistered.sql
+++ /dev/null
@@ -1,23 +0,0 @@
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`workerMachinery_isRegistered`(vWorkerFk VARCHAR(10))
- RETURNS tinyint(1)
- NOT DETERMINISTIC
- READS SQL DATA
-BEGIN
-/**
- * Comprueba si existen registros en las últimas horas (maxHours de machineWorkerConfig) del trabajador vWorkerFk y si tiene a nulo la hora outTimed (indica la hora que deja el vehículo)
- *
- * @param vWorkerFk id del trabajador
- * @return Devuelve TRUE/FALSE en caso de que haya o no registros
- */
- IF (SELECT COUNT(*)
- FROM machineWorker m
- WHERE m.workerFk = vWorkerFk
- AND m.inTimed >= TIMESTAMPADD(HOUR , -(SELECT maxHours from machineWorkerConfig), util.VN_NOW()) AND ISNULL(m.outTimed))
- THEN
- RETURN TRUE;
- ELSE
- RETURN FALSE;
- END IF;
-END$$
-DELIMITER ;
diff --git a/db/routines/vn/procedures/absoluteInventoryHistory.sql b/db/routines/vn/procedures/absoluteInventoryHistory.sql
index d2a2029f0..d0d9ffac2 100644
--- a/db/routines/vn/procedures/absoluteInventoryHistory.sql
+++ b/db/routines/vn/procedures/absoluteInventoryHistory.sql
@@ -39,7 +39,7 @@ BEGIN
AND vWarehouseFk IN (tr.warehouseInFk, 0)
AND b.itemFk = vItemFk
AND NOT e.isExcludedFromAvailable
- AND NOT e.isRaid
+ AND NOT tr.isRaid
UNION ALL
SELECT tr.shipped,
NULL,
@@ -58,7 +58,7 @@ BEGIN
AND s.id <> (SELECT supplierFk FROM inventoryConfig)
AND b.itemFk = vItemFk
AND NOT e.isExcludedFromAvailable
- AND NOT e.isRaid
+ AND NOT tr.isRaid
UNION ALL
SELECT t.shipped,
NULL,
@@ -81,7 +81,7 @@ BEGIN
FROM tHistoricalPast
WHERE `date` < vDate;
- SELECT p1.*, NULL v_virtual
+ SELECT p1.*, NULL v_virtual
FROM (
SELECT vDate `date`,
vCalculatedInventory input,
@@ -96,7 +96,7 @@ BEGIN
FROM tHistoricalPast
WHERE `date` >= vDate
) p1;
-
+
DROP TEMPORARY TABLE tHistoricalPast;
END$$
-DELIMITER ;
\ No newline at end of file
+DELIMITER ;
diff --git a/db/routines/vn/procedures/available_traslate.sql b/db/routines/vn/procedures/available_traslate.sql
index 03eb376ab..bfd5b34c8 100644
--- a/db/routines/vn/procedures/available_traslate.sql
+++ b/db/routines/vn/procedures/available_traslate.sql
@@ -5,7 +5,7 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`available_traslate`(
vWarehouseShipment INT)
proc: BEGIN
/**
- * Calcular la disponibilidad dependiendo del almacen
+ * Calcular la disponibilidad dependiendo del almacen
* de origen y destino según la fecha.
*
* @param vWarehouseLanding Almacén de llegada
@@ -42,10 +42,10 @@ proc: BEGIN
WHERE t.landed BETWEEN vDatedInventory AND vDatedFrom
AND t.warehouseInFk = vWarehouseLanding
AND NOT e.isExcludedFromAvailable
- AND NOT e.isRaid
+ AND NOT t.isRaid
GROUP BY c.itemFk;
- -- Tabla con el ultimo dia de last_buy para cada producto
+ -- Tabla con el ultimo dia de last_buy para cada producto
-- que hace un replace de la anterior.
CALL buy_getUltimate (NULL, vWarehouseShipment, util.VN_CURDATE());
@@ -57,7 +57,7 @@ proc: BEGIN
JOIN travel tr ON tr.id = e.travelFk
LEFT JOIN tItemRange i ON t.itemFk = i.itemFk
WHERE t.warehouseFk = vWarehouseShipment
- AND NOT e.isRaid
+ AND NOT tr.isRaid
ON DUPLICATE KEY UPDATE tItemRange.dated = GREATEST(tItemRange.dated,
tr.landed);
@@ -94,7 +94,7 @@ proc: BEGIN
JOIN tItemRangeLive ir ON ir.itemFk = b.itemFk
WHERE NOT e.isExcludedFromAvailable
AND b.quantity <> 0
- AND NOT e.isRaid
+ AND NOT t.isRaid
AND t.warehouseInFk = vWarehouseLanding
AND t.landed >= vDatedFrom
AND (ir.dated IS NULL OR t.landed <= ir.dated)
@@ -135,4 +135,4 @@ proc: BEGIN
DROP TEMPORARY TABLE tmp.itemList, tItemRange, tItemRangeLive;
END$$
-DELIMITER ;
\ No newline at end of file
+DELIMITER ;
diff --git a/db/routines/vn/procedures/buy_getUltimate.sql b/db/routines/vn/procedures/buy_getUltimate.sql
index 1532222ad..77e2029fc 100644
--- a/db/routines/vn/procedures/buy_getUltimate.sql
+++ b/db/routines/vn/procedures/buy_getUltimate.sql
@@ -1,7 +1,7 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`buy_getUltimate`(
vItemFk INT,
- vWarehouseFk SMALLINT,
+ vWarehouseFk INT,
vDated DATE
)
BEGIN
diff --git a/db/routines/vn/procedures/buy_getVolumeByAgency.sql b/db/routines/vn/procedures/buy_getVolumeByAgency.sql
deleted file mode 100644
index 7393d12d8..000000000
--- a/db/routines/vn/procedures/buy_getVolumeByAgency.sql
+++ /dev/null
@@ -1,20 +0,0 @@
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`buy_getVolumeByAgency`(vDated DATE, vAgencyFk INT)
-BEGIN
-
- DROP TEMPORARY TABLE IF EXISTS tmp.buy;
- CREATE TEMPORARY TABLE tmp.buy (buyFk INT NOT NULL, PRIMARY KEY (buyFk)) ENGINE = MEMORY;
-
- INSERT INTO tmp.buy
- SELECT b.id
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- WHERE t.landed = vDated
- AND t.agencyModeFk IN (0, vAgencyFk);
-
- CALL buy_getVolume();
- DROP TEMPORARY TABLE tmp.buy;
-
-END$$
-DELIMITER ;
diff --git a/db/routines/vn/procedures/claimRatio_add.sql b/db/routines/vn/procedures/claimRatio_add.sql
index 8c3213644..5e2e66a8e 100644
--- a/db/routines/vn/procedures/claimRatio_add.sql
+++ b/db/routines/vn/procedures/claimRatio_add.sql
@@ -46,7 +46,7 @@ BEGIN
JOIN claimDestination cd ON cd.id = ce.claimDestinationFk
JOIN claim c ON c.id = ce.claimFk
JOIN claimState cs ON cs.id = c.claimStateFk
- WHERE cd.description NOT IN ('Bueno', 'Corregido')
+ WHERE cd.code NOT IN ('good', 'corrected', 'supplierClaim')
AND NOT ce.isGreuge
AND cs.code = 'resolved';
@@ -71,7 +71,7 @@ BEGIN
JOIN claimDestination cd ON cd.id = ce.claimDestinationFk
JOIN claim c ON c.id = ce.claimFk
JOIN claimState cs ON cs.id = c.claimStateFk
- WHERE cd.description NOT IN ('Bueno', 'Corregido')
+ WHERE cd.code NOT IN ('good', 'corrected', 'supplierClaim')
AND NOT ce.isGreuge
AND cs.code = 'resolved'
AND c.isChargedToMana;
@@ -82,7 +82,7 @@ BEGIN
JOIN claim c ON c.id = ce.claimFk
JOIN claimState cs ON cs.id = c.claimStateFk
SET ce.isGreuge = TRUE
- WHERE cd.description NOT IN ('Bueno', 'Corregido')
+ WHERE cd.code NOT IN ('good', 'corrected', 'supplierClaim')
AND NOT ce.isGreuge
AND cs.code = 'resolved';
@@ -161,7 +161,7 @@ BEGIN
JOIN claimDestination cd ON cd.id = ce.claimDestinationFk
JOIN claim c ON c.id = ce.claimFk
JOIN claimState cs ON cs.id = c.claimStateFk
- WHERE cd.description NOT IN ('Bueno', 'Corregido')
+ WHERE cd.code NOT IN ('good', 'corrected', 'supplierClaim')
AND cs.code = 'resolved'
AND c.ticketCreated >= util.VN_CURDATE() - INTERVAL 1 YEAR
GROUP BY c.clientFk
diff --git a/db/routines/vn/procedures/clean.sql b/db/routines/vn/procedures/clean.sql
index a8ca68e5f..fcee33c97 100644
--- a/db/routines/vn/procedures/clean.sql
+++ b/db/routines/vn/procedures/clean.sql
@@ -23,6 +23,13 @@ BEGIN
DELETE FROM messageInbox WHERE sendDate < v2Months;
DELETE FROM messageInbox WHERE sendDate < v2Months;
DELETE FROM workerTimeControl WHERE timed < v4Years;
+ DELETE FROM itemShelvingSale
+ WHERE itemShelvingFk IN (
+ SELECT id
+ FROM itemShelving
+ WHERE created < util.VN_CURDATE()
+ AND visible = 0
+ );
DELETE FROM itemShelving WHERE created < util.VN_CURDATE() AND visible = 0;
DELETE FROM ticketDown WHERE created < util.yesterday();
DELETE IGNORE FROM expedition WHERE created < v26Months;
@@ -49,17 +56,11 @@ BEGIN
AND ts.id IS NULL;
DELETE FROM claim WHERE ticketCreated < v4Years;
-- Robert ubicacion anterior de travelLog comentario para debug
- DELETE FROM zoneEvent WHERE `type` = 'day' AND dated < v3Months;
- 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 <= v2Months;
+ DELETE FROM zoneEvent WHERE dated < v2Months OR ended < v2Months;
DELETE b FROM buy b
JOIN entryConfig e ON e.defaultEntry = b.entryFk
WHERE b.created < v2Months;
- DELETE FROM stockBuyed WHERE creationDate < v2Months;
+ DELETE FROM stockBought WHERE dated < v2Months;
DELETE FROM printQueue WHERE statusCode = 'printed' AND created < v2Months;
-- Equipos duplicados
DELETE w.*
diff --git a/db/routines/vn/procedures/clean_logiflora.sql b/db/routines/vn/procedures/clean_logiflora.sql
index fd645a158..ac119631d 100644
--- a/db/routines/vn/procedures/clean_logiflora.sql
+++ b/db/routines/vn/procedures/clean_logiflora.sql
@@ -28,7 +28,7 @@ BEGIN
JOIN agencyMode am ON am.id = tr.agencyModeFk
WHERE NOT b.quantity
AND am.code = 'logiflora'
- AND e.isRaid;
+ AND tr.daysInForward;
START TRANSACTION;
diff --git a/db/routines/vn/procedures/client_create.sql b/db/routines/vn/procedures/client_create.sql
index 3df3df905..fad01c107 100644
--- a/db/routines/vn/procedures/client_create.sql
+++ b/db/routines/vn/procedures/client_create.sql
@@ -34,22 +34,19 @@ BEGIN
DECLARE vIsTaxDataChecked TINYINT(1);
DECLARE vHasCoreVnl BOOLEAN;
DECLARE vMandateTypeFk INT;
- DECLARE vHasDailyInvoice BOOLEAN;
SELECT cc.defaultPayMethodFk,
cc.defaultDueDay,
cc.defaultCredit,
cc.defaultIsTaxDataChecked,
cc.defaultHasCoreVnl,
- cc.defaultMandateTypeFk,
- c.hasDailyInvoice
+ cc.defaultMandateTypeFk
INTO vPayMethodFk,
vDueDay,
vDefaultCredit,
vIsTaxDataChecked,
vHasCoreVnl,
- vMandateTypeFk,
- vHasDailyInvoice
+ vMandateTypeFk
FROM clientConfig cc
LEFT JOIN province p ON p.id = vProvinceFk
LEFT JOIN country c ON c.id = p.countryFk;
@@ -70,8 +67,7 @@ BEGIN
credit = vDefaultCredit,
isTaxDataChecked = vIsTaxDataChecked,
hasCoreVnl = vHasCoreVnl,
- isEqualizated = FALSE,
- hasDailyInvoice = vHasDailyInvoice
+ isEqualizated = FALSE
ON duplicate KEY UPDATE
payMethodFk = vPayMethodFk,
dueDay = vDueDay,
diff --git a/db/routines/vn/procedures/collectionPlacement_get.sql b/db/routines/vn/procedures/collectionPlacement_get.sql
index 239dbd3a2..8d2301e1e 100644
--- a/db/routines/vn/procedures/collectionPlacement_get.sql
+++ b/db/routines/vn/procedures/collectionPlacement_get.sql
@@ -83,7 +83,7 @@ BEGIN
AND s.semaphore = 1
GROUP BY st.saleFk) st ON st.saleFk = ts.saleFk
JOIN itemShelving ish ON ish.itemFk = ts.itemFk
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN sector sc ON sc.id = p.sectorFk
JOIN sectorType st ON st.id = sc.typeFk
diff --git a/db/routines/vn/procedures/collection_addWithReservation.sql b/db/routines/vn/procedures/collection_addWithReservation.sql
index cc0b7fd9b..bb6e94a63 100644
--- a/db/routines/vn/procedures/collection_addWithReservation.sql
+++ b/db/routines/vn/procedures/collection_addWithReservation.sql
@@ -37,23 +37,23 @@ BEGIN
WHERE t.id = vTicketFk;
CALL cache.available_refresh(
- vCacheAvailableFk,
+ vCacheAvailableFk,
FALSE,
- vWarehouseFk,
+ vWarehouseFk,
util.VN_CURDATE());
SELECT available INTO vAvailable
FROM cache.available
- WHERE calc_id = vCacheAvailableFk
+ WHERE calc_id = vCacheAvailableFk
AND item_id = vItemFk;
-
+
IF vAvailable < vQuantity THEN
SET vHasThrow = TRUE;
ELSE
SELECT `name`,
- CONCAT(getUser(), ' ', DATE_FORMAT(util.VN_NOW(), '%H:%i'), ' ', name)
+ CONCAT(getUser(), ' ', DATE_FORMAT(util.VN_NOW(), '%H:%i'), ' ', name)
INTO vItemName, vConcept
- FROM item
+ FROM item
WHERE id = vItemFk;
START TRANSACTION;
@@ -69,7 +69,7 @@ BEGIN
CALL sale_calculateComponent(vSaleFk, NULL);
CALL itemShelvingSale_addBySale(vSaleFk, vSectorFk);
-
+
IF NOT EXISTS (SELECT TRUE FROM itemShelvingSale WHERE saleFk = vSaleFk LIMIT 1) THEN
SET vHasThrow = TRUE;
END IF;
@@ -78,13 +78,13 @@ BEGIN
IF vHasThrow THEN
CALL util.throw("There is no available for the selected item");
END IF;
-
+
IF vSaleGroupFk THEN
INSERT INTO saleGroupDetail
SET saleFk = vSaleFk,
saleGroupFk = vSaleGroupFk;
END IF;
-
+
COMMIT;
END$$
DELIMITER ;
diff --git a/db/routines/vn/procedures/collection_assign.sql b/db/routines/vn/procedures/collection_assign.sql
index ba83f1fbb..a4c861c96 100644
--- a/db/routines/vn/procedures/collection_assign.sql
+++ b/db/routines/vn/procedures/collection_assign.sql
@@ -3,7 +3,7 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`collection_assign`(
vUserFk INT,
OUT vCollectionFk INT
)
-BEGIN
+BEGIN
/**
* Comprueba si existen colecciones libres que se ajustan
* al perfil del usuario y le asigna la más antigua.
@@ -45,6 +45,12 @@ BEGIN
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-- Si hay colecciones sin terminar, sale del proceso
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
CALL collection_get(vUserFk);
SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, pc.maxNotAssignedCollectionLifeTime
@@ -118,9 +124,19 @@ BEGIN
IF vCollectionFk IS NULL THEN
CALL collection_new(vUserFk, vCollectionFk);
- UPDATE `collection`
- SET workerFk = vUserFk
- WHERE id = vCollectionFk;
+ START TRANSACTION;
+
+ SELECT workerFk INTO vCollectionWorker
+ FROM `collection`
+ WHERE id = vCollectionFk FOR UPDATE;
+
+ IF vCollectionWorker IS NULL THEN
+ UPDATE `collection`
+ SET workerFk = vUserFk
+ WHERE id = vCollectionFk;
+ END IF;
+
+ COMMIT;
END IF;
END$$
DELIMITER ;
\ No newline at end of file
diff --git a/db/routines/vn/procedures/collection_getAssigned.sql b/db/routines/vn/procedures/collection_getAssigned.sql
index 518e2dd7b..7151129bf 100644
--- a/db/routines/vn/procedures/collection_getAssigned.sql
+++ b/db/routines/vn/procedures/collection_getAssigned.sql
@@ -5,100 +5,139 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`collection_getAssigne
)
BEGIN
/**
- * Comprueba si existen colecciones libres que se ajustan al perfil del usuario
- * y le asigna la más antigua.
- * Añade un registro al semillero de colecciones y hace la reserva para la colección
- *
+ * Comprueba si existen colecciones libres que se ajustan
+ * al perfil del usuario y le asigna la más antigua.
+ * Añade un registro al semillero de colecciones.
+ *
* @param vUserFk Id de usuario
* @param vCollectionFk Id de colección
*/
DECLARE vHasTooMuchCollections BOOL;
- DECLARE vItemPackingTypeFk VARCHAR(1);
- DECLARE vWarehouseFk INT;
- DECLARE vLockName VARCHAR(215);
- DECLARE vLockTime INT DEFAULT 30;
+ DECLARE vDone BOOL DEFAULT FALSE;
+ DECLARE vCollectionWorker INT;
+ DECLARE vMaxNotAssignedCollectionLifeTime TIME;
+
+ DECLARE vCollections CURSOR FOR
+ WITH collections AS (
+ SELECT tc.collectionFk,
+ SUM(sv.volume) volume,
+ c.saleTotalCount,
+ c.itemPackingTypeFk,
+ c.trainFk,
+ c.warehouseFk,
+ c.wagons
+ FROM vn.ticketCollection tc
+ JOIN vn.collection c ON c.id = tc.collectionFk
+ JOIN vn.saleVolume sv ON sv.ticketFk = tc.ticketFk
+ WHERE c.workerFk IS NULL
+ AND sv.shipped >= util.VN_CURDATE()
+ GROUP BY tc.collectionFk
+ ) SELECT c.collectionFk
+ FROM collections c
+ JOIN vn.operator o
+ WHERE o.workerFk = vUserFk
+ AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL)
+ AND (c.itemPackingTypeFk = o.itemPackingTypeFk OR o.itemPackingTypeFk IS NULL)
+ AND o.numberOfWagons = c.wagons
+ AND o.trainFk = c.trainFk
+ AND o.warehouseFk = c.warehouseFk;
+
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+ -- Si hay colecciones sin terminar, sale del proceso
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
- IF vLockName IS NOT NULL THEN
- DO RELEASE_LOCK(vLockName);
- END IF;
-
+ ROLLBACK;
RESIGNAL;
END;
- -- Si hay colecciones sin terminar, sale del proceso
CALL collection_get(vUserFk);
- SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0,
- pc.collection_assign_lockname
- INTO vHasTooMuchCollections,
- vLockName
- FROM tmp.collection c
- JOIN productionConfig pc;
+ SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, pc.maxNotAssignedCollectionLifeTime
+ INTO vHasTooMuchCollections, vMaxNotAssignedCollectionLifeTime
+ FROM productionConfig pc
+ LEFT JOIN tmp.collection ON TRUE;
DROP TEMPORARY TABLE tmp.collection;
IF vHasTooMuchCollections THEN
- CALL util.throw('There are pending collections');
- END IF;
-
- SELECT warehouseFk, itemPackingTypeFk
- INTO vWarehouseFk, vItemPackingTypeFk
- FROM operator
- WHERE workerFk = vUserFk;
-
- SET vLockName = CONCAT_WS('/',
- vLockName,
- vWarehouseFk,
- vItemPackingTypeFk
- );
-
- IF NOT GET_LOCK(vLockName, vLockTime) THEN
- CALL util.throw(CONCAT('Cannot get lock: ', vLockName));
+ CALL util.throw('Hay colecciones pendientes');
END IF;
-- Se eliminan las colecciones sin asignar que estan obsoletas
- INSERT INTO ticketTracking(stateFk, ticketFk)
- SELECT s.id, tc.ticketFk
- FROM collection c
- JOIN ticketCollection tc ON tc.collectionFk = c.id
- JOIN state s ON s.code = 'PRINTED_AUTO'
- JOIN productionConfig pc
- WHERE c.workerFk IS NULL
- AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime;
- DELETE c
- FROM collection c
- JOIN productionConfig pc
- WHERE c.workerFk IS NULL
- AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime;
+ INSERT INTO ticketTracking(stateFk, ticketFk)
+ SELECT s.id, tc.ticketFk
+ FROM `collection` c
+ JOIN ticketCollection tc ON tc.collectionFk = c.id
+ JOIN `state` s ON s.code = 'PRINTED_AUTO'
+ WHERE c.workerFk IS NULL
+ AND TIMEDIFF(util.VN_NOW(), c.created) > vMaxNotAssignedCollectionLifeTime;
+
+ DELETE FROM `collection`
+ WHERE workerFk IS NULL
+ AND TIMEDIFF(util.VN_NOW(), created) > vMaxNotAssignedCollectionLifeTime;
-- Se añade registro al semillero
- INSERT INTO collectionHotbed
- SET userFk = vUserFk;
+
+ INSERT INTO collectionHotbed(userFk) VALUES(vUserFk);
-- Comprueba si hay colecciones disponibles que se ajustan a su configuracion
- SELECT MIN(c.id) INTO vCollectionFk
- FROM collection c
- JOIN operator o ON (o.itemPackingTypeFk = c.itemPackingTypeFk
- OR c.itemPackingTypeFk IS NULL)
- AND o.numberOfWagons = c.wagons
- AND o.trainFk = c.trainFk
- AND o.warehouseFk = c.warehouseFk
- AND c.workerFk IS NULL
- WHERE o.workerFk = vUserFk;
+
+ OPEN vCollections;
+ l: LOOP
+ SET vDone = FALSE;
+ FETCH vCollections INTO vCollectionFk;
+
+ IF vDone THEN
+ LEAVE l;
+ END IF;
+
+ BEGIN
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ SET vCollectionFk = NULL;
+ RESIGNAL;
+ END;
+
+ START TRANSACTION;
+
+ SELECT workerFk INTO vCollectionWorker
+ FROM `collection`
+ WHERE id = vCollectionFk FOR UPDATE;
+
+ IF vCollectionWorker IS NULL THEN
+ UPDATE `collection`
+ SET workerFk = vUserFk
+ WHERE id = vCollectionFk;
+
+ COMMIT;
+ LEAVE l;
+ END IF;
+
+ ROLLBACK;
+ END;
+ END LOOP;
+ CLOSE vCollections;
IF vCollectionFk IS NULL THEN
CALL collection_new(vUserFk, vCollectionFk);
+
+ START TRANSACTION;
+
+ SELECT workerFk INTO vCollectionWorker
+ FROM `collection`
+ WHERE id = vCollectionFk FOR UPDATE;
+
+ IF vCollectionWorker IS NULL THEN
+ UPDATE `collection`
+ SET workerFk = vUserFk
+ WHERE id = vCollectionFk;
+ END IF;
+
+ COMMIT;
END IF;
-
- UPDATE collection
- SET workerFk = vUserFk
- WHERE id = vCollectionFk;
-
CALL itemShelvingSale_addByCollection(vCollectionFk);
-
- DO RELEASE_LOCK(vLockName);
END$$
DELIMITER ;
\ No newline at end of file
diff --git a/db/routines/vn/procedures/collection_getTickets.sql b/db/routines/vn/procedures/collection_getTickets.sql
index 4566792fa..a468d7582 100644
--- a/db/routines/vn/procedures/collection_getTickets.sql
+++ b/db/routines/vn/procedures/collection_getTickets.sql
@@ -21,9 +21,8 @@ BEGIN
SELECT tob.ticketFk, tob.description
FROM vn.ticketObservation tob
JOIN vn.ticketCollection tc ON tc.ticketFk = tob.ticketFk
- LEFT JOIN vn.observationType ot ON ot.id = tob.observationTypeFk
- WHERE ot.`code` = 'itemPicker'
- AND tc.collectionFk = vParamFk OR tc.ticketFk = vParamFk
+ JOIN vn.observationType ot ON ot.id = tob.observationTypeFk AND ot.`code` = 'itemPicker'
+ WHERE tc.collectionFk = vParamFk OR tc.ticketFk = vParamFk
)
SELECT t.id ticketFk,
IF(!(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`,
@@ -31,7 +30,9 @@ BEGIN
t.warehouseFk,
w.id salesPersonFk,
IFNULL(ob.description,'') observaciones,
- cc.rgb
+ cc.rgb,
+ p.code parkingCode,
+ IF (ps.ticketFk, TRUE, FALSE) isAdvanced
FROM vn.ticket t
LEFT JOIN vn.ticketCollection tc ON t.id = tc.ticketFk
LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk
@@ -43,17 +44,22 @@ BEGIN
LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk
LEFT JOIN vn.client c ON c.id = t.clientFk
LEFT JOIN vn.worker w ON w.id = c.salesPersonFk
- LEFT JOIN observation ob ON ob.ticketFk = t.id
+ LEFT JOIN observation ob ON ob.ticketFk = t.id
+ LEFT JOIN vn.ticketParking tp ON tp.ticketFk = t.id
+ LEFT JOIN vn.parking p ON tp.parkingFk = p.id
+ LEFT JOIN vn.packingSiteAdvanced ps ON ps.ticketFk = t.id
WHERE t.id = vParamFk
AND t.shipped >= vYesterday
- UNION ALL
+ UNION
SELECT t.id ticketFk,
IF(NOT(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`,
am.name agencyName,
t.warehouseFk,
w.id salesPersonFk,
ob.description,
- IF(NOT (vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb`
+ IF(NOT (vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb`,
+ p.code parkingCode,
+ IF (ps.ticketFk, TRUE, FALSE) isAdvanced
FROM vn.ticket t
JOIN vn.ticketCollection tc ON t.id = tc.ticketFk
LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk
@@ -65,16 +71,21 @@ BEGIN
LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk
LEFT JOIN vn.client c ON c.id = t.clientFk
LEFT JOIN vn.worker w ON w.id = c.salesPersonFk
- LEFT JOIN observation ob ON ob.ticketFk = t.id
+ LEFT JOIN observation ob ON ob.ticketFk = t.id
+ LEFT JOIN vn.ticketParking tp ON tp.ticketFk = t.id
+ LEFT JOIN vn.parking p ON tp.parkingFk = p.id
+ LEFT JOIN vn.packingSiteAdvanced ps ON ps.ticketFk = t.id
WHERE tc.collectionFk = vParamFk
- UNION ALL
+ UNION
SELECT sg.ticketFk,
NULL `level`,
am.name agencyName,
t.warehouseFk,
c.salesPersonFk,
ob.description,
- NULL `rgb`
+ NULL `rgb`,
+ p.code parkingCode,
+ IF (ps.ticketFk, TRUE, FALSE) isAdvanced
FROM vn.sectorCollection sc
JOIN vn.sectorCollectionSaleGroup ss ON ss.sectorCollectionFk = sc.id
JOIN vn.saleGroup sg ON sg.id = ss.saleGroupFk
@@ -82,8 +93,12 @@ BEGIN
LEFT JOIN vn.zone z ON z.id = t.zoneFk
LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk
LEFT JOIN observation ob ON ob.ticketFk = t.id
- LEFT JOIN vn.client c ON c.id = t.clientFk
+ LEFT JOIN vn.client c ON c.id = t.clientFk
+ LEFT JOIN vn.ticketParking tp ON tp.ticketFk = t.id
+ LEFT JOIN vn.parking p ON tp.parkingFk = p.id
+ LEFT JOIN vn.packingSiteAdvanced ps ON ps.ticketFk = t.id
WHERE sc.id = vParamFk
- AND t.shipped >= vYesterday;
+ AND t.shipped >= vYesterday
+ GROUP BY ticketFk;
END$$
DELIMITER ;
diff --git a/db/routines/vn/procedures/collection_new.sql b/db/routines/vn/procedures/collection_new.sql
index 480a88f35..84133d36e 100644
--- a/db/routines/vn/procedures/collection_new.sql
+++ b/db/routines/vn/procedures/collection_new.sql
@@ -146,8 +146,6 @@ BEGIN
DELETE pb
FROM tmp.productionBuffer pb
JOIN state s ON s.id = pb.state
- JOIN agencyMode am ON am.id = pb.agencyModeFk
- JOIN agency a ON a.id = am.agencyFk
LEFT JOIN (
SELECT pb.ticketFk, MAX(i.`size`) maxSize
FROM tmp.productionBuffer pb
@@ -158,7 +156,7 @@ BEGIN
) sub ON sub.ticketFk = pb.ticketFk
JOIN productionConfig pc
WHERE pb.shipped <> util.VN_CURDATE()
- OR (pb.ubicacion IS NULL AND a.isOwn)
+ OR pb.ubicacion IS NULL
OR (NOT s.isPreparable AND NOT s.isPrintable)
OR pb.collectionH IS NOT NULL
OR pb.collectionV IS NOT NULL
diff --git a/db/routines/vn/procedures/entry_cloneHeader.sql b/db/routines/vn/procedures/entry_cloneHeader.sql
index c988cc592..f83c5c501 100644
--- a/db/routines/vn/procedures/entry_cloneHeader.sql
+++ b/db/routines/vn/procedures/entry_cloneHeader.sql
@@ -17,7 +17,6 @@ BEGIN
supplierFk,
dated,
isExcludedFromAvailable,
- isRaid,
commission,
currencyFk,
companyFk,
@@ -28,7 +27,6 @@ BEGIN
supplierFk,
dated,
isExcludedFromAvailable,
- isRaid,
commission,
currencyFk,
companyFk,
diff --git a/db/routines/vn/procedures/entry_getTransfer.sql b/db/routines/vn/procedures/entry_getTransfer.sql
index c83556408..873827db2 100644
--- a/db/routines/vn/procedures/entry_getTransfer.sql
+++ b/db/routines/vn/procedures/entry_getTransfer.sql
@@ -5,7 +5,7 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`entry_getTransfer`(
BEGIN
/**
* Retorna los artículos trasladables a partir de una entrada.
- *
+ *
* @param vSelf Id de entrada
*/
DECLARE vDateShipped DATE;
@@ -166,7 +166,7 @@ BEGIN
LEFT JOIN tmp.buyUltimateFromInterval bufi ON bufi.itemFk = i.id
LEFT JOIN buy b3 ON b3.id = bufi.buyFk
WHERE ic.display
- AND NOT e.isRaid
+ AND NOT tr.isRaid
AND (ti.visible OR ti.available)
ORDER BY i.typeFk, i.name, i.id, i.size, i.category, o.name;
diff --git a/db/routines/vn/procedures/entry_isEditable.sql b/db/routines/vn/procedures/entry_isEditable.sql
index 12b6d0ef6..c417f6789 100644
--- a/db/routines/vn/procedures/entry_isEditable.sql
+++ b/db/routines/vn/procedures/entry_isEditable.sql
@@ -9,16 +9,18 @@ BEGIN
*
* @param vSelf Id de entrada
*/
- DECLARE vIsEditable BOOL;
+ DECLARE vIsNotEditable BOOL DEFAULT FALSE;
- SELECT e.isBooked INTO vIsEditable
+ SELECT TRUE INTO vIsNotEditable
FROM `entry` e
- JOIN entryType et ON et.code = e.typeFk
- WHERE NOT et.isInformal
- AND e.id = vSelf;
+ LEFT JOIN entryType et ON et.code = e.typeFk
+ WHERE e.id = vSelf
+ AND e.isBooked
+ AND (e.typeFk IS NULL OR NOT et.isInformal);
- IF vIsEditable AND NOT IFNULL(@isModeInventory, FALSE) THEN
+ IF vIsNotEditable AND NOT IFNULL(@isModeInventory, FALSE) THEN
CALL util.throw(CONCAT('Entry ', vSelf, ' is not editable'));
END IF;
+
END$$
DELIMITER ;
diff --git a/db/routines/vn/procedures/entry_splitByShelving.sql b/db/routines/vn/procedures/entry_splitByShelving.sql
index fbf0cef90..f5de36098 100644
--- a/db/routines/vn/procedures/entry_splitByShelving.sql
+++ b/db/routines/vn/procedures/entry_splitByShelving.sql
@@ -1,10 +1,15 @@
DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`entry_splitByShelving`(vShelvingFk VARCHAR(3), vFromEntryFk INT, vToEntryFk INT)
+CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`entry_splitByShelving`(
+ vShelvingCode VARCHAR(10),
+ vFromEntryFk INT,
+ vToEntryFk INT
+)
BEGIN
/**
- * Divide las compras entre dos entradas de acuerdo con lo ubicado en una matr�cula
+ * Divide las compras entre dos entradas de
+ * acuerdo con lo ubicado en una matricula.
*
- * @param vShelvingFk Identificador de vn.shelving
+ * @param vShelvingCode Código de vn.shelving
* @param vFromEntryFk Entrada origen
* @param vToEntryFk Entrada destino
*/
@@ -14,16 +19,17 @@ BEGIN
DECLARE vDone BOOLEAN DEFAULT FALSE;
DECLARE cur CURSOR FOR
- SELECT bb.id buyFk,
+ SELECT bb.id buyFk,
LEAST(bb.stickers, FLOOR(ish.visible / ish.packing)) ishStickers,
bb.stickers buyStickers
FROM itemShelving ish
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN (SELECT b.id, b.itemFk, b.stickers
FROM buy b
WHERE b.entryFk = vFromEntryFk
ORDER BY b.stickers DESC
LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk
- WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci
+ WHERE sh.code = vShelvingCode COLLATE utf8_general_ci
AND NOT ish.isSplit
GROUP BY ish.id;
@@ -107,9 +113,10 @@ BEGIN
UPDATE buy SET printedStickers = vIshStickers WHERE id = LAST_INSERT_ID();
END IF;
- UPDATE itemShelving
- SET isSplit = TRUE
- WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci;
+ UPDATE itemShelving ish
+ JOIN shelving sh ON sh.id = ish.shelvingFk
+ SET ish.isSplit = TRUE
+ WHERE sh.code = vShelvingCode COLLATE utf8_general_ci;
END LOOP;
CLOSE cur;
END$$
diff --git a/db/routines/vn/procedures/entry_updateComission.sql b/db/routines/vn/procedures/entry_updateComission.sql
index e2de2a4a5..8db28f97d 100644
--- a/db/routines/vn/procedures/entry_updateComission.sql
+++ b/db/routines/vn/procedures/entry_updateComission.sql
@@ -22,7 +22,7 @@ BEGIN
FROM vn.entry e
JOIN vn.travel t ON t.id = e.travelFk
JOIN vn.warehouse w ON w.id = t.warehouseInFk
- WHERE t.shipped >= util.VN_CURDATE()
+ WHERE t.landed >= util.VN_CURDATE()
AND e.currencyFk = vCurrency
AND NOT e.isBooked;
@@ -33,7 +33,7 @@ BEGIN
SET e.commission = vComission;
SELECT `name` INTO vCurrencyName
- FROM currency
+ FROM currency
WHERE id = vCurrency;
CALL entry_recalc();
diff --git a/db/routines/vn/procedures/expeditionPallet_build.sql b/db/routines/vn/procedures/expeditionPallet_build.sql
index 2df73bb85..a33439061 100644
--- a/db/routines/vn/procedures/expeditionPallet_build.sql
+++ b/db/routines/vn/procedures/expeditionPallet_build.sql
@@ -5,22 +5,26 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`expeditionPallet_buil
vWorkerFk INT,
OUT vPalletFk INT
)
-BEGIN
-/** Construye un pallet de expediciones.
+proc: BEGIN
+/**
+ * Builds an expedition pallet.
*
- * Primero comprueba si esas expediciones ya pertenecen a otro pallet,
- * en cuyo caso actualiza ese pallet.
+ * First, it checks if these expeditions already belong to another pallet,
+ * in which case it returns an error.
*
- * @param vExpeditions JSON_ARRAY con esta estructura [exp1, exp2, exp3, ...]
- * @param vArcId INT Identificador de arcRead
- * @param vWorkerFk INT Identificador de worker
- * @param out vPalletFk Identificador de expeditionPallet
+ * @param vExpeditions JSON_ARRAY with this structure [exp1, exp2, exp3, ...]
+ * @param vArcId INT Identifier of arcRead
+ * @param vWorkerFk INT Identifier of worker
+ * @param out vPalletFk Identifier of expeditionPallet
*/
+
DECLARE vCounter INT;
DECLARE vExpeditionFk INT;
DECLARE vTruckFk INT;
DECLARE vPrinterFk INT;
DECLARE vExpeditionStateTypeFk INT;
+ DECLARE vFreeExpeditionCount INT;
+ DECLARE vExpeditionWithPallet INT;
CREATE OR REPLACE TEMPORARY TABLE tExpedition (
expeditionFk INT,
@@ -44,48 +48,63 @@ BEGIN
WHERE e.id = vExpeditionFk;
END WHILE;
- SELECT palletFk INTO vPalletFk
- FROM (
- SELECT palletFk, count(*) n
- FROM tExpedition
- WHERE palletFk > 0
- GROUP BY palletFk
- ORDER BY n DESC
- LIMIT 100
- ) sub
- LIMIT 1;
+ SELECT COUNT(expeditionFk) INTO vFreeExpeditionCount
+ FROM tExpedition
+ WHERE palletFk IS NULL;
- IF vPalletFk IS NULL THEN
- SELECT roadmapStopFk INTO vTruckFk
- FROM (
- SELECT rm.roadmapStopFk, count(*) n
- FROM routesMonitor rm
- JOIN tExpedition e ON e.routeFk = rm.routeFk
- GROUP BY roadmapStopFk
- ORDER BY n DESC
- LIMIT 1
- ) sub;
+ SELECT COUNT(expeditionFk) INTO vExpeditionWithPallet
+ FROM tExpedition
+ WHERE palletFk;
- IF vTruckFk IS NULL THEN
- CALL util.throw ('TRUCK_NOT_AVAILABLE');
- END IF;
-
- INSERT INTO expeditionPallet SET truckFk = vTruckFk;
-
- SET vPalletFk = LAST_INSERT_ID();
+ IF vExpeditionWithPallet THEN
+ UPDATE arcRead
+ SET error = (
+ SELECT GROUP_CONCAT(expeditionFk SEPARATOR ', ')
+ FROM tExpedition
+ WHERE palletFk
+ )
+ WHERE id = vArcId;
+ LEAVE proc;
END IF;
+ IF NOT vFreeExpeditionCount THEN
+ CALL util.throw ('NO_FREE_EXPEDITIONS');
+ END IF;
+
+ SELECT roadmapStopFk INTO vTruckFk
+ FROM (
+ SELECT rm.roadmapStopFk, count(*) n
+ FROM routesMonitor rm
+ JOIN tExpedition e ON e.routeFk = rm.routeFk
+ WHERE e.palletFk IS NULL
+ GROUP BY roadmapStopFk
+ ORDER BY n DESC
+ LIMIT 1
+ ) sub;
+
+ IF vTruckFk IS NULL THEN
+ CALL util.throw ('TRUCK_NOT_AVAILABLE');
+ END IF;
+
+ INSERT INTO expeditionPallet SET truckFk = vTruckFk;
+
+ SET vPalletFk = LAST_INSERT_ID();
+
INSERT INTO expeditionScan(expeditionFk, palletFk, workerFk)
SELECT expeditionFk, vPalletFk, vWorkerFk
FROM tExpedition
- ON DUPLICATE KEY UPDATE palletFk = vPalletFk, workerFk = vWorkerFk;
+ WHERE palletFk IS NULL;
SELECT id INTO vExpeditionStateTypeFk
FROM expeditionStateType
WHERE code = 'PALLETIZED';
-
+
INSERT INTO expeditionState(expeditionFk, typeFk)
- SELECT expeditionFk, vExpeditionStateTypeFk FROM tExpedition;
+ SELECT expeditionFk, vExpeditionStateTypeFk
+ FROM tExpedition
+ WHERE palletFk IS NULL;
+
+ UPDATE arcRead SET error = NULL WHERE id = vArcId;
SELECT printerFk INTO vPrinterFk FROM arcRead WHERE id = vArcId;
diff --git a/db/routines/vn/procedures/expeditionScan_Put.sql b/db/routines/vn/procedures/expeditionScan_Put.sql
index fc7d4da23..999b9af10 100644
--- a/db/routines/vn/procedures/expeditionScan_Put.sql
+++ b/db/routines/vn/procedures/expeditionScan_Put.sql
@@ -4,12 +4,12 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`expeditionScan_Put`(
vExpeditionFk INT
)
BEGIN
- IF NOT (SELECT TRUE FROM expedition WHERE id = vExpeditionFk LIMIT 1) THEN
- CALL util.throw('Expedition not exists');
+ IF NOT EXISTS (SELECT id FROM expeditionPallet WHERE id = vPalletFk) THEN
+ CALL util.throw('Pallet not exists');
END IF;
- IF NOT (SELECT TRUE FROM expeditionPallet WHERE id = vPalletFk LIMIT 1) THEN
- CALL util.throw('Pallet not exists');
+ IF NOT EXISTS (SELECT id FROM expedition WHERE id = vExpeditionFk) THEN
+ CALL util.throw('Expedition not exists');
END IF;
REPLACE expeditionScan(expeditionFk, palletFk)
diff --git a/db/routines/vn/procedures/expedition_getFromRoute.sql b/db/routines/vn/procedures/expedition_getFromRoute.sql
index f95936413..932f614b6 100644
--- a/db/routines/vn/procedures/expedition_getFromRoute.sql
+++ b/db/routines/vn/procedures/expedition_getFromRoute.sql
@@ -16,7 +16,8 @@ BEGIN
a.nickname,
sub2.itemPackingTypeConcat,
est.code,
- es.isScanned
+ es2.isScanned,
+ es2.scanOrder
FROM expedition e
JOIN ticket t ON t.id = e.ticketFk
JOIN ticketState ts ON ts.ticketFk = e.ticketFk
@@ -38,7 +39,8 @@ BEGIN
SELECT MAX(id)
FROM expeditionState es
WHERE expeditionFk = e.id)
+ LEFT JOIN expeditionState es2 ON es2.id = es.id
WHERE t.routeFk = vRouteFk AND e.freightItemFk <> FALSE
- ORDER BY r.created, t.priority DESC;
+ ORDER BY r.dated, t.priority DESC;
END$$
DELIMITER ;
diff --git a/db/routines/vn/procedures/expedition_selfConsumptionPackaging.sql b/db/routines/vn/procedures/expedition_selfConsumptionPackaging.sql
new file mode 100644
index 000000000..166ec476c
--- /dev/null
+++ b/db/routines/vn/procedures/expedition_selfConsumptionPackaging.sql
@@ -0,0 +1,95 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`expedition_selfConsumptionPackaging`(
+ vSelf INT,
+ vAction ENUM('add', 'remove')
+)
+proc:BEGIN
+/**
+ * Maneja el consumo de cajas para autoconsumo, permitiendo
+ * añadir o quitar cajas utilizadas según la acción indicada.
+ *
+ * @param vSelf Id de expedición
+ */
+ DECLARE vClientFk INT;
+ DECLARE vAddressFk INT;
+ DECLARE vItemFk INT;
+ DECLARE vItemName VARCHAR(50);
+ DECLARE vWarehouseFk INT;
+ DECLARE vCreated DATE;
+ DECLARE vTicketFk INT;
+ DECLARE vSaleFk INT;
+ DECLARE vQuantity INT;
+
+ IF vAction NOT IN ('add', 'remove') THEN
+ CALL util.throw('Action not supported');
+ END IF;
+
+ SELECT pc.clientSelfConsumptionFk,
+ pc.addressSelfConsumptionFk,
+ i.id,
+ i.name,
+ t.warehouseFk,
+ e.created
+ INTO vClientFk,
+ vAddressFk,
+ vItemFk,
+ vItemName,
+ vWarehouseFk,
+ vCreated
+ FROM expedition e
+ LEFT JOIN packaging p ON p.id = e.packagingFk
+ LEFT JOIN item i ON i.id = p.itemFk
+ JOIN ticket t ON t.id = e.ticketFk
+ JOIN productionConfig pc
+ WHERE e.id = vSelf;
+
+ IF vClientFk IS NULL OR vItemFk IS NULL THEN
+ LEAVE proc;
+ END IF;
+
+ SET vCreated = DATE(vCreated);
+
+ SELECT id INTO vTicketFk
+ FROM ticket
+ WHERE shipped BETWEEN vCreated AND util.dayEnd(vCreated)
+ AND clientFk = vClientFk
+ AND addressFk = vAddressFk
+ AND warehouseFk = vWarehouseFk
+ AND nickname = 'CAJAS AUTOCONSUMO'
+ LIMIT 1;
+
+ IF vTicketFk IS NULL AND vAction = 'add' THEN
+ INSERT INTO ticket(clientFk, warehouseFk, shipped, nickname, addressFk)
+ VALUES (vClientFk, vWarehouseFk, vCreated, 'CAJAS AUTOCONSUMO', vAddressFk);
+
+ SET vTicketFk = LAST_INSERT_ID();
+ END IF;
+
+ SELECT id, quantity INTO vSaleFk, vQuantity
+ FROM sale
+ WHERE itemFk = vItemFk
+ AND ticketFk = vTicketFk
+ LIMIT 1;
+
+ IF vAction = 'add' THEN
+ IF vSaleFk IS NOT NULL THEN
+ UPDATE sale
+ SET quantity = quantity + 1
+ WHERE id = vSaleFk;
+ ELSE
+ INSERT INTO sale(itemFk, ticketFk, concept, quantity)
+ VALUES (vItemFk, vTicketFk, vItemName, 1);
+ END IF;
+ ELSE
+ IF vSaleFk IS NOT NULL THEN
+ IF vQuantity > 1 THEN
+ UPDATE sale
+ SET quantity = quantity - 1
+ WHERE id = vSaleFk;
+ ELSE
+ DELETE FROM sale WHERE id = vSaleFk;
+ END IF;
+ END IF;
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/inventoryFailureAdd.sql b/db/routines/vn/procedures/inventoryFailureAdd.sql
deleted file mode 100644
index e2b5fa4a0..000000000
--- a/db/routines/vn/procedures/inventoryFailureAdd.sql
+++ /dev/null
@@ -1,48 +0,0 @@
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`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 ;
diff --git a/db/routines/vn/procedures/inventoryMake.sql b/db/routines/vn/procedures/inventoryMake.sql
index 91065771a..316083db0 100644
--- a/db/routines/vn/procedures/inventoryMake.sql
+++ b/db/routines/vn/procedures/inventoryMake.sql
@@ -137,7 +137,7 @@ BEGIN
JOIN travel tr ON tr.id = e.travelFk
WHERE tr.warehouseInFk = vWarehouseFk
AND tr.landed BETWEEN vDateLastInventory AND vDateYesterday
- AND NOT isRaid
+ AND NOT tr.isRaid
GROUP BY b.itemFk;
-- Transfers
@@ -150,7 +150,7 @@ BEGIN
JOIN travel tr ON tr.id = e.travelFk
WHERE tr.warehouseOutFk = vWarehouseFk
AND tr.shipped BETWEEN vDateLastInventory AND vDateYesterday
- AND NOT isRaid
+ AND NOT tr.isRaid
GROUP BY b.itemFk
) sub
ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity, 0) + sub.quantityOut;
diff --git a/db/routines/vn/procedures/invoiceIn_booking.sql b/db/routines/vn/procedures/invoiceIn_booking.sql
index 36189afcc..ef68e4804 100644
--- a/db/routines/vn/procedures/invoiceIn_booking.sql
+++ b/db/routines/vn/procedures/invoiceIn_booking.sql
@@ -43,7 +43,7 @@ BEGIN
ii.cplusTaxBreakFk,
ii.cplusSubjectOpFk,
ii.siiTypeInvoiceInFk,
- ii.cplusRectificationTypeFk,
+ ic.cplusRectificationTypeFk,
ii.booked,
IFNULL(a.isUeeMember, c.isUeeMember) isUeeMember,
(c.id = cc.id) isSameCountry,
@@ -66,6 +66,7 @@ BEGIN
e.name expenseName
FROM invoiceIn ii
JOIN supplier s ON s.id = ii.supplierFk
+ LEFT JOIN invoiceInCorrection ic ON ic.correctingFk = ii.id
LEFT JOIN province p ON p.id = s.provinceFk
LEFT JOIN autonomy a ON a.id = p.autonomyFk
JOIN country c ON c.id = s.countryFk
@@ -219,7 +220,7 @@ BEGIN
) eWithheld ON TRUE
WHERE tii.taxTypeSageFk IS NOT NULL
AND (tii.taxCode IS NULL OR tii.taxCode NOT IN ('import10', 'import21'))
- GROUP BY tii.PorcentajeIva, tii.expenseFk;
+ GROUP BY tii.CuentaIvaRepercutido;
-- Línea iva inversor sujeto pasivo
INSERT INTO XDiario(
@@ -284,7 +285,7 @@ BEGIN
AND NOT(tii.isVies
AND c.nontaxableTransactionTypeFk = tii.transactionTypeSageFk
AND tii.taxCode = 'nonTaxable')
- GROUP BY tii.PorcentajeIva, tii.expenseFk;
+ GROUP BY tii.CuentaIvaRepercutido;
-- Actualización del registro original
UPDATE invoiceIn ii
diff --git a/db/routines/vn/procedures/invoiceOut_newFromAddress.sql b/db/routines/vn/procedures/invoiceOut_newFromAddress.sql
new file mode 100644
index 000000000..495ace608
--- /dev/null
+++ b/db/routines/vn/procedures/invoiceOut_newFromAddress.sql
@@ -0,0 +1,56 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`invoiceOut_newFromAddress`(
+ IN vAddressFk INT,
+ IN vSerial CHAR(2),
+ IN vMaxShipped DATE,
+ IN vCompanyFk INT,
+ IN vTaxArea VARCHAR(25),
+ IN vRef VARCHAR(25),
+ OUT vInvoiceId INT)
+BEGIN
+/**
+ * Factura los tickets de un consignatario hasta una fecha dada
+ * @param vAddressFk Id del consignatario a facturar
+ * @param vSerial Serie de factura
+ * @param vMaxShipped Fecha hasta la cual cogerá tickets para facturar
+ * @param vCompanyFk Id de la empresa desde la que se factura
+ * @param vTaxArea Tipo de iva en relacion a la empresa y al cliente, NULL por defecto
+ * @param vRef Referencia de la factura en caso que se quiera forzar, NULL por defecto
+ * @return vInvoiceId factura
+ */
+ DECLARE vIsRefEditable BOOLEAN;
+
+ IF vRef IS NOT NULL AND vSerial IS NOT NULL THEN
+ SELECT isRefEditable INTO vIsRefEditable
+ FROM invoiceOutSerial
+ WHERE code = vSerial;
+
+ IF NOT vIsRefEditable THEN
+ CALL util.throw('serial non editable');
+ END IF;
+ END IF;
+
+ DROP TEMPORARY TABLE IF EXISTS `tmp`.`ticketToInvoice`;
+ CREATE TEMPORARY TABLE `tmp`.`ticketToInvoice`
+ (PRIMARY KEY (`id`))
+ ENGINE = MEMORY
+ SELECT id FROM ticket t
+ WHERE t.addressFk = vAddressFk
+ AND t.refFk IS NULL
+ AND t.companyFk = vCompanyFk
+ AND t.shipped BETWEEN
+ util.firstDayOfYear(vMaxShipped - INTERVAL 1 YEAR)
+ AND util.dayend(vMaxShipped);
+
+ CALL invoiceOut_new(vSerial, util.VN_CURDATE(), vTaxArea, vInvoiceId);
+
+ UPDATE invoiceOut
+ SET `ref` = vRef
+ WHERE id = vInvoiceId
+ AND vRef IS NOT NULL;
+
+ IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN
+ CALL invoiceOutBooking(vInvoiceId);
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemCampaign_add.sql b/db/routines/vn/procedures/itemCampaign_add.sql
new file mode 100644
index 000000000..8fb40df67
--- /dev/null
+++ b/db/routines/vn/procedures/itemCampaign_add.sql
@@ -0,0 +1,54 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemCampaign_add`()
+proc: BEGIN
+/**
+ * Añade registros a tabla itemCampaign.
+ *
+ * @param vDateFrom Fecha desde
+ * @param vDateTo Fecha hasta
+ * @param vCampaign Código de la campaña
+ */
+ DECLARE vYesterday DATE;
+ DECLARE vCampaign VARCHAR(100);
+ DECLARE vScopeDays INT;
+ DECLARE vPreviousDays INT;
+ DECLARE vDateSumFrom DATE;
+ DECLARE vDateSumTo DATE;
+
+ SET vYesterday = util.yesterday();
+
+ SELECT dated, code, scopeDays, previousDays
+ INTO vDateSumTo, vCampaign, vScopeDays, vPreviousDays
+ FROM campaign
+ WHERE dated >= vYesterday
+ ORDER BY dated
+ LIMIT 1;
+
+ IF vCampaign IS NULL THEN
+ CALL util.throw('Missing data in campaign table');
+ END IF;
+
+ IF NOT vYesterday BETWEEN vDateSumTo - INTERVAL vPreviousDays DAY
+ AND vDateSumTo THEN
+ LEAVE proc;
+ END IF;
+
+ SET vDateSumFrom = vDateSumTo - INTERVAL vScopeDays DAY;
+ SET vDateSumTo = vDateSumTo - INTERVAL 1 DAY;
+
+ INSERT INTO itemCampaign(dated, itemFk, quantity, total, campaign)
+ SELECT vYesterday,
+ s.itemFk,
+ SUM(s.quantity) quantity,
+ SUM((s.quantity * s.price) * (100 - s.discount) / 100) total,
+ vCampaign
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN client c ON c.id = t.clientFk
+ WHERE t.shipped BETWEEN vDateSumFrom AND util.dayEnd(vDateSumTo)
+ AND c.typeFk = 'normal'
+ AND NOT t.isDeleted
+ GROUP BY s.itemFk
+ HAVING quantity;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/itemPlacementSupplyAiming.sql b/db/routines/vn/procedures/itemPlacementSupplyAiming.sql
index b96860623..ae0890564 100644
--- a/db/routines/vn/procedures/itemPlacementSupplyAiming.sql
+++ b/db/routines/vn/procedures/itemPlacementSupplyAiming.sql
@@ -1,5 +1,9 @@
DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyAiming`(vShelvingFk VARCHAR(10), quantity INT, vItemFk INT)
+CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyAiming`(
+ vShelvingCode VARCHAR(10),
+ vQuantity INT,
+ vItemFk INT
+)
BEGIN
SELECT ish.itemFk,
@@ -9,21 +13,21 @@ BEGIN
ish.itemShelvingFk,
ish.shelving,
ish.stock,
- LEAST(ish.stock,quantity) as total,
+ LEAST(ish.stock,vQuantity) total,
CONCAT(
- CAST(FLOOR(LEAST(ish.stock,quantity) / ish.packing) AS DECIMAL(10,0)),
+ CAST(FLOOR(LEAST(ish.stock, vQuantity) / 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, vQuantity) MOD ish.packing,
+ CONCAT(' + ',CAST(LEAST(ish.stock, vQuantity) 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
+ LEAST(ish.stock, vQuantity)
+ ) proposal
+ FROM itemShelvingPlacementSupplyStock ish
+ WHERE ish.shelving = vShelvingCode COLLATE utf8_general_ci
AND ish.itemFk = vItemFk;
END$$
diff --git a/db/routines/vn/procedures/itemPlacementSupplyGetOrder.sql b/db/routines/vn/procedures/itemPlacementSupplyGetOrder.sql
index 958dc7e78..d2648ca6c 100644
--- a/db/routines/vn/procedures/itemPlacementSupplyGetOrder.sql
+++ b/db/routines/vn/procedures/itemPlacementSupplyGetOrder.sql
@@ -1,5 +1,7 @@
DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyGetOrder`(vSector INT )
+CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyGetOrder`(
+ vSectorFk INT
+)
BEGIN
DECLARE vId INT;
@@ -7,31 +9,35 @@ BEGIN
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
+ FROM itemShelvingPlacementSupply isps
+ JOIN itemShelving ish ON ish.id = isps.itemShelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
WHERE isps.userFk = getUser()
ORDER BY isps.created DESC
LIMIT 1;
- SET vNextParkingFk = vn.itemShelvingPlacementSupply_ClosestGet(vLastParkingFk);
+ SET vNextParkingFk = itemShelvingPlacementSupply_ClosestGet(vLastParkingFk);
SELECT ipsl.id INTO vId
- FROM vn.itemPlacementSupplyList ipsl
- JOIN vn.itemShelvingPlacementSupplyStock ispss ON ispss.itemFk = ipsl.itemFk
+ FROM itemPlacementSupplyList ipsl
+ JOIN 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
+ AND ipsl.sectorFk = vSectorFk
+ ORDER BY ipsl.repoUserFk DESC,
+ ipsl.priority DESC,
+ (ispss.parkingFk = vNextParkingFk) DESC,
+ ispss.parking DESC,
+ ipsl.created
LIMIT 1;
- UPDATE vn.itemPlacementSupply
+ UPDATE itemPlacementSupply
SET repoUserFk = getUser()
WHERE id = vId;
- SELECT * FROM vn.itemPlacementSupplyList
+ SELECT * FROM itemPlacementSupplyList
WHERE id = vId
- AND sectorFk = vSector;
+ AND sectorFk = vSectorFk;
END$$
DELIMITER ;
diff --git a/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql b/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql
index cefa64d13..92c17b82f 100644
--- a/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql
+++ b/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql
@@ -1,5 +1,8 @@
DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyStockGetTargetList`(vItemFk INT,vSectorFk INT)
+CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyStockGetTargetList`(
+ vItemFk INT,
+ vSectorFk INT
+)
BEGIN
/**
* Devuelve la lista de ubicaciones para itemFk en ese sector. Se utiliza en la preparación previa.
@@ -13,11 +16,11 @@ BEGIN
SUM(ish.visible) stockTotal,
ish.created,
p.pickingOrder
- 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 sc ON sc.id = p.sectorFk
- JOIN vn.warehouse w ON w.id = sc.warehouseFk
+ FROM itemShelving ish
+ JOIN shelving sh ON sh.id = ish.shelvingFk
+ JOIN parking p ON p.id = sh.parkingFk
+ JOIN sector sc ON sc.id = p.sectorFk
+ JOIN warehouse w ON w.id = sc.warehouseFk
WHERE ish.visible > 0
AND ish.itemFk = vItemFk
GROUP BY ish.id
diff --git a/db/routines/vn/procedures/itemShelvingLog_get.sql b/db/routines/vn/procedures/itemShelvingLog_get.sql
deleted file mode 100644
index 52e7a273f..000000000
--- a/db/routines/vn/procedures/itemShelvingLog_get.sql
+++ /dev/null
@@ -1,35 +0,0 @@
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelvingLog_get`(vShelvingFk VARCHAR(10) )
-BEGIN
-
-/**
- * Devuelve el log de los item en cada carro
- *
- * @param vShelvingFk Matrícula del carro
- *
- */
-
- SELECT isl.itemShelvingFk,
- isl.created,
- isl.accion,
- isl.itemFk,
- isl.shelvingFk,
- isl.quantity,
- isl.visible,
- isl.available,
- isl.grouping,
- isl.packing,
- isl.stars,
- item.longName,
- item.size,
- item.subName,
- worker.code,
- isl.accion
- FROM item
- JOIN itemShelvingLog isl ON item.id = isl.itemFk
- JOIN worker ON isl.workerFk = worker.id
- WHERE shelvingFk = vShelvingFk OR isl.itemFk = vShelvingFk
- ORDER BY isl.created DESC;
-
-END$$
-DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelvingMatch.sql b/db/routines/vn/procedures/itemShelvingMatch.sql
index 850c7907b..4ffa66fcb 100644
--- a/db/routines/vn/procedures/itemShelvingMatch.sql
+++ b/db/routines/vn/procedures/itemShelvingMatch.sql
@@ -20,7 +20,7 @@ BEGIN
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
+ JOIN shelving sh ON sh.id = ish.shelvingFk
LEFT JOIN parking pk ON pk.id = sh.parkingFk
WHERE ish.created BETWEEN vFromTimed AND vToTimed
GROUP BY itemFk
diff --git a/db/routines/vn/procedures/itemShelvingSale_addBySale.sql b/db/routines/vn/procedures/itemShelvingSale_addBySale.sql
index 6625e89b8..eeec60248 100644
--- a/db/routines/vn/procedures/itemShelvingSale_addBySale.sql
+++ b/db/routines/vn/procedures/itemShelvingSale_addBySale.sql
@@ -18,18 +18,19 @@ proc: BEGIN
DECLARE vReservedQuantity INT;
DECLARE vOutStanding INT;
DECLARE vUserFk INT;
- DECLARE vTotalReservedQuantity INT;
+ DECLARE vTotalReservedQuantity INT;
DECLARE vSaleQuantity INT;
+ DECLARE vIsRequiredTx BOOL DEFAULT NOT @@in_transaction;
DECLARE vItemShelvingAvailable CURSOR FOR
SELECT ish.id itemShelvingFk,
ish.available
FROM sale s
JOIN itemShelving ish ON ish.itemFk = s.itemFk
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN sector sc ON sc.id = p.sectorFk
- JOIN productionConfig pc
+ JOIN productionConfig pc
WHERE s.id = vSaleFk
AND NOT sc.isHideForPickers
AND (sc.id = vSectorFk OR vSectorFk IS NULL)
@@ -44,15 +45,15 @@ proc: BEGIN
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
- ROLLBACK;
+ CALL util.tx_rollback(vIsRequiredTx);
RESIGNAL;
END;
-
- START TRANSACTION;
-
+
+ CALL util.tx_start(vIsRequiredTx);
+
SELECT id INTO vSaleFk
FROM sale
- WHERE id = vSaleFk
+ WHERE id = vSaleFk
FOR UPDATE;
SELECT MAX(p.pickingOrder), s.quantity - SUM(IFNULL(iss.quantity, 0)), s.quantity
@@ -60,12 +61,12 @@ proc: BEGIN
FROM sale s
LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id
LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
- LEFT JOIN shelving sh ON sh.code = ish.shelvingFk
+ LEFT JOIN shelving sh ON sh.id = ish.shelvingFk
LEFT JOIN parking p ON p.id = sh.parkingFk
WHERE s.id = vSaleFk;
IF vOutStanding <= 0 THEN
- COMMIT;
+ CALL util.tx_commit(vIsRequiredTx);
LEAVE proc;
END IF;
@@ -85,7 +86,7 @@ proc: BEGIN
IF vTotalReservedQuantity <> vSaleQuantity THEN
CALL util.debugAdd('itemShelvingSale_addBySale',
CONCAT(vSaleFk, ' - ', vSaleQuantity,' - ', vTotalReservedQuantity,'-', vOutStanding,'-', account.myUser_getId()));
-
+
UPDATE sale
SET quantity = vTotalReservedQuantity
WHERE id = vSaleFk;
@@ -93,7 +94,7 @@ proc: BEGIN
LEAVE l;
END IF;
- SELECT id INTO vItemShelvingFk
+ SELECT id INTO vItemShelvingFk
FROM itemShelving
WHERE id = vItemShelvingFk
FOR UPDATE;
@@ -102,19 +103,19 @@ proc: BEGIN
SET vOutStanding = vOutStanding - vReservedQuantity;
IF vReservedQuantity > 0 THEN
- CALL util.debugAdd('itemShelvingSale_addBySale_reservedQuantity',
- CONCAT(vSaleFk, ' - ', vReservedQuantity, ' - ', vOutStanding, account.myUser_getId()));
- INSERT INTO itemShelvingSale(
- itemShelvingFk,
- saleFk,
- quantity,
- userFk,
- isPicked)
- SELECT vItemShelvingFk,
- vSaleFk,
- vReservedQuantity,
- vUserFk,
- FALSE;
+ CALL util.debugAdd('itemShelvingSale_addBySale_reservedQuantity',
+ CONCAT(vSaleFk, ' - ', vReservedQuantity, ' - ', vOutStanding, account.myUser_getId()));
+ INSERT INTO itemShelvingSale(
+ itemShelvingFk,
+ saleFk,
+ quantity,
+ userFk,
+ isPicked)
+ SELECT vItemShelvingFk,
+ vSaleFk,
+ vReservedQuantity,
+ vUserFk,
+ FALSE;
UPDATE itemShelving
SET available = available - vReservedQuantity
@@ -123,6 +124,6 @@ proc: BEGIN
END IF;
END LOOP;
CLOSE vItemShelvingAvailable;
- COMMIT;
+ CALL util.tx_commit(vIsRequiredTx);
END$$
DELIMITER ;
\ No newline at end of file
diff --git a/db/routines/vn/procedures/itemShelvingSale_deleteAdded.sql b/db/routines/vn/procedures/itemShelvingSale_deleteAdded.sql
new file mode 100644
index 000000000..9b15e82d1
--- /dev/null
+++ b/db/routines/vn/procedures/itemShelvingSale_deleteAdded.sql
@@ -0,0 +1,49 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelvingSale_deleteAdded`(
+ vSelf INT(11)
+)
+proc: BEGIN
+/**
+ * Borra una reservea devolviendo la cantidad al itemShelving
+ *
+ * @param vSelf Identificador del itemShelvingSale
+ */
+ DECLARE vSaleFk INT;
+ DECLARE vHasSalesPicked BOOL;
+
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ START TRANSACTION;
+
+ SELECT iss.saleFk INTO vSaleFk
+ FROM itemShelvingSale iss
+ JOIN sale s ON s.id = iss.saleFk
+ WHERE iss.id = vSelf AND s.isAdded
+ FOR UPDATE;
+
+ IF vSaleFk IS NULL THEN
+ CALL util.throw('The sale can not be deleted');
+ END IF;
+
+ SELECT COUNT(*) INTO vHasSalesPicked
+ FROM itemShelvingSale
+ WHERE saleFk = vSaleFk AND isPicked;
+
+ IF vHasSalesPicked THEN
+ CALL util.throw('A sale with picked sales cannot be deleted');
+ END IF;
+
+ UPDATE itemShelvingSale iss
+ JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
+ SET ish.available = ish.available + iss.quantity
+ WHERE iss.saleFk = vSaleFk;
+
+ DELETE FROM sale WHERE id = vSaleFk;
+
+ COMMIT;
+END$$
+DELIMITER ;
\ No newline at end of file
diff --git a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql
index cde1b6872..1975180d1 100644
--- a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql
+++ b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql
@@ -3,7 +3,8 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelvingSale_setQ
vItemShelvingSaleFk INT(10),
vQuantity DECIMAL(10,0),
vIsItemShelvingSaleEmpty BOOLEAN,
- vSectorFk INT
+ vSectorFk INT,
+ vShelvingFk VARCHAR(10)
)
BEGIN
/**
@@ -24,6 +25,7 @@ BEGIN
DECLARE vItemFk INT;
DECLARE vTotalQuantity INT;
DECLARE vStateCode VARCHAR(45);
+ DECLARE vCurrentShelvingFk VARCHAR(10);
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
@@ -45,18 +47,26 @@ BEGIN
iss.saleFk,
iss.itemShelvingFk,
SUM(IFNULL(iss.quantity,0)),
- IF(sgd.id, 'PREVIOUS_PREPARATION', 'PREPARED')
+ IF(sgd.id, 'PREVIOUS_PREPARATION', 'PREPARED'),
+ sh.code
INTO vItemFk,
vSaleFk,
vItemShelvingFk,
vReservedQuantity,
- vStateCode
+ vStateCode,
+ vCurrentShelvingFk
FROM itemShelvingSale iss
JOIN sale s ON s.id = iss.saleFk
- LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleFk = iss.saleFk
+ JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
+ LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = iss.saleFk
+ LEFT JOIN shelving sh ON sh.id = ish.shelvingFk
WHERE iss.id = vItemShelvingSaleFk
AND NOT iss.isPicked;
+ IF NOT (vCurrentShelvingFk <=> vShelvingFk) THEN
+ CALL util.throw('The shelving can not be different from the shelving reserved');
+ END IF;
+
IF vQuantity > vReservedQuantity
OR (vQuantity < vReservedQuantity AND NOT vIsItemShelvingSaleEmpty)
OR (vQuantity = vReservedQuantity AND vIsItemShelvingSaleEmpty) THEN
diff --git a/db/routines/vn/procedures/itemShelving_add.sql b/db/routines/vn/procedures/itemShelving_add.sql
index 92d1609e4..a8f0b5250 100644
--- a/db/routines/vn/procedures/itemShelving_add.sql
+++ b/db/routines/vn/procedures/itemShelving_add.sql
@@ -1,6 +1,6 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_add`(
- vShelvingFk VARCHAR(8),
+ vShelvingCode VARCHAR(10),
vBarcode VARCHAR(22),
vQuantity INT,
vPackagingFk VARCHAR(10),
@@ -12,7 +12,7 @@ BEGIN
/**
* Añade registro o lo actualiza si ya existe.
*
- * @param vShelvingFk matrícula del carro
+ * @param vShelvingCode matrícula del carro
* @param vBarcode el id del registro
* @param vQuantity indica la cantidad del producto
* @param vPackagingFk el packaging del producto en itemShelving, NULL para coger el de la ultima compra
@@ -23,10 +23,15 @@ BEGIN
**/
DECLARE vItemFk INT;
DECLARE vBuyFk INT;
+ DECLARE vShelvingFk INT;
SELECT id INTO vBuyFk
FROM buy WHERE id = vBarcode;
+ SELECT id INTO vShelvingFk
+ FROM shelving
+ WHERE code COLLATE utf8_unicode_ci = vShelvingCode;
+
SELECT barcodeToItem(vBarcode) INTO vItemFk;
IF vBuyFk IS NULL THEN
@@ -40,7 +45,7 @@ BEGIN
END IF;
IF (SELECT COUNT(*) FROM itemShelving
- WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk
+ WHERE shelvingFk = vShelvingFk
AND itemFk = vItemFk
AND packing = vPacking
AND buyFk = vBuyFk) THEN
@@ -48,7 +53,9 @@ BEGIN
UPDATE itemShelving
SET visible = visible + vQuantity,
available = available + vQuantity
- WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking;
+ WHERE shelvingFk = vShelvingFk
+ AND itemFk = vItemFk
+ AND packing = vPacking;
ELSE
diff --git a/db/routines/vn/procedures/itemShelving_addByClaim.sql b/db/routines/vn/procedures/itemShelving_addByClaim.sql
index 5e7cdf3fc..55ac3e337 100644
--- a/db/routines/vn/procedures/itemShelving_addByClaim.sql
+++ b/db/routines/vn/procedures/itemShelving_addByClaim.sql
@@ -1,29 +1,38 @@
DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_addByClaim`(vClaimFk INT, vShelvingFk VARCHAR(3))
+CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_addByClaim`(
+ vClaimFk INT,
+ vShelvingCode VARCHAR(10)
+)
BEGIN
/**
* Insert items of claim into itemShelving.
*
* @param vClaimFk The claim
- * @param vShelvingFk The shelving
+ * @param vShelvingCode The shelving code
* @table tmp.buyUltimate
*/
DECLARE vWarehouseFk INT;
+ DECLARE vShelvingFk INT;
SELECT t.warehouseFk INTO vWarehouseFk
FROM claim c
JOIN ticket t ON t.id = c.ticketFk
WHERE c.id = vClaimFk;
+ SELECT id INTO vShelvingFk
+ FROM shelving
+ WHERE code COLLATE utf8_unicode_ci = vShelvingCode;
+
CALL buy_getUltimate(NULL, vWarehouseFk, util.VN_CURDATE());
INSERT INTO itemShelving (itemFk, shelvingFk, packing, `grouping`, visible)
- SELECT s.itemFk, vShelvingFk, b.packing, b.`grouping`, cb.quantity AS visible
+ SELECT s.itemFk, vShelvingFk, b.packing, b.`grouping`, cb.quantity visible
FROM claim c
JOIN claimBeginning cb ON c.id = cb.claimFk
JOIN sale s ON s.id = cb.saleFk
JOIN ticket t ON t.id = s.ticketFk
- JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk AND bu.warehouseFk = t.warehouseFk
+ JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
+ AND bu.warehouseFk = t.warehouseFk
JOIN buy b ON b.id = bu.buyFk
WHERE c.id = vClaimFk;
END$$
diff --git a/db/routines/vn/procedures/itemShelving_addList.sql b/db/routines/vn/procedures/itemShelving_addList.sql
index 05b392485..04fa1e10c 100644
--- a/db/routines/vn/procedures/itemShelving_addList.sql
+++ b/db/routines/vn/procedures/itemShelving_addList.sql
@@ -1,16 +1,22 @@
DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_addList`(vShelvingFk VARCHAR(3), vList TEXT, vIsChecking BOOL, vWarehouseFk INT)
+CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_addList`(
+ vShelvingCode VARCHAR(10),
+ vList TEXT,
+ vIsChecking BOOL,
+ vWarehouseFk INT
+)
BEGIN
-/* Recorre cada elemento en la colección vList.
+/**
+ * Recorre cada elemento en la colección vList.
* Si el parámetro isChecking = FALSE, llama a itemShelving_add.
*
* Cuando es TRUE sólo inserta los elementos de la colección que no están ya en
- * ese shelving, actualizando los valores del campo vn.itemShelving.isChecked
+ * ese shelving, actualizando los valores del campo itemShelving.isChecked
*
- * param vShelvingFk Identificador de vn.shelving
- * param vList JSON array con esta estructura: '[value1, value2, ...]'
- * param vIsChecking Define si hay que añadir o comprobar los items
- * param vWarehouseFk Identificador de vn.warehouse
+ * @param vShelvingCode Código de shelving
+ * @param vList JSON array con esta estructura: '[value1, value2, ...]'
+ * @param vIsChecking Define si hay que añadir o comprobar los items
+ * @param vWarehouseFk Identificador de warehouse
*/
DECLARE vListLength INT DEFAULT JSON_LENGTH(vList);
DECLARE vCounter INT DEFAULT 0;
@@ -18,28 +24,34 @@ BEGIN
DECLARE vPath VARCHAR(6);
DECLARE vItemFk INT;
DECLARE vIsChecked BOOL;
+ DECLARE vShelvingFk INT;
+
+ SELECT id INTO vShelvingFk
+ FROM shelving
+ WHERE code COLLATE utf8_unicode_ci = vShelvingCode;
WHILE vCounter < vListLength DO
- SET vPath = CONCAT('$[',vCounter,']');
- SET vBarcode = JSON_EXTRACT(vList,vPath);
+ SET vPath = CONCAT('$[', vCounter, ']');
+ SET vBarcode = JSON_EXTRACT(vList, vPath);
SET vIsChecked = NULL;
IF vIsChecking THEN
SELECT barcodeToItem(vBarcode) INTO vItemFk;
- SELECT COUNT(*) INTO vIsChecked
- FROM vn.itemShelving
- WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk
+ SELECT IF(COUNT(*), TRUE, FALSE) INTO vIsChecked
+ FROM itemShelving
+ WHERE shelvingFk = vShelvingFk
AND itemFk = vItemFk;
END IF;
- IF NOT (vIsChecking AND vIsChecked) THEN
- CALL vn.itemShelving_add(vShelvingFk, vBarcode, 1, NULL, NULL, NULL, vWarehouseFk);
+ IF NOT vIsChecking OR NOT vIsChecked THEN
+ CALL itemShelving_add(vShelvingCode, vBarcode, 1, NULL, NULL, NULL, vWarehouseFk);
END IF;
- UPDATE vn.itemShelving
+ UPDATE itemShelving
SET isChecked = vIsChecked
- WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk
- AND itemFk = vItemFk AND isChecked IS NULL;
+ WHERE shelvingFk = vShelvingFk
+ AND itemFk = vItemFk
+ AND isChecked IS NULL;
SET vCounter = vCounter + 1;
END WHILE;
diff --git a/db/routines/vn/procedures/itemShelving_get.sql b/db/routines/vn/procedures/itemShelving_get.sql
index 606bb8bd9..0038257c2 100644
--- a/db/routines/vn/procedures/itemShelving_get.sql
+++ b/db/routines/vn/procedures/itemShelving_get.sql
@@ -1,15 +1,18 @@
DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_get`(IN vSelf VARCHAR(8))
+CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_get`(
+ vShelvingCode VARCHAR(10)
+)
BEGIN
/**
-* Lista artículos de itemshelving
+* Lista artículos de itemShelving.
*
-* @param vSelf matrícula del carro
+* @param vShelvingCode Matrícula del carro
**/
SELECT ish.itemFk item,
- IFNULL(i.longName, CONCAT(i.name, ' ', i.size)) description,
+ i.name,
+ i.longName,
+ i.size,
ish.visible,
- CEIL(ish.visible/ish.packing) stickers,
ish.packing,
ish.grouping,
p.code,
@@ -17,12 +20,14 @@ BEGIN
s.priority,
ish.isChecked,
ic.url,
- ish.available
+ ish.available,
+ ish.buyFk,
+ ish.shelvingFk
FROM itemShelving ish
JOIN item i ON i.id = ish.itemFk
- JOIN shelving s ON vSelf = s.code COLLATE utf8_unicode_ci
- LEFT JOIN parking p ON s.parkingFk = p.id
+ JOIN shelving s ON s.id = ish.shelvingFk
+ LEFT JOIN parking p ON p.id = s.parkingFk
JOIN hedera.imageConfig ic
- WHERE ish.shelvingFk COLLATE utf8_unicode_ci = vSelf;
+ WHERE s.code COLLATE utf8_unicode_ci = vShelvingCode;
END$$
DELIMITER ;
diff --git a/db/routines/vn/procedures/itemShelving_getAlternatives.sql b/db/routines/vn/procedures/itemShelving_getAlternatives.sql
index 89176c4f5..3eff3254b 100644
--- a/db/routines/vn/procedures/itemShelving_getAlternatives.sql
+++ b/db/routines/vn/procedures/itemShelving_getAlternatives.sql
@@ -1,21 +1,31 @@
DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_getAlternatives`(vShelvingFk VARCHAR(10))
+CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_getAlternatives`(
+ vShelvingCode VARCHAR(10)
+)
BEGIN
/**
- * Devuelve un listado de posibles ubicaciones alternativas a ubicar los item de la matricula
- * del carro que se le ha pasado.
+ * Devuelve un listado de posibles ubicaciones alternativas a ubicar
+ * los item de la matricula del carro que se le ha pasado.
*
- * @param vShelvingFk matricula del carro
+ * @param vShelvingCode Matricula del carro
*/
- SELECT is2.id,is2.shelvingFk , p.code, is2.itemFk , is2.visible, p.pickingOrder
+ DECLARE vShelvingFk INT;
+
+ SELECT id INTO vShelvingFk
+ FROM shelving
+ WHERE code COLLATE utf8_unicode_ci = vShelvingCode;
+
+ SELECT is2.id,is2.shelvingFk, p.code, is2.itemFk , is2.visible, p.pickingOrder
FROM itemShelving is2
- JOIN shelving sh ON sh.code = is2.shelvingFk
+ JOIN shelving sh ON sh.id = is2.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN sector s ON s.id = p.sectorFk
- LEFT JOIN operator o ON o.sectorFk = s.id AND o.workerFk = account.myUser_getId()
+ LEFT JOIN operator o ON o.sectorFk = s.id
+ AND o.workerFk = account.myUser_getId()
JOIN warehouse wh ON wh.id = s.warehouseFk
- JOIN itemShelving is3 ON is3.itemFk = is2.itemFk AND is3.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci
- WHERE is2.shelvingFk <> vShelvingFk COLLATE utf8_unicode_ci
+ JOIN itemShelving is3 ON is3.itemFk = is2.itemFk
+ AND is3.shelvingFk = vShelvingFk
+ WHERE is2.shelvingFk <> vShelvingFk
GROUP BY is2.id
ORDER BY p.pickingOrder DESC;
END$$
diff --git a/db/routines/vn/procedures/itemShelving_getInfo.sql b/db/routines/vn/procedures/itemShelving_getInfo.sql
index f02100e8b..f4c8c5b35 100644
--- a/db/routines/vn/procedures/itemShelving_getInfo.sql
+++ b/db/routines/vn/procedures/itemShelving_getInfo.sql
@@ -16,7 +16,7 @@ BEGIN
ish.itemFk itemFk,
sh.priority
FROM vn.itemShelving ish
- JOIN vn.shelving sh ON sh.`code` = ish.shelvingFk
+ JOIN vn.shelving sh ON sh.id = ish.shelvingFk
JOIN vn.parking pk ON pk.id = sh.parkingFk
WHERE ish.itemFk = vItemFk
ORDER BY sh.priority DESC, created ASC;
diff --git a/db/routines/vn/procedures/itemShelving_getItemDetails.sql b/db/routines/vn/procedures/itemShelving_getItemDetails.sql
index 4e641ca72..36f9830f0 100644
--- a/db/routines/vn/procedures/itemShelving_getItemDetails.sql
+++ b/db/routines/vn/procedures/itemShelving_getItemDetails.sql
@@ -1,14 +1,14 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_getItemDetails`(
vBarcodeItem INT,
- vShelvingFK VARCHAR(10)
+ vShelvingCode VARCHAR(10)
)
BEGIN
/**
* Obtiene el precio y visible de un item
*
* @param vBarcodeItem barcode de artículo
- * @param vShelvingFK Ubicación actual del artículo
+ * @param vShelvingCode Ubicación actual del artículo
*/
DECLARE vIsItem BOOL;
DECLARE vBuyFk INT;
@@ -38,18 +38,19 @@ BEGIN
WITH visible AS(
SELECT itemFk,
IFNULL(buyingValue, 0) +
- IFNULL(freightValue, 0) +
- IFNULL(comissionValue, 0) +
- IFNULL(packageValue, 0) itemCost
- FROM vn.buy b
+ IFNULL(freightValue, 0) +
+ IFNULL(comissionValue, 0) +
+ IFNULL(packageValue, 0) itemCost
+ FROM vn.buy b
WHERE b.id = vBuyFk
) SELECT v.itemFk,
- vShelvingFK,
+ vShelvingCode,
v.itemCost,
SUM(ish.visible) visible
FROM vn.itemShelving ish
+ JOIN vn.shelving sh ON sh.id = ish.shelvingFK
JOIN visible v
- WHERE ish.shelvingFK = vShelvingFK COLLATE utf8mb3_general_ci
- AND ish.itemFk = v.itemFk;
+ WHERE sh.code = vShelvingCode COLLATE utf8mb3_general_ci
+ AND ish.itemFk = v.itemFk;
END$$
DELIMITER ;
\ No newline at end of file
diff --git a/db/routines/vn/procedures/itemShelving_getSaleDate.sql b/db/routines/vn/procedures/itemShelving_getSaleDate.sql
index d8ab6ed0c..fad4d5abc 100644
--- a/db/routines/vn/procedures/itemShelving_getSaleDate.sql
+++ b/db/routines/vn/procedures/itemShelving_getSaleDate.sql
@@ -1,14 +1,20 @@
DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_getSaleDate`(vShelvingFk VARCHAR(3))
+CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_getSaleDate`(
+ vShelvingCode VARCHAR(10)
+)
BEGIN
-
- /* Devuelve la mínima fecha en que se necesita cada producto en esa matrícula.
- *
- * @param vShelvingFk Matrícula del carro o pallet
- */
-
+/**
+ * Devuelve la mínima fecha en que se necesita cada producto en esa matrícula.
+ *
+ * @param vShelvingCode Matrícula del carro o pallet
+ */
DECLARE vWarehouseFk INT;
DECLARE vStockScopeDays INT;
+ DECLARE vShelvingFk INT;
+
+ SELECT id INTO vShelvingFk
+ FROM shelving
+ WHERE code COLLATE utf8_unicode_ci = vShelvingCode;
SELECT s.warehouseFk, stockScopeDays
INTO vWarehouseFk, vStockScopeDays
@@ -30,7 +36,7 @@ BEGIN
ENGINE = MEMORY
SELECT itemFk, SUM(visible) visible
FROM itemShelving
- WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci
+ WHERE shelvingFk = vShelvingFk
GROUP BY itemFk;
CREATE OR REPLACE TEMPORARY TABLE tmp.tStockByDay
@@ -52,7 +58,7 @@ BEGIN
SELECT ish.itemFk, - SUM(ish.visible), util.VN_CURDATE()
FROM itemShelving ish
JOIN tmp.tItems i ON i.itemFk = ish.itemFk
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON sh.parkingFk = p.id
JOIN sector s ON s.id = p.sectorFk
WHERE s.isReserve
@@ -110,7 +116,7 @@ BEGIN
UPDATE tmp.tStockByDay sbd
JOIN (SELECT ish.itemFK, SUM(ish.visible) amount
FROM itemShelving ish
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN sector s ON s.id = p.sectorFk
WHERE s.warehouseFk = vWarehouseFk
@@ -150,10 +156,10 @@ BEGIN
p.sectorFk,
ish.shelvingFk
FROM itemShelving ish
- JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.shelving sh ON sh.id = ish.shelvingFk
LEFT JOIN parking p ON p.id = parkingFk
LEFT JOIN vn.sector s ON s.id = p.sectorFk
- WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci
+ WHERE ish.shelvingFk = vShelvingFk
) sub4 ON sub4.itemFk = ts.itemFk
LEFT JOIN sector s ON s.id = sub4.sectorFk
LEFT JOIN item i ON i.id = ts.itemFk
diff --git a/db/routines/vn/procedures/itemShelving_inventory.sql b/db/routines/vn/procedures/itemShelving_inventory.sql
index b57df02e0..9ae96c7a8 100644
--- a/db/routines/vn/procedures/itemShelving_inventory.sql
+++ b/db/routines/vn/procedures/itemShelving_inventory.sql
@@ -42,7 +42,7 @@ BEGIN
JOIN item i ON i.id = ish.itemFk
JOIN itemType it ON it.id = i.typeFk
JOIN tmp.stockMisfit sm ON sm.itemFk = ish.itemFk
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
LEFT JOIN (
SELECT s.itemFk, sum(s.quantity) notPrepared
diff --git a/db/routines/vn/procedures/itemShelving_selfConsumption.sql b/db/routines/vn/procedures/itemShelving_selfConsumption.sql
index 083d8d74c..5820b9d28 100644
--- a/db/routines/vn/procedures/itemShelving_selfConsumption.sql
+++ b/db/routines/vn/procedures/itemShelving_selfConsumption.sql
@@ -1,6 +1,6 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_selfConsumption`(
- vShelvingFk VARCHAR(10) COLLATE utf8_general_ci,
+ vShelvingCode VARCHAR(10) COLLATE utf8_general_ci,
vItemFk INT,
vQuantity INT
)
@@ -9,9 +9,9 @@ BEGIN
* Leave the indicated amount on the shelve
* and create a ticket with the difference.
*
- * @param vShelvingFk id of the shelve where the item is located.
- * @param vItemFk article of which the self-consumption ticket is to be created.
- * @param vQuantity amount that will stay on the shelve
+ * @param vShelvingCode Code of the shelve where the item is located
+ * @param vItemFk Item of which the self-consumption ticket is to be created
+ * @param vQuantity Amount that will stay on the shelve
*/
DECLARE vVisible INT;
DECLARE vClientFk INT;
@@ -21,6 +21,11 @@ BEGIN
DECLARE vAgencyModeFk INT;
DECLARE vItemShelvingFk INT;
DECLARE vAddressFk INT;
+ DECLARE vShelvingFk INT;
+
+ SELECT id INTO vShelvingFk
+ FROM shelving
+ WHERE code = vShelvingCode;
SELECT c.id,
pc.clientSelfConsumptionFk,
@@ -37,7 +42,7 @@ BEGIN
JOIN parking p ON p.sectorFk = s.id
JOIN shelving s2 ON s2.parkingFk = p.id
JOIN productionConfig pc
- WHERE s2.code = vShelvingFk;
+ WHERE s2.id = vShelvingFk;
IF vClientFk IS NULL THEN
CALL util.throw('The company does not have a customer assigned');
@@ -47,7 +52,7 @@ BEGIN
CALL util.throw('The shelf cannot have NULL or negative quantities');
END IF;
- IF vShelvingFk IS NULL THEN
+ IF vShelvingCode IS NULL THEN
CALL util.throw('The shelf is necessary');
END IF;
diff --git a/db/routines/vn/procedures/itemShelving_transfer.sql b/db/routines/vn/procedures/itemShelving_transfer.sql
index 95d70227f..e0e6af110 100644
--- a/db/routines/vn/procedures/itemShelving_transfer.sql
+++ b/db/routines/vn/procedures/itemShelving_transfer.sql
@@ -1,7 +1,7 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_transfer`(
vItemShelvingFk INT,
- vShelvingFk VARCHAR(10)
+ vShelvingCode VARCHAR(10)
)
BEGIN
/**
@@ -9,9 +9,14 @@ BEGIN
* fusionando si coincide el packing y la fecha.
*
* @param vItemShelvingFk Identificador de itemShelving
- * @param vShelvingFk Identificador de shelving
+ * @param vShelvingCode Código de shelving
*/
DECLARE vNewItemShelvingFk INT;
+ DECLARE vShelvingFk INT;
+
+ SELECT id INTO vShelvingFk
+ FROM shelving
+ WHERE code COLLATE utf8_unicode_ci = vShelvingCode;
SELECT MAX(ish.id) INTO vNewItemShelvingFk
FROM itemShelving ish
@@ -26,7 +31,7 @@ BEGIN
AND ish2.packing = ish.packing
AND DATE(ish2.created) = DATE(ish.created)
AND ish2.buyFk = ish.buyFk
- WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci;
+ WHERE ish.shelvingFk = vShelvingFk;
IF vNewItemShelvingFk THEN
UPDATE itemShelving ish
@@ -38,9 +43,7 @@ BEGIN
DELETE FROM itemShelving
WHERE id = vItemShelvingFk;
ELSE
- IF (SELECT EXISTS(SELECT id FROM shelving
- WHERE code = vShelvingFk COLLATE utf8_unicode_ci)) THEN
-
+ IF (SELECT EXISTS(SELECT id FROM shelving WHERE id = vShelvingFk)) THEN
UPDATE itemShelving
SET shelvingFk = vShelvingFk
WHERE id = vItemShelvingFk;
diff --git a/db/routines/vn/procedures/item_cleanFloramondo.sql b/db/routines/vn/procedures/item_cleanFloramondo.sql
index 849cfe93d..21d8ebe3c 100644
--- a/db/routines/vn/procedures/item_cleanFloramondo.sql
+++ b/db/routines/vn/procedures/item_cleanFloramondo.sql
@@ -164,10 +164,6 @@ BEGIN
SET itemFk = vItemNew
WHERE itemFk = vItemOld;
- UPDATE inventoryFailure
- SET itemFk = vItemNew
- WHERE itemFk = vItemOld;
-
UPDATE genericAllocation
SET itemFk = vItemNew
WHERE itemFk = vItemOld;
diff --git a/db/routines/vn/procedures/item_devalueA2.sql b/db/routines/vn/procedures/item_devalueA2.sql
index d0178f6a7..3264165a6 100644
--- a/db/routines/vn/procedures/item_devalueA2.sql
+++ b/db/routines/vn/procedures/item_devalueA2.sql
@@ -1,7 +1,7 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`item_devalueA2`(
vSelf INT,
- vShelvingFK VARCHAR(10),
+ vShelvingCode VARCHAR(10) COLLATE utf8mb3_general_ci,
vBuyingValue DECIMAL(10,4),
vQuantity INT
)
@@ -12,7 +12,7 @@ BEGIN
* de almacén y shelvings correspondientes
*
* @param vSelf Id de artículo a devaluar
- * @param vShelvingFK Ubicación actual del artículo
+ * @param vShelvingCode Código de shelving / ubicación
* @param vBuyingValue Nuevo precio de coste
* @param vQuantity Cantidad del ítem a pasar a A2
*/
@@ -109,10 +109,11 @@ BEGIN
CALL util.throw ('The item has not a buy');
END IF;
- SELECT id,visible INTO vTargetItemShelvingFk, vCurrentVisible
- FROM itemShelving
- WHERE shelvingFk = vShelvingFK COLLATE utf8mb3_general_ci
- AND itemFk = vSelf
+ SELECT ish.id, ish.visible INTO vTargetItemShelvingFk, vCurrentVisible
+ FROM itemShelving ish
+ JOIN shelving sh ON sh.id = ish.shelvingFk
+ WHERE sh.code = vShelvingCode
+ AND ish.itemFk = vSelf
LIMIT 1;
IF vCurrentVisible IS NULL THEN
@@ -388,16 +389,17 @@ BEGIN
userFk,
isChecked)
SELECT vItemA2Fk,
- shelvingFk,
+ ish.shelvingFk,
vQuantity ,
- `grouping`,
- packing,
- packagingFk,
+ ish.`grouping`,
+ ish.packing,
+ ish.packagingFk,
account.myUser_getId(),
- isChecked
- FROM itemShelving
- WHERE itemFK = vSelf
- AND shelvingFk = vShelvingFK COLLATE utf8mb3_general_ci
+ ish.isChecked
+ FROM itemShelving ish
+ JOIN shelving sh ON sh.id = ish.shelvingFk
+ WHERE ish.itemFK = vSelf
+ AND sh.code = vShelvingCode
ON DUPLICATE KEY UPDATE
visible = vQuantity + VALUES(visible);
diff --git a/db/routines/vn/procedures/item_getBalance.sql b/db/routines/vn/procedures/item_getBalance.sql
index 4aa589d19..c4974491c 100644
--- a/db/routines/vn/procedures/item_getBalance.sql
+++ b/db/routines/vn/procedures/item_getBalance.sql
@@ -50,16 +50,16 @@ BEGIN
JOIN vn.entry e ON e.id = b.entryFk
JOIN vn.travel tr ON tr.id = e.travelFk
JOIN vn.supplier s ON s.id = e.supplierFk
- JOIN vn.state st ON st.`code` = IF(tr.landed < util.VN_CURDATE()
+ JOIN vn.state st ON st.`code` = IF(tr.landed < util.VN_CURDATE()
OR (util.VN_CURDATE() AND tr.isReceived),
'DELIVERED',
'FREE')
WHERE tr.landed >= vDateInventory
AND tr.warehouseInFk = vWarehouseFk
- AND (s.id <> vSupplierInventoryFk OR vDated IS NULL)
+ AND (s.id <> vSupplierInventoryFk OR vDated IS NULL)
AND b.itemFk = vItemFk
AND NOT e.isExcludedFromAvailable
- AND NOT e.isRaid
+ AND NOT tr.isRaid
),
entriesOut AS (
SELECT 'entry',
@@ -95,7 +95,7 @@ BEGIN
AND b.itemFk = vItemFk
AND NOT e.isExcludedFromAvailable
AND NOT w.isFeedStock
- AND NOT e.isRaid
+ AND NOT tr.isRaid
),
sales AS (
WITH itemSales AS (
@@ -147,10 +147,10 @@ BEGIN
NULL
FROM itemSales s
LEFT JOIN vn.state stPrep ON stPrep.`code` = 'PREPARED'
- LEFT JOIN vn.saleTracking stk ON stk.saleFk = s.saleFk
+ LEFT JOIN vn.saleTracking stk ON stk.saleFk = s.saleFk
AND stk.stateFk = stPrep.id
GROUP BY s.saleFk
- ),
+ ),
orders AS (
SELECT 'order' originType,
o.id originId,
@@ -215,9 +215,9 @@ BEGIN
t.`in` invalue,
t.`out`,
@a := @a + IFNULL(t.`in`, 0) - IFNULL(t.`out`, 0) balance,
- @currentLineFk := IF (@shipped < util.VN_CURDATE()
+ @currentLineFk := IF (@shipped < util.VN_CURDATE()
OR (@shipped = util.VN_CURDATE() AND (t.isPicked OR a.`code` >= 'ON_PREPARATION')),
- t.lineFk,
+ t.lineFk,
@currentLineFk) lastPreparedLineFk,
t.isTicket,
t.lineFk,
@@ -254,21 +254,21 @@ BEGIN
UNION ALL
SELECT originType,
originId,
- shipped,
- alertlevel,
- stateName,
+ shipped,
+ alertlevel,
+ stateName,
reference,
entityType,
- entityId,
+ entityId,
entityName,
- `in`,
- `out`,
- @a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0),
- 0,
- isTicket,
- lineFk,
- isPicked,
- clientType,
+ `in`,
+ `out`,
+ @a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0),
+ 0,
+ isTicket,
+ lineFk,
+ isPicked,
+ clientType,
claimFk,
`order`
FROM tItemDiary
diff --git a/db/routines/vn/procedures/item_getInfo.sql b/db/routines/vn/procedures/item_getInfo.sql
index 341142892..bd59728f7 100644
--- a/db/routines/vn/procedures/item_getInfo.sql
+++ b/db/routines/vn/procedures/item_getInfo.sql
@@ -42,7 +42,6 @@ BEGIN
i.minimum `min`,
p.name producer,
o.code origin,
- v.visible - IFNULL(vVisibleItemShelving, 0) unlocated,
a.available,
vVisibleItemShelving,
v.visible,
diff --git a/db/routines/vn/procedures/item_getMinacum.sql b/db/routines/vn/procedures/item_getMinacum.sql
index 85474fc3f..e3c915820 100644
--- a/db/routines/vn/procedures/item_getMinacum.sql
+++ b/db/routines/vn/procedures/item_getMinacum.sql
@@ -63,7 +63,7 @@ BEGIN
AND NOT e.isExcludedFromAvailable
AND b.quantity <> 0
AND (vItemFk IS NULL OR b.itemFk = vItemFk)
- AND NOT e.isRaid
+ AND NOT t.isRaid
UNION ALL
SELECT r.itemFk,
r.shipment,
diff --git a/db/routines/vn/procedures/item_getSimilar.sql b/db/routines/vn/procedures/item_getSimilar.sql
index 56afd92e9..336f3521e 100644
--- a/db/routines/vn/procedures/item_getSimilar.sql
+++ b/db/routines/vn/procedures/item_getSimilar.sql
@@ -8,19 +8,23 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`item_getSimilar`(
)
BEGIN
/**
-* Propone articulos ordenados, con la cantidad
-* de veces usado y segun sus caracteristicas.
-*
-* @param vSelf Id de artículo
-* @param vWarehouseFk Id de almacen
-* @param vDated Fecha
-* @param vShowType Mostrar tipos
-* @param vDaysInForward Días de alcance para las ventas
-*/
+ * Propone articulos ordenados, con la cantidad
+ * de veces usado y segun sus caracteristicas.
+ *
+ * @param vSelf Id de artículo
+ * @param vWarehouseFk Id de almacen
+ * @param vDated Fecha
+ * @param vShowType Mostrar tipos
+ * @param vDaysInForward Días de alcance para las ventas (https://redmine.verdnatura.es/issues/7956#note-4)
+ */
DECLARE vAvailableCalcFk INT;
+ DECLARE vVisibleCalcFk INT;
+ DECLARE vTypeFk INT;
DECLARE vPriority INT DEFAULT 1;
CALL cache.available_refresh(vAvailableCalcFk, FALSE, vWarehouseFk, vDated);
+ CALL cache.visible_refresh(vVisibleCalcFk, FALSE, vWarehouseFk);
+ CALL buy_getUltimate(NULL, vWarehouseFk, vDated);
WITH itemTags AS (
SELECT i.id,
@@ -40,25 +44,9 @@ BEGIN
AND it.priority = vPriority
LEFT JOIN vn.tag t ON t.id = it.tagFk
WHERE i.id = vSelf
- ),
- stock AS (
- SELECT itemFk, SUM(visible) stock
- FROM vn.itemShelvingStock
- WHERE warehouseFk = vWarehouseFk
- GROUP BY itemFk
- ),
- sold AS (
- SELECT SUM(s.quantity) quantity, s.itemFk
- FROM vn.sale s
- JOIN vn.ticket t ON t.id = s.ticketFk
- LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id
- WHERE t.shipped >= CURDATE() + INTERVAL vDaysInForward DAY
- AND iss.saleFk IS NULL
- AND t.warehouseFk = vWarehouseFk
- GROUP BY s.itemFk
)
SELECT i.id itemFk,
- LEAST(CAST(sd.quantity AS INT), sk.stock) advanceable,
+ NULL advanceable, -- https://redmine.verdnatura.es/issues/7956#note-4
i.longName,
i.subName,
i.tag5,
@@ -80,37 +68,37 @@ BEGIN
WHEN b.groupingMode = 'packing' THEN b.packing
ELSE 1
END minQuantity,
- sk.stock located,
+ v.visible located,
b.price2
FROM vn.item i
- LEFT JOIN sold sd ON sd.itemFk = i.id
JOIN cache.available a ON a.item_id = i.id
AND a.calc_id = vAvailableCalcFk
- LEFT JOIN stock sk ON sk.itemFk = i.id
- LEFT JOIN cache.last_buy lb ON lb.item_id = i.id
- AND lb.warehouse_id = vWarehouseFk
+ LEFT JOIN cache.visible v ON v.item_id = i.id
+ AND v.calc_id = vVisibleCalcFk
+ LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.id
LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id
AND ip.itemFk = vSelf
LEFT JOIN vn.itemTag it ON it.itemFk = i.id
AND it.priority = vPriority
LEFT JOIN vn.tag t ON t.id = it.tagFk
- LEFT JOIN vn.buy b ON b.id = lb.buy_id
+ LEFT JOIN vn.buy b ON b.id = bu.buyFk
JOIN itemTags its
- WHERE (a.available > 0 OR sd.quantity < sk.stock)
+ WHERE a.available > 0
AND (i.typeFk = its.typeFk OR NOT vShowType)
AND i.id <> vSelf
- ORDER BY (a.available > 0) DESC,
- `counter` DESC,
- (t.name = its.name) DESC,
- (it.value = its.value) DESC,
- (i.tag5 = its.tag5) DESC,
- match5 DESC,
- (i.tag6 = its.tag6) DESC,
- match6 DESC,
- (i.tag7 = its.tag7) DESC,
- match7 DESC,
- (i.tag8 = its.tag8) DESC,
- match8 DESC
+ ORDER BY `counter` DESC,
+ (t.name = its.name) DESC,
+ (it.value = its.value) DESC,
+ (i.tag5 = its.tag5) DESC,
+ match5 DESC,
+ (i.tag6 = its.tag6) DESC,
+ match6 DESC,
+ (i.tag7 = its.tag7) DESC,
+ match7 DESC,
+ (i.tag8 = its.tag8) DESC,
+ match8 DESC
LIMIT 100;
+
+ DROP TEMPORARY TABLE tmp.buyUltimate;
END$$
DELIMITER ;
diff --git a/db/routines/vn/procedures/item_multipleBuyByDate.sql b/db/routines/vn/procedures/item_multipleBuyByDate.sql
index 115202895..04d3f1855 100644
--- a/db/routines/vn/procedures/item_multipleBuyByDate.sql
+++ b/db/routines/vn/procedures/item_multipleBuyByDate.sql
@@ -17,22 +17,22 @@ BEGIN
ALTER TABLE tmp.itemInventory
ADD `buy_date` datetime NOT NULL;
-
+
CREATE OR REPLACE TEMPORARY TABLE lastBuyScope
SELECT i.id, MAX(t.landed) lastLanded
- FROM item i
- JOIN buy b ON b.itemFk = i.id
+ FROM item i
+ JOIN buy b ON b.itemFk = i.id
JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
+ JOIN travel t ON t.id = e.travelFk
JOIN supplier s ON s.id = e.supplierFk
JOIN warehouse w ON w.id = t.warehouseInFk
WHERE t.landed BETWEEN (vDated + INTERVAL - vLastBuyScope DAY) AND vDated
AND NOT s.name = 'INVENTARIO'
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND w.isComparative
- AND NOT e.isRaid
+ AND NOT t.isRaid
GROUP BY i.id;
-
+
UPDATE tmp.itemInventory y
JOIN lastBuyScope lbs ON lbs.id = y.id
SET y.buy_date = lbs.lastLanded;
diff --git a/db/routines/vn/procedures/item_valuateInventory.sql b/db/routines/vn/procedures/item_valuateInventory.sql
index 5642ba812..7e420be27 100644
--- a/db/routines/vn/procedures/item_valuateInventory.sql
+++ b/db/routines/vn/procedures/item_valuateInventory.sql
@@ -25,7 +25,7 @@ BEGIN
LIMIT 1;
SET vHasNotInventory = (vInventoried IS NULL);
-
+
IF vHasNotInventory THEN
SELECT landed INTO vInventoryClone
FROM travel tr
@@ -50,7 +50,7 @@ BEGIN
PRIMARY KEY (warehouseInventory, itemFk) USING HASH
)
ENGINE = MEMORY;
-
+
-- Inventario inicial
IF vHasNotInventory THEN
INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
@@ -109,7 +109,7 @@ BEGIN
JOIN warehouse w ON w.id = tr.warehouseInFk
WHERE tr.landed BETWEEN vInventoried AND vDateDayEnd
AND IF(tr.landed = util.VN_CURDATE(), tr.isReceived, TRUE)
- AND NOT e.isRaid
+ AND NOT tr.isRaid
AND w.valuatedInventory
AND t.isInventory
AND e.supplierFk <> vInventorySupplierFk
@@ -131,7 +131,7 @@ BEGIN
JOIN itemCategory ic ON ic.id = t.categoryFk
JOIN warehouse w ON w.id = tr.warehouseOutFk
WHERE tr.shipped BETWEEN vInventoried AND vDateDayEnd
- AND NOT e.isRaid
+ AND NOT tr.isRaid
AND w.valuatedInventory
AND t.isInventory
AND (t.id = vItemTypeFk OR vItemTypeFk IS NULL)
@@ -159,7 +159,7 @@ BEGIN
ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + s.quantity * IF(vHasNotInventory, 1, -1);
-- Volver a poner lo que esta aun en las estanterias
- IF vDated = util.VN_CURDATE() THEN
+ IF vDated = util.VN_CURDATE() THEN
INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
SELECT w.id,
s.itemFk,
@@ -196,14 +196,14 @@ BEGIN
JOIN warehouse wIn ON wIn.id = tr.warehouseInFk
JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk
WHERE vDated >= tr.shipped AND vDated < tr.landed
- AND NOT isRaid
+ AND NOT tr.isRaid
AND wIn.valuatedInventory
AND t.isInventory
AND e.isConfirmed
AND (t.id = vItemTypeFk OR vItemTypeFk IS NULL)
AND (ic.id = vItemCategoryFk OR vItemCategoryFk IS NULL)
ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity);
-
+
CALL buy_getUltimate (NULL, NULL, vDateDayEnd);
DELETE FROM tInventory WHERE quantity IS NULL OR NOT quantity;
@@ -233,7 +233,7 @@ BEGIN
JOIN warehouse w ON w.id = warehouseFk
JOIN item i ON i.id = ti.itemFk
JOIN itemType tp ON tp.id = i.typeFk
- JOIN itemCategory ic ON ic.id = tp.categoryFk
+ JOIN itemCategory ic ON ic.id = tp.categoryFk
WHERE w.valuatedInventory
AND ti.total > 0;
diff --git a/db/routines/vn/procedures/machineWorker_add.sql b/db/routines/vn/procedures/machineWorker_add.sql
deleted file mode 100644
index 41000f556..000000000
--- a/db/routines/vn/procedures/machineWorker_add.sql
+++ /dev/null
@@ -1,22 +0,0 @@
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`machineWorker_add`(vPlate VARCHAR(10), vWorkerFk INT)
-BEGIN
-
-/**
- * Inserta registro si el vWorkerFk no ha registrado nada en las últimas 12 horas
- * @param vPlate número de matrícula
- * @param vWorkerFk id del worker
- *
-*/
- UPDATE vn.machineWorker mw
- JOIN vn.machine m ON m.id = mw.machineFk
- SET mw.outTimed = util.VN_NOW()
- WHERE (mw.workerFk = vWorkerFk OR m.plate = vPlate)
- AND ISNULL(mw.outTimed);
-
- INSERT INTO machineWorker (machineFk, workerFk)
- SELECT m.id, vWorkerFk
- FROM machine m
- WHERE m.plate= vPlate;
-END$$
-DELIMITER ;
diff --git a/db/routines/vn/procedures/machineWorker_getHistorical.sql b/db/routines/vn/procedures/machineWorker_getHistorical.sql
deleted file mode 100644
index 67b1971a2..000000000
--- a/db/routines/vn/procedures/machineWorker_getHistorical.sql
+++ /dev/null
@@ -1,21 +0,0 @@
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`machineWorker_getHistorical`(vPlate VARCHAR(20), vWorkerFk INT)
-BEGIN
-/**
- * Obtiene historial de la matrícula vPlate que el trabajador vWorkerFk escanea,
- * si es jefe de producción muestra el historial completo.
- *
- * @param vPlate número de matrícula
- * @param vWorkerFk id del trabajador
- *
-*/
- DECLARE vWorkerName VARCHAR(255) DEFAULT account.user_getNameFromId(vWorkerFk);
-
- SELECT mw.inTimed,account.user_getNameFromId(mw.workerFk) as workerName, mw.outTimed
- FROM machineWorker mw
- JOIN machine m ON m.plate = vPlate
- WHERE mw.machineFk = m.id
- AND mw.workerFk = IF(account.user_hasRole(vWorkerName, 'coolerAssist'), mw.workerFk, vWorkerFk)
- ORDER BY mw.inTimed DESC;
-END$$
-DELIMITER ;
diff --git a/db/routines/vn/procedures/machineWorker_update.sql b/db/routines/vn/procedures/machineWorker_update.sql
deleted file mode 100644
index f1a6e40b5..000000000
--- a/db/routines/vn/procedures/machineWorker_update.sql
+++ /dev/null
@@ -1,38 +0,0 @@
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`machineWorker_update`(vPlate VARCHAR(10), vWorkerFk INT)
-BEGIN
-
-/**
- * Actualiza el registro correspondiente si el vWorkerFk se ha registrado en las últimas horas (campo maxHours de machineWorkerConfig) con vPlate,
- *
- * @param vPlate número de matrícula
- * @param vWorkerFk id del trabajador
- *
-*/
-
- DECLARE vMachineFk INT(10);
- DECLARE vMaxHours INT(10);
-
- SELECT m.id INTO vMachineFk
- FROM machine m
- WHERE m.plate = vPlate;
-
- SELECT maxHours INTO vMaxHours
- FROM machineWorkerConfig;
-
- IF (SELECT COUNT(*)
- FROM machineWorker m
- WHERE m.workerFk = vWorkerFk
- AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW()) AND ISNULL(m.outTimed)) THEN
-
- UPDATE machineWorker m
- SET m.outTimed = CURRENT_TIMESTAMP()
- WHERE m.workerFk = vWorkerFk
- AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW())
- AND ISNULL(m.outTimed)
- AND m.machineFk = vMachineFk;
-
- END IF;
-
-END$$
-DELIMITER ;
diff --git a/db/routines/vn/procedures/machine_getWorkerPlate.sql b/db/routines/vn/procedures/machine_getWorkerPlate.sql
deleted file mode 100644
index cbb71c4cf..000000000
--- a/db/routines/vn/procedures/machine_getWorkerPlate.sql
+++ /dev/null
@@ -1,16 +0,0 @@
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`machine_getWorkerPlate`(vWorkerFk INT)
-BEGIN
-/**
- * Selecciona la matrícula del vehículo del workerfk
- *
- * @param vWorkerFk el id del trabajador
- */
- SELECT m.plate
- FROM machine m
- JOIN machineWorker mw ON mw.machineFk = m.id
- WHERE mw.inTimed >= TIMESTAMPADD(HOUR , -12,util.VN_NOW())
- AND ISNULL(mw.outTimed)
- AND mw.workerFk = vWorkerFk;
-END$$
-DELIMITER ;
diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql
index c051706b7..ee18bbe96 100644
--- a/db/routines/vn/procedures/multipleInventory.sql
+++ b/db/routines/vn/procedures/multipleInventory.sql
@@ -1,173 +1,173 @@
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`multipleInventory`(
- vDate DATE,
- vWarehouseFk TINYINT,
- vMaxDays TINYINT
-)
-proc: BEGIN
- DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY;
- DECLARE vDateFrom DATE DEFAULT vDate;
- DECLARE vDateTo DATETIME;
- DECLARE vDateToTomorrow DATETIME;
- DECLARE vDefaultDayRange INT;
- DECLARE vCalcFk INT;
-
- IF vDate < util.VN_CURDATE() THEN
- LEAVE proc;
- END IF;
-
- IF vDate = util.VN_CURDATE() THEN
- SELECT inventoried INTO vDateFrom
- FROM config;
- END IF;
-
- SELECT defaultDayRange INTO vDefaultDayRange
- FROM comparativeConfig;
-
- SET vDateTo = vDate + INTERVAL IFNULL(vMaxDays, vDefaultDayRange) DAY;
- SET vDateToTomorrow = vDateTo + INTERVAL 1 DAY;
-
- ALTER TABLE tmp.itemInventory
- 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';
-
- -- Calculo del inventario
- CREATE OR REPLACE TEMPORARY TABLE tItemInventoryCalc
- (PRIMARY KEY (itemFk))
- ENGINE = MEMORY
- SELECT itemFk,
- SUM(quantity) quantity
- FROM (
- SELECT s.itemFk, - s.quantity quantity
- FROM sale s
- JOIN ticket t ON t.id = s.ticketFk
- JOIN warehouse w ON w.id = t.warehouseFk
- WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate)
- AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk
- AND w.isComparative
- UNION ALL
- SELECT b.itemFk, b.quantity
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- JOIN warehouse w ON w.id = t.warehouseInFk
- WHERE t.landed BETWEEN vDateFrom AND util.dayEnd(vDate)
- AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk
- AND w.isComparative
- AND NOT e.isExcludedFromAvailable
- AND NOT e.isRaid
- UNION ALL
- SELECT b.itemFk, - b.quantity
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- JOIN warehouse w ON w.id = t.warehouseOutFk
- WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate)
- AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk
- AND w.isComparative
- AND NOT e.isExcludedFromAvailable
- AND NOT e.isRaid
- ) sub
- GROUP BY itemFk;
-
- -- Cálculo del visible
- CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk);
-
- CREATE OR REPLACE TEMPORARY TABLE tItemVisibleCalc
- (PRIMARY KEY (item_id))
- ENGINE = MEMORY
- SELECT item_id, visible
- FROM cache.visible
- WHERE calc_id = vCalcFk;
-
- UPDATE tmp.itemInventory it
- LEFT JOIN tItemInventoryCalc iic ON iic.itemFk = it.id
- LEFT JOIN tItemVisibleCalc ivc ON ivc.item_id = it.id
- SET it.inventory = iic.quantity,
- it.visible = ivc.visible,
- it.avalaible = iic.quantity,
- it.sd = iic.quantity;
-
- -- Calculo del disponible
- CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc
- (INDEX (itemFk, warehouseFk))
- ENGINE = MEMORY
- SELECT sub.itemFk,
- vWarehouseFk warehouseFk,
- sub.dated,
- SUM(sub.quantity) quantity
- FROM (
- SELECT s.itemFk,
- DATE(t.shipped) dated,
- - s.quantity quantity
- FROM sale s
- JOIN ticket t ON t.id = s.ticketFk
- JOIN warehouse w ON w.id = t.warehouseFk
- WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo
- AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk
- AND w.isComparative
- UNION ALL
- SELECT b.itemFk, t.landed, b.quantity
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- JOIN warehouse w ON w.id = t.warehouseInFk
- WHERE t.landed BETWEEN vDateTomorrow AND vDateTo
- AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk
- AND w.isComparative
- AND NOT e.isExcludedFromAvailable
- AND NOT e.isRaid
- UNION ALL
- SELECT b.itemFk, t.shipped, - b.quantity
- FROM buy b
- JOIN entry e ON e.id = b.entryFk
- JOIN travel t ON t.id = e.travelFk
- JOIN warehouse w ON w.id = t.warehouseOutFk
- WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo
- AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk
- AND w.isComparative
- AND NOT e.isExcludedFromAvailable
- AND NOT e.isRaid
- ) sub
- GROUP BY sub.itemFk, sub.dated;
-
- CALL item_getAtp(vDate);
- CALL travel_upcomingArrivals(vWarehouseFk, vDate);
-
- CREATE OR REPLACE TEMPORARY TABLE tItemAvailableCalc
- (PRIMARY KEY (itemFk))
- ENGINE = MEMORY
- SELECT it.itemFk,
- SUM(it.quantity) quantity,
- im.quantity minQuantity
- FROM tmp.itemCalc it
- JOIN tmp.itemAtp im ON im.itemFk = it.itemFk
- JOIN item i ON i.id = it.itemFk
- LEFT JOIN origin o ON o.id = i.originFk
- LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk
- WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL,
- t.landing,
- vDateToTomorrow)
- GROUP BY it.itemFk;
-
- UPDATE tmp.itemInventory it
- JOIN tItemAvailableCalc iac ON iac.itemFk = it.id
- SET it.avalaible = IF(iac.minQuantity > 0,
- it.avalaible,
- it.avalaible + iac.minQuantity),
- it.sd = it.inventory + iac.quantity;
-
- DROP TEMPORARY TABLE
- tmp.itemTravel,
- tmp.itemCalc,
- tmp.itemAtp,
- tItemInventoryCalc,
- tItemVisibleCalc,
- tItemAvailableCalc;
-END$$
-DELIMITER ;
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`multipleInventory`(
+ vDate DATE,
+ vWarehouseFk TINYINT,
+ vMaxDays TINYINT
+)
+proc: BEGIN
+ DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY;
+ DECLARE vDateFrom DATE DEFAULT vDate;
+ DECLARE vDateTo DATETIME;
+ DECLARE vDateToTomorrow DATETIME;
+ DECLARE vDefaultDayRange INT;
+ DECLARE vCalcFk INT;
+
+ IF vDate < util.VN_CURDATE() THEN
+ LEAVE proc;
+ END IF;
+
+ IF vDate = util.VN_CURDATE() THEN
+ SELECT inventoried INTO vDateFrom
+ FROM config;
+ END IF;
+
+ SELECT defaultDayRange INTO vDefaultDayRange
+ FROM comparativeConfig;
+
+ SET vDateTo = vDate + INTERVAL IFNULL(vMaxDays, vDefaultDayRange) DAY;
+ SET vDateToTomorrow = vDateTo + INTERVAL 1 DAY;
+
+ ALTER TABLE tmp.itemInventory
+ 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';
+
+ -- Calculo del inventario
+ CREATE OR REPLACE TEMPORARY TABLE tItemInventoryCalc
+ (PRIMARY KEY (itemFk))
+ ENGINE = MEMORY
+ SELECT itemFk,
+ SUM(quantity) quantity
+ FROM (
+ SELECT s.itemFk, - s.quantity quantity
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate)
+ AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk
+ AND w.isComparative
+ UNION ALL
+ SELECT b.itemFk, b.quantity
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN warehouse w ON w.id = t.warehouseInFk
+ WHERE t.landed BETWEEN vDateFrom AND util.dayEnd(vDate)
+ AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk
+ AND w.isComparative
+ AND NOT e.isExcludedFromAvailable
+ AND NOT t.isRaid
+ UNION ALL
+ SELECT b.itemFk, - b.quantity
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN warehouse w ON w.id = t.warehouseOutFk
+ WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate)
+ AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk
+ AND w.isComparative
+ AND NOT e.isExcludedFromAvailable
+ AND NOT t.isRaid
+ ) sub
+ GROUP BY itemFk;
+
+ -- Cálculo del visible
+ CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk);
+
+ CREATE OR REPLACE TEMPORARY TABLE tItemVisibleCalc
+ (PRIMARY KEY (item_id))
+ ENGINE = MEMORY
+ SELECT item_id, visible
+ FROM cache.visible
+ WHERE calc_id = vCalcFk;
+
+ UPDATE tmp.itemInventory it
+ LEFT JOIN tItemInventoryCalc iic ON iic.itemFk = it.id
+ LEFT JOIN tItemVisibleCalc ivc ON ivc.item_id = it.id
+ SET it.inventory = iic.quantity,
+ it.visible = ivc.visible,
+ it.avalaible = iic.quantity,
+ it.sd = iic.quantity;
+
+ -- Calculo del disponible
+ CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc
+ (INDEX (itemFk, warehouseFk))
+ ENGINE = MEMORY
+ SELECT sub.itemFk,
+ vWarehouseFk warehouseFk,
+ sub.dated,
+ SUM(sub.quantity) quantity
+ FROM (
+ SELECT s.itemFk,
+ DATE(t.shipped) dated,
+ - s.quantity quantity
+ FROM sale s
+ JOIN ticket t ON t.id = s.ticketFk
+ JOIN warehouse w ON w.id = t.warehouseFk
+ WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo
+ AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk
+ AND w.isComparative
+ UNION ALL
+ SELECT b.itemFk, t.landed, b.quantity
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN warehouse w ON w.id = t.warehouseInFk
+ WHERE t.landed BETWEEN vDateTomorrow AND vDateTo
+ AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk
+ AND w.isComparative
+ AND NOT e.isExcludedFromAvailable
+ AND NOT t.isRaid
+ UNION ALL
+ SELECT b.itemFk, t.shipped, - b.quantity
+ FROM buy b
+ JOIN entry e ON e.id = b.entryFk
+ JOIN travel t ON t.id = e.travelFk
+ JOIN warehouse w ON w.id = t.warehouseOutFk
+ WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo
+ AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk
+ AND w.isComparative
+ AND NOT e.isExcludedFromAvailable
+ AND NOT t.isRaid
+ ) sub
+ GROUP BY sub.itemFk, sub.dated;
+
+ CALL item_getAtp(vDate);
+ CALL travel_upcomingArrivals(vWarehouseFk, vDate);
+
+ CREATE OR REPLACE TEMPORARY TABLE tItemAvailableCalc
+ (PRIMARY KEY (itemFk))
+ ENGINE = MEMORY
+ SELECT it.itemFk,
+ SUM(it.quantity) quantity,
+ im.quantity minQuantity
+ FROM tmp.itemCalc it
+ JOIN tmp.itemAtp im ON im.itemFk = it.itemFk
+ JOIN item i ON i.id = it.itemFk
+ LEFT JOIN origin o ON o.id = i.originFk
+ LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk
+ WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL,
+ t.landing,
+ vDateToTomorrow)
+ GROUP BY it.itemFk;
+
+ UPDATE tmp.itemInventory it
+ JOIN tItemAvailableCalc iac ON iac.itemFk = it.id
+ SET it.avalaible = IF(iac.minQuantity > 0,
+ it.avalaible,
+ it.avalaible + iac.minQuantity),
+ it.sd = it.inventory + iac.quantity;
+
+ DROP TEMPORARY TABLE
+ tmp.itemTravel,
+ tmp.itemCalc,
+ tmp.itemAtp,
+ tItemInventoryCalc,
+ tItemVisibleCalc,
+ tItemAvailableCalc;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/productionControl.sql b/db/routines/vn/procedures/productionControl.sql
index 1d206e20d..813c65ab2 100644
--- a/db/routines/vn/procedures/productionControl.sql
+++ b/db/routines/vn/procedures/productionControl.sql
@@ -217,7 +217,7 @@ proc: BEGIN
st.code = 'previousPrepared' isPreviousPrepared,
sc.itemPackingTypeFk
FROM itemShelving ish
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN sector sc ON sc.id = p.sectorFk
JOIN sectorType st ON st.id = sc.typeFk
diff --git a/db/routines/vn/procedures/queueMember_updateQueue.sql b/db/routines/vn/procedures/queueMember_updateQueue.sql
new file mode 100644
index 000000000..5af44da4f
--- /dev/null
+++ b/db/routines/vn/procedures/queueMember_updateQueue.sql
@@ -0,0 +1,29 @@
+DELIMITER $$
+
+CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`queueMember_updateQueue`(
+ vBusinessFk INT
+)
+BEGIN
+ /**
+ * Elimina la entrada de la cola anterior y luego inserta la nueva para un trabajador.
+ *
+ * @param vBusinessFk ID del negocio
+ */
+ DECLARE vNewQueue VARCHAR(10);
+ DECLARE vExtension VARCHAR(10);
+ DECLARE exit handler FOR SQLEXCEPTION
+
+ SELECT d.pbxQueue, s.extension
+ INTO vNewQueue, vExtension
+ FROM business b
+ JOIN department d ON d.id = b.departmentFk
+ JOIN pbx.sip s ON s.user_id = b.workerFk
+ WHERE b.id = vBusinessFk;
+
+ DELETE FROM pbx.queueMember
+ WHERE extension = vExtension COLLATE utf8_general_ci;
+
+ INSERT IGNORE INTO pbx.queueMember (queue, extension)
+ VALUES (vNewQueue, vExtension);
+END$$
+DELIMITER ;
\ No newline at end of file
diff --git a/db/routines/vn/procedures/raidUpdate.sql b/db/routines/vn/procedures/raidUpdate.sql
deleted file mode 100644
index 71352868e..000000000
--- a/db/routines/vn/procedures/raidUpdate.sql
+++ /dev/null
@@ -1,31 +0,0 @@
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`raidUpdate`()
-BEGIN
-/**
- * Actualiza el travel de las entradas de redadas
- */
- UPDATE entry e
- JOIN entryVirtual ev ON ev.entryFk = e.id
- JOIN travel t ON t.id = e.travelFk
- JOIN (
- SELECT *
- FROM (
- SELECT t.id, t.landed, tt.warehouseInFk, tt.warehouseOutFk
- FROM travel t
- JOIN (
- SELECT t.warehouseInFk, t.warehouseOutFk
- FROM entryVirtual ev
- JOIN entry e ON e.id = ev.entryFk
- JOIN travel t ON t.id = e.travelFk
- GROUP BY t.warehouseInFk, t.warehouseOutFk
- ) tt ON t.warehouseInFk = tt.warehouseInFk AND t.warehouseOutFk = tt.warehouseOutFk
- WHERE shipped > util.VN_CURDATE() AND NOT isDelivered
- ORDER BY t.landed
- LIMIT 10000000000000000000
- ) t
- GROUP BY t.warehouseInFk, t.warehouseOutFk
- ) tt ON t.warehouseInFk = tt.warehouseInFk AND t.warehouseOutFk = tt.warehouseOutFk
- SET e.travelFk = t.id;
-
-END$$
-DELIMITER ;
diff --git a/db/routines/vn/procedures/routeMonitor_calculate.sql b/db/routines/vn/procedures/routeMonitor_calculate.sql
index c9a7a9ccf..31667f211 100644
--- a/db/routines/vn/procedures/routeMonitor_calculate.sql
+++ b/db/routines/vn/procedures/routeMonitor_calculate.sql
@@ -27,7 +27,7 @@ BEGIN
rm.ticketFree = 0,
rm.ticketProduction = 0,
rm.ticketPacked = 0,
- rm.dated = r.created;
+ rm.dated = r.dated;
UPDATE routesMonitor rm
JOIN (
diff --git a/db/routines/vn/procedures/route_calcCommission.sql b/db/routines/vn/procedures/route_calcCommission.sql
index 7c911a5e2..dc44adb9b 100644
--- a/db/routines/vn/procedures/route_calcCommission.sql
+++ b/db/routines/vn/procedures/route_calcCommission.sql
@@ -11,8 +11,10 @@ BEGIN
*/
DECLARE vIsUpdatable, vIsFreelance BOOL DEFAULT 0;
DECLARE vAgencyModePricePercentage DOUBLE;
+ DECLARE vIsKmTruckRate BOOL;
+ DECLARE vCountryFk INT;
- SELECT r.created >= rc.cutoffDated INTO vIsUpdatable
+ SELECT r.dated >= rc.cutoffDated INTO vIsUpdatable
FROM route r
JOIN routeConfig rc
WHERE r.id = vSelf;
@@ -21,10 +23,17 @@ BEGIN
DELETE FROM routeCommission
WHERE routeFk = vSelf;
- SELECT w.isFreelance INTO vIsFreelance
+ SELECT w.isFreelance, v.isKmTruckRate, p.countryFk INTO vIsFreelance, vIsKmTruckRate, vCountryFk
FROM route r
JOIN worker w ON w.id = r.workerFk
- WHERE r.id = vSelf;
+ JOIN vehicle v ON v.id = r.vehicleFk
+ LEFT JOIN ticket t ON t.routeFk = r.id
+ LEFT JOIN address a ON a.id = t.addressFk
+ LEFT JOIN province p ON p.id = a.provinceFk
+ WHERE r.id = vSelf
+ GROUP BY p.countryFk
+ ORDER BY COUNT(*) DESC
+ LIMIT 1;
SELECT ampp.percentage INTO vAgencyModePricePercentage
FROM route r
@@ -39,7 +48,9 @@ BEGIN
workCenterFk,
freelanceYearlyM3,
cat4m3,
- cat5m3
+ cat5m3,
+ isKmTruckRate,
+ countryFk
)
SELECT vSelf,
r.commissionWorkCenterFk,
@@ -51,11 +62,14 @@ BEGIN
IFNULL(r.m3, 0),
0
),
- rc.distributionCat4M3 * IFNULL(r.m3, 0),
- rc.distributionCat5M3 * IFNULL(r.m3, 0)
+ IFNULL(wc.distributionCat4M3, rc.distributionCat4M3) * IFNULL(r.m3, 0),
+ IFNULL(wc.distributionCat5M3, rc.distributionCat5M3) * IFNULL(r.m3, 0),
+ vIsKmTruckRate,
+ vCountryFk
FROM route r
JOIN vehicle v ON v.id = r.vehicleFk
JOIN routeConfig rc
+ LEFT JOIN workCenterCommission wc ON wc.workCenterFk = r.commissionWorkCenterFk
WHERE r.id = vSelf
AND r.workerFk
AND r.commissionWorkCenterFk;
@@ -68,21 +82,28 @@ BEGIN
yearlyKm,
yearlyM3,
cat4m3,
- cat5m3
+ cat5m3,
+ isKmTruckRate,
+ countryFk
)
SELECT vSelf,
r.commissionWorkCenterFk,
(r.kmEnd - r.kmStart) *
IF(v.isKmTruckRate, rc.kmHeavy, rc.kmLight),
IFNULL(r.m3, 0) *
- IF(v.isKmTruckRate, rc.deliveryM3Cat5, rc.deliveryM3Cat4),
+ IF(v.isKmTruckRate,
+ IFNULL(wc.deliveryM3Cat5, rc.deliveryM3Cat5),
+ IFNULL(wc.deliveryM3Cat4, rc.deliveryM3Cat4)),
(r.kmEnd - r.kmStart) * rc.kmYearly,
IFNULL(r.m3, 0) * rc.m3Yearly,
- rc.distributionCat4M3 * IFNULL(r.m3, 0),
- rc.distributionCat5M3 * IFNULL(r.m3, 0)
+ IFNULL(wc.distributionCat4M3, rc.distributionCat4M3) * IFNULL(r.m3, 0),
+ IFNULL(wc.distributionCat5M3, rc.distributionCat5M3) * IFNULL(r.m3, 0),
+ vIsKmTruckRate,
+ vCountryFk
FROM route r
JOIN vehicle v ON v.id = r.vehicleFk
JOIN routeConfig rc
+ LEFT JOIN workCenterCommission wc ON wc.workCenterFk = r.commissionWorkCenterFk
WHERE r.id = vSelf
AND r.kmStart
AND r.kmEnd
diff --git a/db/routines/vn/procedures/saleTracking_sectorCollectionAddPrevOK.sql b/db/routines/vn/procedures/saleTracking_sectorCollectionAddPrevOK.sql
new file mode 100644
index 000000000..003168ec8
--- /dev/null
+++ b/db/routines/vn/procedures/saleTracking_sectorCollectionAddPrevOK.sql
@@ -0,0 +1,20 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`saleTracking_sectorCollectionAddPrevOK`(
+ vSectorCollectionFk INT
+)
+BEGIN
+/**
+ * Inserta los registros de sectorCollection con el estado PREVIA OK si la reserva está picked
+ *
+ * @param vSectorCollectionFk Identificador de vn.sectorCollection
+ */
+ REPLACE saleTracking(saleFk, isChecked, workerFk, stateFk)
+ SELECT sgd.saleFk, TRUE, sc.userFk, s.id
+ FROM sectorCollection sc
+ JOIN sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id
+ JOIN saleGroupDetail sgd ON sgd.saleGroupFk = scsg.saleGroupFk
+ JOIN state s ON s.code = 'OK PREVIOUS'
+ JOIN itemShelvingSale iss ON iss.saleFk = sgd.saleFk
+ WHERE sc.id = vSectorCollectionFk AND iss.isPicked;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/sale_boxPickingPrint.sql b/db/routines/vn/procedures/sale_boxPickingPrint.sql
index 6bb954a78..f156ff8f8 100644
--- a/db/routines/vn/procedures/sale_boxPickingPrint.sql
+++ b/db/routines/vn/procedures/sale_boxPickingPrint.sql
@@ -27,7 +27,7 @@ BEGIN
DECLARE vQuantity INT;
DECLARE vRemainder INT DEFAULT 0;
DECLARE vRemainderSaleFk INT;
- DECLARE vShelving VARCHAR(10);
+ DECLARE vShelvingFk VARCHAR(10);
DECLARE vTicketFk INT;
SELECT s.quantity,
@@ -74,7 +74,7 @@ w1: WHILE vQuantity >= vPacking DO
p.pickingOrder,
ish.created
FROM itemShelving ish
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
LEFT JOIN itemShelvingSale iss
ON iss.itemShelvingFk = ish.id
@@ -262,9 +262,9 @@ w1: WHILE vQuantity >= vPacking DO
CALL dipole.expedition_Add(vExpeditionFk,vPrinterFk, TRUE);
SELECT shelvingFk, p.code
- INTO vShelving, vParkingCode
+ INTO vShelvingFk, vParkingCode
FROM itemShelving ish
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
WHERE ish.id = vItemShelvingFk;
@@ -273,7 +273,7 @@ w1: WHILE vQuantity >= vPacking DO
itemFk = vItemFk,
quantity = vPacking,
longName = vConcept,
- shelvingFk = vShelving,
+ shelvingFk = vShelvingFk,
parkingCode = vParkingCode,
phone = RIGHT(phone,vMaxPhoneLength),
street = RIGHT(street, vMAxStreetLength)
diff --git a/db/routines/vn/procedures/sale_getBoxPickingList.sql b/db/routines/vn/procedures/sale_getBoxPickingList.sql
index f343ab375..4f6a08083 100644
--- a/db/routines/vn/procedures/sale_getBoxPickingList.sql
+++ b/db/routines/vn/procedures/sale_getBoxPickingList.sql
@@ -41,7 +41,7 @@ BEGIN
AND iss.created >= vDated
GROUP BY iss.itemShelvingFk, s.itemFk) tISS
ON tISS.itemFk = ish.itemFk AND tISS.itemShelvingFk = ish.id
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN tmp.productionBuffer pb ON pb.ticketFk = s.ticketFk
JOIN agencyMode am ON am.id = pb.agencyModeFk
diff --git a/db/routines/vn/procedures/sale_getProblems.sql b/db/routines/vn/procedures/sale_getProblems.sql
index 2bba8fbc3..e016f3ab4 100644
--- a/db/routines/vn/procedures/sale_getProblems.sql
+++ b/db/routines/vn/procedures/sale_getProblems.sql
@@ -40,7 +40,7 @@ BEGIN
isTooLittle BOOL DEFAULT FALSE,
isVip BOOL DEFAULT FALSE,
PRIMARY KEY (ticketFk, saleFk)
- ) ENGINE = MEMORY;
+ ); -- No memory
INSERT INTO tmp.sale_problems(ticketFk,
saleFk,
@@ -87,7 +87,7 @@ BEGIN
SUM(ish.visible) visible,
s.warehouseFk warehouseFk
FROM itemShelving ish
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN sector s ON s.id = p.sectorFk
GROUP BY ish.itemFk, s.warehouseFk;
@@ -127,7 +127,7 @@ BEGIN
LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
AND issw.warehouseFk = t.warehouseFk
WHERE IFNULL(v.visible, 0) < s.quantity
- AND IFNULL(av.available, 0) < s.quantity
+ AND IFNULL(av.available, 0) < 0
AND IFNULL(issw.visible, 0) < s.quantity
AND NOT s.isPicked
AND NOT s.reserved
@@ -190,7 +190,7 @@ BEGIN
LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
AND issw.warehouseFk = t.warehouseFk
WHERE IFNULL(v.visible, 0) < s.quantity
- AND IFNULL(av.available, 0) >= s.quantity
+ AND IFNULL(av.available, 0) >= 0
AND IFNULL(issw.visible, 0) < s.quantity
AND s.quantity > 0
AND NOT s.isPicked
diff --git a/db/routines/vn/procedures/shelvingChange.sql b/db/routines/vn/procedures/shelvingChange.sql
index 2e7e92082..901b1cf95 100644
--- a/db/routines/vn/procedures/shelvingChange.sql
+++ b/db/routines/vn/procedures/shelvingChange.sql
@@ -1,11 +1,13 @@
DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`shelvingChange`(IN `vShelvingO` VARCHAR(8), IN `vShelvingD` VARCHAR(8))
+CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`shelvingChange`(
+ `vShelvingO` VARCHAR(10),
+ `vShelvingD` VARCHAR(10)
+)
BEGIN
-
- UPDATE vn.itemShelving
- SET shelvingFk = vShelvingD COLLATE utf8_unicode_ci
- WHERE shelvingFk = vShelvingO COLLATE utf8_unicode_ci;
-
-
+ UPDATE itemShelving ish
+ JOIN shelving sh1 ON sh1.code = vShelvingD COLLATE utf8_unicode_ci
+ JOIN shelving sh2 ON sh2.code = vShelvingO COLLATE utf8_unicode_ci
+ SET ish.shelvingFk = sh1.id
+ WHERE ish.shelvingFk = sh2.id;
END$$
DELIMITER ;
diff --git a/db/routines/vn/procedures/shelvingParking_get.sql b/db/routines/vn/procedures/shelvingParking_get.sql
index a9ed9f74a..c05e8afc3 100644
--- a/db/routines/vn/procedures/shelvingParking_get.sql
+++ b/db/routines/vn/procedures/shelvingParking_get.sql
@@ -1,8 +1,10 @@
DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`shelvingParking_get`(vShelvingFk VARCHAR(10), vWarehouseFk INT, vDayRange INT)
-BEGIN
-
-
+CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`shelvingParking_get`(
+ vShelvingCode VARCHAR(10),
+ vWarehouseFk INT,
+ vDayRange INT
+)
+BEGIN
SELECT s.itemFk,
s.concept,
CAST(SUM(s.quantity) AS DECIMAL(10,0)) as sinServir,
@@ -10,14 +12,15 @@ SELECT s.itemFk,
FROM vn.sale s
LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id
JOIN vn.ticket t ON t.id = s.ticketFk
- LEFT JOIN vn.itemShelvingStock ist ON ist.itemFk = s.itemFk AND ist.warehouseFk = vWarehouseFk
- JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk AND ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci
+ LEFT JOIN vn.itemShelvingStock ist ON ist.itemFk = s.itemFk
+ AND ist.warehouseFk = vWarehouseFk
+ JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
+ AND sh.code = vShelvingCode COLLATE utf8_general_ci
WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(TIMESTAMPADD(DAY, GREATEST(0,vDayRange), util.VN_CURDATE()))
AND iss.saleFk IS NULL
AND t.warehouseFk = vWarehouseFk
GROUP BY s.itemFk
HAVING sinServir > aparcado;
-
-
END$$
DELIMITER ;
diff --git a/db/routines/vn/procedures/shelving_clean.sql b/db/routines/vn/procedures/shelving_clean.sql
index 0b29968bc..155338827 100644
--- a/db/routines/vn/procedures/shelving_clean.sql
+++ b/db/routines/vn/procedures/shelving_clean.sql
@@ -12,12 +12,12 @@ BEGIN
DELETE ish.*
FROM itemShelving ish
- JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.shelving sh ON sh.id = ish.shelvingFk
WHERE sh.parkingFk IS NULL
AND ish.created < TIMESTAMPADD(WEEK,-1,util.VN_CURDATE());
UPDATE shelving sh
- LEFT JOIN itemShelving its ON its.shelvingFk = sh.`code`
+ LEFT JOIN itemShelving its ON its.shelvingFk = sh.id
SET isPrinted = 0,
parkingFk = NULL
WHERE its.id IS NULL
@@ -27,11 +27,11 @@ UPDATE shelving sh
OR
sh.parked < util.VN_CURDATE() - INTERVAL 2 WEEK
)
-
AND IF(code REGEXP '^[A-Za-z]{2}[0-9]', LEFT (code, 2) NOT IN (
- SELECT DISTINCT LEFT(its.shelvingFk, 2)
+ SELECT DISTINCT LEFT(sh.code, 2)
FROM itemShelving its
- WHERE its.shelvingFk REGEXP '^[A-Za-z]{2}[0-9]'
+ JOIN shelving sh ON sh.id = its.shelvingFk
+ WHERE sh.code REGEXP '^[A-Za-z]{2}[0-9]'
), TRUE);
END$$
diff --git a/db/routines/vn/procedures/shelving_getSpam.sql b/db/routines/vn/procedures/shelving_getSpam.sql
index cef407285..a80021cdf 100644
--- a/db/routines/vn/procedures/shelving_getSpam.sql
+++ b/db/routines/vn/procedures/shelving_getSpam.sql
@@ -25,7 +25,7 @@ BEGIN
LEFT JOIN (
SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS reserva
FROM vn.itemShelving ish
- JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.shelving sh ON sh.id = ish.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
JOIN vn.sector s ON s.id = p.sectorFk
WHERE s.code = 'FUENTES_PICASSE'
@@ -68,7 +68,7 @@ BEGIN
sh.isSpam
FROM vn.itemShelving ish
JOIN vn.item i ON i.id = ish.itemFk
- JOIN vn.shelving sh ON sh.code = ish.shelvingFk
+ JOIN vn.shelving sh ON sh.id = ish.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
JOIN vn.sector s ON s.id = p.sectorFk
JOIN vn.warehouse w ON w.id = s.warehouseFk
diff --git a/db/routines/vn/procedures/stockBought_calculate.sql b/db/routines/vn/procedures/stockBought_calculate.sql
index 8b2a32e5d..c248d0deb 100644
--- a/db/routines/vn/procedures/stockBought_calculate.sql
+++ b/db/routines/vn/procedures/stockBought_calculate.sql
@@ -7,13 +7,13 @@ proc: BEGIN
* Calculate the stock of the auction warehouse from the inventory date to vDated
* without taking into account the outputs of the same day vDated
*
- * @param vDated Date to calculate the stock.
+ * @param vDated Date to calculate the stock
*/
IF vDated < util.VN_CURDATE() THEN
LEAVE proc;
END IF;
- CREATE OR REPLACE TEMPORARY TABLE tStockBought
+ CREATE OR REPLACE TEMPORARY TABLE tCurrentData
SELECT workerFk, reserve
FROM stockBought
WHERE dated = vDated
@@ -21,15 +21,28 @@ proc: BEGIN
DELETE FROM stockBought WHERE dated = vDated;
+ CREATE OR REPLACE TEMPORARY TABLE tStockSold
+ SELECT it.workerFk,
+ SUM(ic.cm3 * ito.quantity / vc.palletM3 / 1000000) sold
+ FROM itemTicketOut ito
+ JOIN item i ON i.id = ito.itemFk
+ JOIN itemType it ON it.id = i.typeFk
+ JOIN ticket t ON t.id = ito.ticketFk
+ JOIN warehouse wh ON wh.id = t.warehouseFk
+ JOIN itemCost ic ON ic.itemFk = ito.itemFk
+ AND ic.warehouseFk = t.warehouseFk
+ JOIN volumeConfig vc
+ WHERE ito.shipped BETWEEN vDated AND util.dayEnd(vDated)
+ AND wh.code = 'VNH'
+ GROUP BY it.workerFk;
+
CALL item_calculateStock(vDated);
- INSERT INTO stockBought(workerFk, bought, dated)
+ CREATE OR REPLACE TEMPORARY TABLE tStockBought
SELECT it.workerFk,
- ROUND(SUM(
- (ti.quantity / b.packing) *
- buy_getVolume(b.id)
- ) / vc.palletM3 / 1000000, 1) bought,
- vDated
+ SUM((ti.quantity / b.packing) *
+ buy_getVolume(b.id)
+ ) / vc.palletM3 / 1000000 bought
FROM itemType it
JOIN item i ON i.typeFk = it.id
LEFT JOIN tmp.item ti ON ti.itemFk = i.id
@@ -43,20 +56,33 @@ proc: BEGIN
GROUP BY it.workerFk
HAVING bought;
+
+ INSERT INTO stockBought(workerFk, bought, dated)
+ SELECT tb.workerFk,
+ ROUND(GREATEST(tb.bought - IFNULL(ts.sold, 0), 0), 2),
+ vDated
+ FROM tStockBought tb
+ LEFT JOIN tStockSold ts ON ts.workerFk = tb.workerFk;
+
UPDATE stockBought s
- JOIN tStockBought ts ON ts.workerFk = s.workerFk
+ JOIN tCurrentData ts ON ts.workerFk = s.workerFk
SET s.reserve = ts.reserve
WHERE s.dated = vDated;
INSERT INTO stockBought (workerFk, reserve, dated)
SELECT ts.workerFk, ts.reserve, vDated
- FROM tStockBought ts
+ FROM tCurrentData ts
WHERE ts.workerFk NOT IN (
SELECT workerFk
FROM stockBought
WHERE dated = vDated
);
- DROP TEMPORARY TABLE tStockBought, tmp.item, tmp.buyUltimate;
+ UPDATE stockBought s
+ JOIN tStockSold ts ON ts.workerFk = s.workerFk
+ SET s.bought = IF(s.bought < ABS(ts.sold), 0, ROUND(s.bought - ABS(ts.sold), 1))
+ WHERE s.dated = vDated;
+
+ DROP TEMPORARY TABLE tCurrentData, tmp.item, tmp.buyUltimate, tStockSold;
END$$
DELIMITER ;
diff --git a/db/routines/vn/procedures/stockBuyedByWorker.sql b/db/routines/vn/procedures/stockBuyedByWorker.sql
index 13bda0133..536638770 100644
--- a/db/routines/vn/procedures/stockBuyedByWorker.sql
+++ b/db/routines/vn/procedures/stockBuyedByWorker.sql
@@ -71,4 +71,4 @@ BEGIN
tmp.item,
tStockBuyed;
END$$
-DELIMITER ;
+DELIMITER ;
\ No newline at end of file
diff --git a/db/routines/vn/procedures/stockBuyed_add.sql b/db/routines/vn/procedures/stockBuyed_add.sql
index aab85e7fa..0491c2424 100644
--- a/db/routines/vn/procedures/stockBuyed_add.sql
+++ b/db/routines/vn/procedures/stockBuyed_add.sql
@@ -67,4 +67,4 @@ BEGIN
tmp.item,
tStockBuyed;
END$$
-DELIMITER ;
+DELIMITER ;
\ No newline at end of file
diff --git a/db/routines/vn/procedures/ticketDown_PrintableSelection.sql b/db/routines/vn/procedures/ticketDown_PrintableSelection.sql
index 082a890a6..8f448d647 100644
--- a/db/routines/vn/procedures/ticketDown_PrintableSelection.sql
+++ b/db/routines/vn/procedures/ticketDown_PrintableSelection.sql
@@ -9,7 +9,7 @@ BEGIN
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.shelving sh ON sh.id = ish.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
WHERE p.sectorFk = vSectorFk
) sub ON sub.id = td.ticketFk
diff --git a/db/routines/vn/procedures/ticketRefund_upsert.sql b/db/routines/vn/procedures/ticketRefund_upsert.sql
new file mode 100644
index 000000000..fb22e6e8c
--- /dev/null
+++ b/db/routines/vn/procedures/ticketRefund_upsert.sql
@@ -0,0 +1,25 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticketRefund_upsert`(
+ vRefundTicketFk INT,
+ vOriginalTicketFk INT
+)
+ READS SQL DATA
+BEGIN
+/**
+ * Common code for ticketRefund triggers
+ *
+ * @param vRefundTicketFk
+ * @param vOriginalTicketFk
+ */
+ DECLARE vIsDeleted BOOL;
+
+ SELECT COUNT(*) INTO vIsDeleted
+ FROM ticket
+ WHERE id IN (vRefundTicketFk, vOriginalTicketFk)
+ AND isDeleted;
+
+ IF vIsDeleted THEN
+ CALL util.throw('The refund ticket cannot be deleted tickets');
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/ticket_DelayTruckSplit.sql b/db/routines/vn/procedures/ticket_DelayTruckSplit.sql
index 1dc45d065..3d22207f3 100644
--- a/db/routines/vn/procedures/ticket_DelayTruckSplit.sql
+++ b/db/routines/vn/procedures/ticket_DelayTruckSplit.sql
@@ -27,7 +27,7 @@ BEGIN
SUM(ish.visible) visible,
s.warehouseFk warehouseFk
FROM itemShelving ish
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN sector s ON s.id = p.sectorFk
GROUP BY ish.itemFk,
diff --git a/db/routines/vn/procedures/ticket_canAdvance.sql b/db/routines/vn/procedures/ticket_canAdvance.sql
index 57c3f4235..cee706e08 100644
--- a/db/routines/vn/procedures/ticket_canAdvance.sql
+++ b/db/routines/vn/procedures/ticket_canAdvance.sql
@@ -51,7 +51,9 @@ BEGIN
origin.companyFk futureCompanyFk,
IFNULL(dest.nickname, origin.nickname) nickname,
dest.landed,
- dest.preparation
+ dest.preparation,
+ origin.departmentFk,
+ origin.saleClonedFk
FROM (
SELECT s.ticketFk,
c.salesPersonFk workerFk,
@@ -71,10 +73,14 @@ BEGIN
t.addressFk,
t.warehouseFk,
t.companyFk,
- t.agencyModeFk
+ t.agencyModeFk,
+ wd.departmentFk,
+ sc.saleClonedFk
FROM ticket t
JOIN client c ON c.id = t.clientFk
+ JOIN workerDepartment wd ON wd.workerFk = c.salesPersonFk
JOIN sale s ON s.ticketFk = t.id
+ LEFT JOIN saleCloned sc ON sc.saleClonedFk = s.id
JOIN saleVolume sv ON sv.saleFk = s.id
JOIN item i ON i.id = s.itemFk
JOIN ticketState ts ON ts.ticketFk = t.id
diff --git a/db/routines/vn/procedures/ticket_close.sql b/db/routines/vn/procedures/ticket_close.sql
index 0da001ffa..e2dcef9a5 100644
--- a/db/routines/vn/procedures/ticket_close.sql
+++ b/db/routines/vn/procedures/ticket_close.sql
@@ -43,7 +43,7 @@ BEGIN
c.isTaxDataChecked,
t.companyFk,
t.shipped,
- IFNULL(a.hasDailyInvoice, co.hasDailyInvoice),
+ c.hasDailyInvoice,
w.isManaged,
c.hasToInvoice
INTO vClientFk,
@@ -55,9 +55,6 @@ BEGIN
vHasToInvoice
FROM ticket t
JOIN `client` c ON c.id = t.clientFk
- JOIN province p ON p.id = c.provinceFk
- LEFT JOIN autonomy a ON a.id = p.autonomyFk
- JOIN country co ON co.id = p.countryFk
JOIN warehouse w ON w.id = t.warehouseFk
WHERE t.id = vCurTicketFk;
@@ -85,7 +82,7 @@ BEGIN
IF(vHasDailyInvoice) AND vHasToInvoice THEN
SELECT invoiceSerial(vClientFk, vCompanyFk, 'quick') INTO vSerial;
- IF vSerial IS NULL THEN
+ IF vSerial IS NULL THEN
CALL util.throw('Cannot booking without a serial');
END IF;
diff --git a/db/routines/vn/procedures/ticket_getSplitList.sql b/db/routines/vn/procedures/ticket_getSplitList.sql
index 988bc2931..66e9bdb57 100644
--- a/db/routines/vn/procedures/ticket_getSplitList.sql
+++ b/db/routines/vn/procedures/ticket_getSplitList.sql
@@ -28,7 +28,7 @@ BEGIN
SUM(ish.visible) visible,
s.warehouseFk warehouseFk
FROM itemShelving ish
- JOIN shelving sh ON sh.code = ish.shelvingFk
+ JOIN shelving sh ON sh.id = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN sector s ON s.id = p.sectorFk
GROUP BY ish.itemFk,
diff --git a/db/routines/vn/procedures/ticket_getTax.sql b/db/routines/vn/procedures/ticket_getTax.sql
index 947c45806..cb9dc09d9 100644
--- a/db/routines/vn/procedures/ticket_getTax.sql
+++ b/db/routines/vn/procedures/ticket_getTax.sql
@@ -1,5 +1,7 @@
DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_getTax`(IN vTaxArea VARCHAR(25))
+CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_getTax`(
+ vTaxArea VARCHAR(25)
+)
BEGIN
/**
* Calcula la base imponible, el IVA y el recargo de equivalencia para
@@ -33,30 +35,39 @@ BEGIN
CREATE OR REPLACE TEMPORARY TABLE tmp.ticketTax
(PRIMARY KEY (ticketFk, code, rate))
ENGINE = MEMORY
- SELECT * FROM (
- SELECT tmpTicket.ticketFk,
- bp.pgcFk,
- SUM(s.quantity * s.price * (100 - s.discount) / 100 ) 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
+ WITH sales AS (
+ SELECT s.ticketFk,
+ s.itemFk,
+ s.quantity * s.price * (100 - s.discount) / 100 total,
+ t.companyFk,
+ t.addressFk,
+ su.countryFk,
+ ata.areaFk,
+ itc.taxClassFk
+ FROM vn.sale s
+ JOIN tmp.ticket tmp ON tmp.ticketFk = s.ticketFk
+ JOIN vn.ticket t ON t.id = s.ticketFk
+ JOIN vn.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
+ JOIN vn.itemTaxCountry itc ON itc.itemFk = s.itemFk
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
- ) t3
+ HAVING total
+ )
+ SELECT s.ticketFk,
+ bp.pgcFk,
+ SUM(s.total) taxableBase,
+ pgc.rate,
+ tc.code,
+ bp.priority
+ FROM sales s
+ JOIN vn.bookingPlanner bp ON bp.countryFk = s.countryFk
+ AND bp.taxAreaFk = s.areaFk
+ AND bp.taxClassFk = s.taxClassFk
+ JOIN vn.pgc ON pgc.code = bp.pgcFk
+ JOIN vn.taxClass tc ON tc.id = bp.taxClassFk
+ GROUP BY s.ticketFk, pgc.code, pgc.rate
+ HAVING taxableBase
ORDER BY priority;
CREATE OR REPLACE TEMPORARY TABLE tmp.ticketServiceTax
diff --git a/db/routines/vn/procedures/ticket_splitItemPackingType.sql b/db/routines/vn/procedures/ticket_splitItemPackingType.sql
index 9a4bc01eb..31e0c24e7 100644
--- a/db/routines/vn/procedures/ticket_splitItemPackingType.sql
+++ b/db/routines/vn/procedures/ticket_splitItemPackingType.sql
@@ -3,87 +3,124 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_splitItemPacki
vSelf INT,
vOriginalItemPackingTypeFk VARCHAR(1)
)
-proc:BEGIN
+BEGIN
/**
- * Clona y reparte las líneas de ventas de un ticket en funcion del tipo de empaquetado.
- * Respeta el id de ticket original para el tipo de empaquetado propuesto.
+ * Separa en diferentes tickets según el tipo de empaquetado
+ * El ticket original conserva las líneas del tipo de empaquetado especificado
+ * Las líneas sin tipo de empaquetado se asignan al ticket del tipo por defecto.
*
- * @param vSelf Id ticket
- * @param vOriginalItemPackingTypeFk Tipo empaquetado que se mantiene el ticket original
+ * @param vSelf Id del ticket original
+ * @param vOriginalItemPackingTypeFk Tipo de empaquetado a mantener en el ticket original
* @return table tmp.ticketIPT(ticketFk, itemPackingTypeFk)
*/
- DECLARE vDone INT DEFAULT FALSE;
- DECLARE vHasItemPackingType BOOL;
- DECLARE vItemPackingTypeFk INT;
+ DECLARE vIsDone BOOLEAN DEFAULT FALSE;
+ DECLARE vCurrentPackingType VARCHAR(1);
+ DECLARE vDefaultPackingType VARCHAR(1);
+ DECLARE vHasOriginalPackingType BOOLEAN;
DECLARE vNewTicketFk INT;
+ DECLARE vTicketFk INT;
- DECLARE vItemPackingTypes CURSOR FOR
- SELECT DISTINCT itemPackingTypeFk
- FROM tSalesToMove;
+ DECLARE vItemPackingTypes CURSOR FOR
+ SELECT DISTINCT itemPackingTypeFk FROM tSalesToMove;
- DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE;
- SELECT COUNT(*) INTO vHasItemPackingType
- FROM ticket t
- JOIN sale s ON s.ticketFk = t.id
- JOIN item i ON i.id = s.itemFk
- WHERE t.id = vSelf
- AND i.itemPackingTypeFk = vOriginalItemPackingTypeFk;
-
- CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT(
- ticketFk INT,
- itemPackingTypeFk VARCHAR(1)
- ) ENGINE=MEMORY
- SELECT vSelf ticketFk, vOriginalItemPackingTypeFk itemPackingTypeFk;
-
- IF NOT vHasItemPackingType THEN
- LEAVE proc;
- END IF;
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
CREATE OR REPLACE TEMPORARY TABLE tSalesToMove (
ticketFk INT,
saleFk INT,
- itemPackingTypeFk INT
+ itemPackingTypeFk VARCHAR(1)
) ENGINE=MEMORY;
+ SELECT COALESCE(MAX(ic.defaultPackingTypeFk), MAX(i.itemPackingTypeFk)) INTO vDefaultPackingType
+ FROM vn.sale s
+ JOIN item i ON i.id = s.itemFk
+ LEFT JOIN itemConfig ic ON ic.defaultPackingTypeFk = i.itemPackingTypeFk
+ WHERE s.ticketFk = vSelf
+ GROUP BY s.ticketFk;
+
+ SELECT EXISTS (
+ SELECT TRUE
+ FROM sale s
+ JOIN item i ON i.id = s.itemFk
+ WHERE s.ticketFk = vSelf
+ AND i.itemPackingTypeFk = vOriginalItemPackingTypeFk
+ ) INTO vHasOriginalPackingType;
+
+ IF vOriginalItemPackingTypeFk IS NULL OR NOT vHasOriginalPackingType THEN
+ SET vOriginalItemPackingTypeFk = vDefaultPackingType;
+ END IF;
+
+ START TRANSACTION;
+
+ SELECT t.id INTO vTicketFk
+ FROM ticket t
+ JOIN sale s ON s.id = t.id
+ WHERE t.id = vSelf
+ FOR UPDATE;
+
INSERT INTO tSalesToMove (saleFk, itemPackingTypeFk)
- SELECT s.id, i.itemPackingTypeFk
- FROM ticket t
- JOIN sale s ON s.ticketFk = t.id
- JOIN item i ON i.id = s.itemFk
- WHERE t.id = vSelf
+ SELECT s.id, i.itemPackingTypeFk
+ FROM sale s
+ JOIN item i ON i.id = s.itemFk
+ WHERE s.ticketFk = vSelf
AND i.itemPackingTypeFk <> vOriginalItemPackingTypeFk;
OPEN vItemPackingTypes;
-
l: LOOP
- SET vDone = FALSE;
- FETCH vItemPackingTypes INTO vItemPackingTypeFk;
+ SET vIsDone = FALSE;
+ FETCH vItemPackingTypes INTO vCurrentPackingType;
- IF vDone THEN
+ IF vIsDone THEN
LEAVE l;
END IF;
CALL ticket_Clone(vSelf, vNewTicketFk);
+ SELECT id INTO vTicketFk
+ FROM ticket t
+ WHERE t.id = vNewTicketFk
+ FOR UPDATE;
+
UPDATE tSalesToMove
SET ticketFk = vNewTicketFk
- WHERE itemPackingTypeFk = vItemPackingTypeFk;
+ WHERE itemPackingTypeFk = vCurrentPackingType;
+
+ IF vCurrentPackingType = vDefaultPackingType THEN
+ INSERT INTO tSalesToMove (ticketFk, saleFk, itemPackingTypeFk)
+ SELECT vNewTicketFk, s.id, i.itemPackingTypeFk
+ FROM sale s
+ JOIN item i ON i.id = s.itemFk
+ WHERE s.ticketFk = vSelf
+ AND i.itemPackingTypeFk IS NULL;
+ END IF;
END LOOP;
-
CLOSE vItemPackingTypes;
UPDATE sale s
- JOIN tSalesToMove stm ON stm.saleFk = s.id
- SET s.ticketFk = stm.ticketFk
- WHERE stm.ticketFk;
+ JOIN tSalesToMove t ON t.saleFk = s.id
+ SET s.ticketFk = t.ticketFk;
- INSERT INTO tmp.ticketIPT (ticketFk, itemPackingTypeFk)
- SELECT ticketFk, itemPackingTypeFk
+ CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT
+ ENGINE=MEMORY
+ SELECT s.ticketFk, MAX(i.itemPackingTypeFk) itemPackingTypeFk
+ FROM sale s
+ JOIN item i ON i.id = s.itemFk
+ WHERE s.ticketFk = vSelf
+ GROUP BY s.ticketFk
+ UNION
+ SELECT ticketFk, MAX(itemPackingTypeFk)
FROM tSalesToMove
GROUP BY ticketFk;
+ COMMIT;
+
DROP TEMPORARY TABLE tSalesToMove;
END$$
DELIMITER ;
diff --git a/db/routines/vn/procedures/travelVolume_get.sql b/db/routines/vn/procedures/travelVolume_get.sql
index 99c0acbb8..ab24a6395 100644
--- a/db/routines/vn/procedures/travelVolume_get.sql
+++ b/db/routines/vn/procedures/travelVolume_get.sql
@@ -10,7 +10,7 @@ BEGIN
JOIN vn.entry e ON e.travelFk = tr.id
JOIN vn.buy b ON b.entryFk = e.id
WHERE tr.landed BETWEEN vFromDated AND vToDated
- AND e.isRaid = FALSE
+ AND NOT tr.isRaid
AND tr.warehouseInFk = vWarehouseFk
GROUP BY tr.landed , a.name ;
END$$
diff --git a/db/routines/vn/procedures/travel_checkRaid.sql b/db/routines/vn/procedures/travel_checkRaid.sql
new file mode 100644
index 000000000..885fc718a
--- /dev/null
+++ b/db/routines/vn/procedures/travel_checkRaid.sql
@@ -0,0 +1,17 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`travel_checkRaid`(
+ vIsRaid BOOL,
+ vDaysInForward INT
+)
+BEGIN
+/**
+ * Check if the values of isRaid and daysInforward are correct
+ *
+ * @param vIsRaid idRaid value
+ * @param vDaysInForward daysInForward value
+ */
+ IF NOT vIsRaid AND vDaysInForward THEN
+ CALL util.throw('If daysInForward has a value, the raid cannot be unchecked');
+ END IF;
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/procedures/travel_cloneWithEntries.sql b/db/routines/vn/procedures/travel_cloneWithEntries.sql
index ee26aea32..5b2958edc 100644
--- a/db/routines/vn/procedures/travel_cloneWithEntries.sql
+++ b/db/routines/vn/procedures/travel_cloneWithEntries.sql
@@ -62,7 +62,7 @@ BEGIN
END IF;
CALL entry_cloneHeader(vAuxEntryFk, vNewEntryFk, vNewTravelFk);
- CALL entry_copyBuys(vAuxEntryFk, vNewEntryFk);
+ CALL entry_copyBuys(vAuxEntryFk, vNewEntryFk);
SELECT evaNotes INTO vEvaNotes
FROM entry
@@ -71,6 +71,8 @@ BEGIN
UPDATE entry
SET evaNotes = vEvaNotes
WHERE id = vNewEntryFk;
+
+ CALL buy_recalcPricesByEntry(vNewEntryFk);
END LOOP;
SET @isModeInventory = FALSE;
diff --git a/db/routines/vn/procedures/travel_moveRaids.sql b/db/routines/vn/procedures/travel_moveRaids.sql
index 95e02ec55..17d7ecc4c 100644
--- a/db/routines/vn/procedures/travel_moveRaids.sql
+++ b/db/routines/vn/procedures/travel_moveRaids.sql
@@ -1,72 +1,77 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`travel_moveRaids`()
BEGIN
-
-/*
- * Desplaza al dia siguiente los travels que contengan redadas y avisa a los compradores
- *
+/**
+ * Desplaza los travels en el futuro y avisa a los compradores
+ *
*/
DECLARE vDone BOOL DEFAULT FALSE;
- DECLARE vWorkerName VARCHAR(50);
- DECLARE vRaid TEXT;
- DECLARE vWorker VARCHAR(50) DEFAULT '';
- DECLARE vMailBody TEXT DEFAULT '';
+ DECLARE vBuyerEmail VARCHAR(40);
+ DECLARE vTravelLink TEXT;
+ DECLARE vMailBody TEXT;
+ DECLARE vDaysBetweenDates INT;
+ DECLARE vSubject VARCHAR(30);
- DECLARE vCur CURSOR FOR
- SELECT GROUP_CONCAT( DISTINCT CONCAT('https://salix.verdnatura.es/#!/travel/', ttr.id, '/summary ') ORDER BY ttr.id SEPARATOR '\n\r'),
- u.name
- FROM tmp.travel ttr
- JOIN entry e ON e.travelFk = ttr.id
- JOIN buy b ON b.entryFk = e.id
- JOIN item i ON i.id = b.itemFk
- JOIN itemType it ON it.id = i.typeFk
- JOIN account.user u ON u.id = it.workerFk
- GROUP BY u.name;
+ DECLARE vTravels CURSOR FOR
+ SELECT GROUP_CONCAT(DISTINCT travelLink ORDER BY id SEPARATOR '\n\r'),
+ buyerEmail
+ FROM tTravelToMove
+ GROUP BY buyerEmail;
- DECLARE CONTINUE HANDLER FOR NOT FOUND
- SET vDone = TRUE;
+ DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
-
- DROP TEMPORARY TABLE IF EXISTS tmp.travel;
- CREATE TEMPORARY TABLE tmp.travel
- SELECT tr.id,tr.landed
- FROM travel tr
- JOIN entry e ON e.travelFk = tr.id
- WHERE tr.landed = util.tomorrow()
- AND e.isRaid
- GROUP BY tr.id;
+
+ CREATE OR REPLACE TEMPORARY TABLE tTravelToMove
+ WITH travels AS (
+ SELECT id,
+ CONCAT('https://salix.verdnatura.es/#!/travel/', id,'/summary') travelLink,
+ util.VN_CURDATE() + INTERVAL daysInForward DAY newLanded,
+ util.VN_CURDATE() - INTERVAL DATEDIFF(landed, shipped) + daysInForward DAY newShipped
+ FROM vn.travel
+ WHERE isRaid
+ AND daysInForward
+ )SELECT t.id,
+ t.travelLink,
+ t.newLanded,
+ t.newShipped,
+ CONCAT(u.name, '@verdnatura.es') buyerEmail
+ FROM travels t
+ STRAIGHT_JOIN vn.entry e ON e.travelFk = t.id
+ 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 account.user u ON u.id = it.workerFk
+ GROUP BY t.id;
START TRANSACTION;
UPDATE travel tr
- JOIN tmp.travel ttr ON ttr.id = tr.id
- SET tr.landed = TIMESTAMPADD(DAY, 1, tr.landed);
+ JOIN tTravelToMove ttm ON ttm.id = tr.id
+ SET tr.landed = ttm.newLanded,
+ tr.shipped = ttm.newShipped;
- OPEN vCur;
+ OPEN vTravels;
l: LOOP
SET vDone = FALSE;
- FETCH vCur INTO vRaid, vWorkerName;
+ FETCH vTravels INTO vTravelLink, vBuyerEmail;
IF vDone THEN
LEAVE l;
END IF;
- CALL `vn`.`mail_insert`(CONCAT(vWorkerName, '@verdnatura.es'),
- 'noreply@verdnatura.es',
- 'Cambio de fecha en Redadas',
- CONCAT('Se ha movido las siguientes redadas: \n\r ', vRaid)
- );
+ SET vSubject = 'Cambio de fecha en Redadas',
+ vMailBody = CONCAT('Se ha movido los siguientes travels: \n\r ', vTravelLink);
+ CALL mail_insert(vBuyerEmail, 'noreply@verdnatura.es', vSubject, vMailBody);
END LOOP;
- CLOSE vCur;
+ CLOSE vTravels;
COMMIT;
- DROP TEMPORARY TABLE tmp.travel;
-
+ DROP TEMPORARY TABLE tTravelToMove;
END$$
DELIMITER ;
diff --git a/db/routines/vn/procedures/workerTimeControl_check.sql b/db/routines/vn/procedures/workerTimeControl_check.sql
deleted file mode 100644
index 30cf5c639..000000000
--- a/db/routines/vn/procedures/workerTimeControl_check.sql
+++ /dev/null
@@ -1,168 +0,0 @@
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`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 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;
- DECLARE vTo VARCHAR(50) DEFAULT NULL;
- DECLARE vUserName VARCHAR(50) DEFAULT NULL;
- DECLARE vBody VARCHAR(255) DEFAULT NULL;
-
- SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax
- INTO vDayBreak, vWeekBreak, vWeekScope, vDayWorkMax, vDayStayMax
- FROM workerTimeControlParams;
-
- SELECT MAX(timed) INTO vLastIn
- FROM workerTimeControl
- WHERE userFk = vUserFk
- AND direction = 'in';
-
- SELECT MAX(timed) INTO vLastOut
- FROM workerTimeControl
- WHERE userFk = vUserFk
- AND direction = 'out';
-
- SELECT CONCAT(u.name,'@verdnatura.es') INTO vTo
- FROM account.user u
- WHERE u.id = (SELECT bossFk FROM worker WHERE id = vUserFk);
-
- SELECT CONCAT(firstName,' ',lastName) INTO vUserName
- FROM worker w
- WHERE w.id = vUserFk;
-
-
- IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastIn) > vDayStayMax THEN -- NUEVA JORNADA
-
- -- VERIFICAR DESCANSO DIARIO
- IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN
- SELECT "Descansos 12 h" AS problem;
- -- ENVIAMOS CORREO AL BOSSFK
- SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 12 h") INTO vBody;
- CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
- END IF;
-
- -- VERIFICAR FICHADAS IMPARES DEL ÚLTIMO DÍA QUE SE FICHÓ
- IF (SELECT MOD(COUNT(*),2) -- <>0
- FROM workerTimeControl
- WHERE userFk = vUserFk
- AND timed >= vLastIn
- ) THEN
- SELECT "Dias con fichadas impares" AS problem;
- -- ENVIAMOS CORREO AL BOSSFK
- SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Dias con fichadas impares") INTO vBody;
- CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
- END IF;
-
- -- VERIFICAR VACACIONES
- SELECT at2.name INTO vCalendarStateType
- FROM calendar c
- JOIN business b ON b.id = c.businessFk
- JOIN absenceType at2 ON at2.id = c.dayOffTypeFk
- WHERE c.dated = util.VN_CURDATE()
- AND at2.isAllowedToWork = FALSE
- AND b.workerFk = vUserFk
- LIMIT 1;
-
- IF(LENGTH(vCalendarStateType)) THEN
- SELECT vCalendarStateType AS problem;
- -- ENVIAMOS CORREO AL BOSSFK
- SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Vacaciones") INTO vBody;
- CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
-
- END IF;
-
- -- VERIFICAR CONTRATO EN VIGOR
- IF (SELECT COUNT(*)
- FROM business b
- WHERE b.workerFk = vUserFk
- AND b.started <= vDated
- AND IFNULL(b.ended, vDated) >= vDated
- ) = 0 THEN
- SELECT "No hay un contrato en vigor" AS problem;
- -- ENVIAMOS CORREO AL BOSSFK
- SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"No hay un contrato en vigor") INTO vBody;
- CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
-
- END IF;
-
- -- VERIFICAR DESCANSO SEMANAL
- SET @vHasBreakWeek:= FALSE;
- SET @vLastTimed:= UNIX_TIMESTAMP((util.VN_NOW() - INTERVAL vWeekScope SECOND));
-
- DROP TEMPORARY TABLE IF EXISTS tmp.trash;
- CREATE TEMPORARY TABLE tmp.trash
- SELECT IF(vWeekBreak-(UNIX_TIMESTAMP(timed)-@vLastTimed) <= 0, @vHasBreakWeek:=TRUE, TRUE) alias,
- @vLastTimed:= UNIX_TIMESTAMP(timed)
- FROM workerTimeControl
- WHERE timed>= (util.VN_NOW() - INTERVAL vWeekScope SECOND)
- AND userFk= vUserFk
- AND direction IN ('in','out')
- ORDER BY timed ASC;
-
- IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA
- SELECT "Descansos 36 h" AS problem;
- -- ENVIAMOS CORREO AL BOSSFK
- SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 36 h") INTO vBody;
- CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
- END IF;
-
- DROP TEMPORARY TABLE tmp.trash;
-
- ELSE -- DIA ACTUAL
-
- -- VERIFICA QUE EL TIEMPO EFECTIVO NO SUPERE EL MÁXIMO
- SELECT IFNULL(SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))),0) - IF( MOD(COUNT(*),2), UNIX_TIMESTAMP(util.VN_NOW()), 0) INTO vTimedWorked
- FROM workerTimeControl wtc
- WHERE userFk = vUserFk
- AND timed >= vLastIn
- ORDER BY timed;
-
- IF vTimedWorked > vDayWorkMax THEN
- SELECT "Jornadas" AS problem;
- -- ENVIAMOS CORREO AL BOSSFK
- SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Jornadas") INTO vBody;
- CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
- END IF;
-
- END IF;
-
- -- VERIFICAR DEPARTAMENTO
- /* IF vTabletFk IS NOT NULL THEN
- SELECT wtcu.departmentFk INTO vDepartmentFk
- FROM workerTimeControlUserInfo wtcu
- WHERE wtcu.userFk = vUserFk;
- IF (SELECT COUNT(td.tabletFk)
- FROM tabletDepartment td
- WHERE td.tabletFk = vTabletFk AND td.departmentFk = vDepartmentFk
- ) = 0 THEN
- SELECT "No perteneces a este departamento." AS problem;
- -- ENVIAMOS CORREO AL BOSSFK
- SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No perteneces a este departamento.") INTO vBody;
- CALL mail_insert(vTo,vTo,'error al fichar',vBody);
- LEAVE proc;
- END IF;
- END IF;*/
-
-END$$
-DELIMITER ;
diff --git a/db/routines/vn/procedures/worker_updateBusiness.sql b/db/routines/vn/procedures/worker_updateBusiness.sql
index a160c417a..43edb0416 100644
--- a/db/routines/vn/procedures/worker_updateBusiness.sql
+++ b/db/routines/vn/procedures/worker_updateBusiness.sql
@@ -21,6 +21,8 @@ BEGIN
SET businessFk = vNewBusinessFk
WHERE id = vSelf;
+ CALL queueMember_updateQueue(vNewBusinessFk);
+
IF vOldBusinessFk IS NULL THEN
CALL account.account_enable(vSelf);
diff --git a/db/routines/vn/triggers/address_beforeInsert.sql b/db/routines/vn/triggers/address_beforeInsert.sql
index 56ef7aa51..a4f384f14 100644
--- a/db/routines/vn/triggers/address_beforeInsert.sql
+++ b/db/routines/vn/triggers/address_beforeInsert.sql
@@ -6,6 +6,7 @@ BEGIN
DECLARE vIsEqualizated BOOL;
SET NEW.editorFk = account.myUser_getId();
+ SET NEW.geoFk = address_getGeo(NEW.id);
IF (NEW.phone <> '') THEN
CALL pbx.phone_isValid(NEW.phone);
diff --git a/db/routines/vn/triggers/address_beforeUpdate.sql b/db/routines/vn/triggers/address_beforeUpdate.sql
index 35887912c..0b19a6266 100644
--- a/db/routines/vn/triggers/address_beforeUpdate.sql
+++ b/db/routines/vn/triggers/address_beforeUpdate.sql
@@ -3,7 +3,6 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`address_beforeUpdate`
BEFORE UPDATE ON `address`
FOR EACH ROW
BEGIN
-
SET NEW.editorFk = account.myUser_getId();
IF !(NEW.phone <=> OLD.phone) AND (NEW.phone <> '') THEN
@@ -14,5 +13,10 @@ BEGIN
CALL pbx.phone_isValid(NEW.mobile);
END IF;
+ IF NOT (NEW.provinceFk <=> OLD.provinceFk)
+ OR (NEW.postalCode <=> OLD.postalCode) THEN
+
+ SET NEW.geoFk = address_getGeo(NEW.id);
+ END IF;
END$$
DELIMITER ;
diff --git a/db/routines/vn/triggers/business_afterUpdate.sql b/db/routines/vn/triggers/business_afterUpdate.sql
index 888308b9a..11aeb88b6 100644
--- a/db/routines/vn/triggers/business_afterUpdate.sql
+++ b/db/routines/vn/triggers/business_afterUpdate.sql
@@ -3,10 +3,20 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`business_afterUpdate`
AFTER UPDATE ON `business`
FOR EACH ROW
BEGIN
+ DECLARE vIsActive BOOL;
+ DECLARE vExtension VARCHAR(10);
+
CALL worker_updateBusiness(NEW.workerFk);
IF NOT (OLD.workerFk <=> NEW.workerFk) THEN
CALL worker_updateBusiness(OLD.workerFk);
END IF;
+
+ IF NOT (OLD.departmentFk <=> NEW.departmentFk) THEN
+ SELECT COUNT(*) INTO vIsActive FROM worker WHERE businessFk = NEW.id;
+ IF vIsActive THEN
+ CALL queueMember_updateQueue(NEW.id);
+ END IF;
+ END IF;
END$$
DELIMITER ;
diff --git a/db/routines/vn/triggers/client_beforeInsert.sql b/db/routines/vn/triggers/client_beforeInsert.sql
index 45de107f1..b4038a2ba 100644
--- a/db/routines/vn/triggers/client_beforeInsert.sql
+++ b/db/routines/vn/triggers/client_beforeInsert.sql
@@ -3,8 +3,10 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`client_beforeInsert`
BEFORE INSERT ON `client`
FOR EACH ROW
BEGIN
-
SET NEW.editorFk = account.myUser_getId();
+ SET NEW.accountingAccount = 4300000000 + NEW.id;
+ SET NEW.lastSalesPersonFk = NEW.salesPersonFk;
+ SET NEW.geoFk = client_getGeo(NEW.id);
IF (NEW.phone <> '') THEN
CALL pbx.phone_isValid(NEW.phone);
@@ -13,9 +15,5 @@ BEGIN
IF (NEW.mobile <> '') THEN
CALL pbx.phone_isValid(NEW.mobile);
END IF;
-
- SET NEW.accountingAccount = 4300000000 + NEW.id;
-
- SET NEW.lastSalesPersonFk = NEW.salesPersonFk;
END$$
DELIMITER ;
diff --git a/db/routines/vn/triggers/client_beforeUpdate.sql b/db/routines/vn/triggers/client_beforeUpdate.sql
index 7142d6604..00418a9e7 100644
--- a/db/routines/vn/triggers/client_beforeUpdate.sql
+++ b/db/routines/vn/triggers/client_beforeUpdate.sql
@@ -72,5 +72,11 @@ BEGIN
IF NOT (NEW.businessTypeFk <=> OLD.businessTypeFk) AND (NEW.businessTypeFk = 'individual' OR OLD.businessTypeFk = 'individual') THEN
SET NEW.isTaxDataChecked = 0;
END IF;
+
+ IF NOT (NEW.provinceFk <=> OLD.provinceFk)
+ OR (NEW.postcode <=> OLD.postcode) THEN
+
+ SET NEW.geoFk = client_getGeo(NEW.id);
+ END IF;
END$$
DELIMITER ;
diff --git a/db/routines/vn/triggers/entry_beforeUpdate.sql b/db/routines/vn/triggers/entry_beforeUpdate.sql
index 8e5a326a0..4f2c5ed4a 100644
--- a/db/routines/vn/triggers/entry_beforeUpdate.sql
+++ b/db/routines/vn/triggers/entry_beforeUpdate.sql
@@ -3,7 +3,7 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`entry_beforeUpdate`
BEFORE UPDATE ON `entry`
FOR EACH ROW
BEGIN
- DECLARE vIsVirtual BOOL;
+ DECLARE vIsRaid BOOL;
DECLARE vPrintedCount INT;
DECLARE vHasDistinctWarehouses BOOL;
DECLARE vTotalBuy INT;
@@ -37,18 +37,20 @@ BEGIN
IF NEW.travelFk IS NOT NULL THEN
CALL travel_throwAwb(NEW.travelFk);
END IF;
-
- SELECT COUNT(*) > 0 INTO vIsVirtual
- FROM entryVirtual WHERE entryFk = NEW.id;
+
+ SELECT t.isRaid INTO vIsRaid
+ FROM travel t
+ JOIN entry e ON e.travelFk = t.id
+ WHERE e.id = NEW.id;
SELECT NOT (o.warehouseInFk <=> n.warehouseInFk)
- OR NOT (o.warehouseOutFk <=> n.warehouseOutFk)
+ OR NOT (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
+ IF vIsRaid AND vHasDistinctWarehouses THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'A cloned entry cannot be moved to a travel with different warehouses';
END IF;
@@ -71,7 +73,7 @@ BEGIN
SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk);
END IF;
- IF NOT (NEW.travelFk <=> OLD.travelFk)
+ IF NOT (NEW.travelFk <=> OLD.travelFk)
OR NOT (NEW.currencyFk <=> OLD.currencyFk)
OR NOT (NEW.supplierFk <=> OLD.supplierFk) THEN
diff --git a/db/routines/vn/triggers/expedition_beforeDelete.sql b/db/routines/vn/triggers/expedition_beforeDelete.sql
index 13ba19631..60d3a6ca1 100644
--- a/db/routines/vn/triggers/expedition_beforeDelete.sql
+++ b/db/routines/vn/triggers/expedition_beforeDelete.sql
@@ -7,6 +7,7 @@ BEGIN
SET packages = (SELECT COUNT(counter)-1
FROM expedition e WHERE e.ticketFk = OLD.ticketFk and e.freightItemFk)
WHERE t.id = OLD.ticketFk;
-
+
+ CALL expedition_selfConsumptionPackaging(OLD.id, 'remove');
END$$
DELIMITER ;
diff --git a/db/routines/vn/triggers/invoiceIn_afterUpdate.sql b/db/routines/vn/triggers/invoiceIn_afterUpdate.sql
index 95b1d98a9..8c2785e38 100644
--- a/db/routines/vn/triggers/invoiceIn_afterUpdate.sql
+++ b/db/routines/vn/triggers/invoiceIn_afterUpdate.sql
@@ -3,24 +3,30 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`invoiceIn_afterUpdate`
AFTER UPDATE ON `invoiceIn`
FOR EACH ROW
BEGIN
- IF NEW.issued != OLD.issued
- OR NEW.currencyFk != OLD.currencyFk THEN
+ DECLARE vIsEuro BOOL;
+
+ SELECT `code` = 'EUR' INTO vIsEuro
+ FROM currency
+ WHERE id = NEW.currencyFk;
+
+ IF (NOT NEW.issued <=> OLD.issued
+ OR NEW.currencyFk <> OLD.currencyFk) THEN
UPDATE invoiceInTax iit
JOIN invoiceIn ii ON ii.id = iit.invoiceInFk
LEFT JOIN referenceRate rr ON rr.dated = ii.issued
AND rr.currencyFk = ii.currencyFk
- SET iit.taxableBase = IF(iit.foreignValue IS NULL, iit.taxableBase, iit.foreignValue / rr.value)
+ SET iit.taxableBase = IF(vIsEuro, iit.taxableBase, iit.foreignValue / rr.value),
+ iit.foreignValue = IF(vIsEuro, NULL, iit.foreignValue)
WHERE ii.id = NEW.id;
UPDATE invoiceInDueDay iidd
JOIN invoiceIn ii ON ii.id = iidd.invoiceInFk
LEFT JOIN referenceRate rr ON rr.dated = ii.issued
AND rr.currencyFk = ii.currencyFk
- SET iidd.amount = IF(iidd.foreignValue IS NULL, iidd.amount, iidd.foreignValue / rr.value)
+ SET iidd.amount = IF(vIsEuro, iidd.amount, iidd.foreignValue / rr.value),
+ iidd.foreignValue = IF(vIsEuro, NULL, iidd.foreignValue)
WHERE ii.id = NEW.id;
-
END IF;
-
END$$
DELIMITER ;
diff --git a/db/routines/vn/triggers/itemCost_beforeUpdate.sql b/db/routines/vn/triggers/itemCost_beforeUpdate.sql
index bd5fde85a..8de288a92 100644
--- a/db/routines/vn/triggers/itemCost_beforeUpdate.sql
+++ b/db/routines/vn/triggers/itemCost_beforeUpdate.sql
@@ -16,7 +16,7 @@ BEGIN
JOIN vn.route r ON r.id = t.routeFk
WHERE r.isOk = FALSE
AND ic.itemFk = NEW.itemFk
- AND r.created >= util.VN_CURDATE()
+ AND r.dated >= util.VN_CURDATE()
GROUP BY r.id;
IF NEW.cm3Delivery = 0 AND NEW.warehouseFk = 60 THEN
CALL mail_insert(
diff --git a/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql b/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql
index 3531b094c..ad4a6f670 100644
--- a/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql
+++ b/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql
@@ -3,10 +3,10 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`itemShelvingSale_afterI
AFTER INSERT ON `itemShelvingSale`
FOR EACH ROW
BEGIN
-
UPDATE sale s
JOIN operator o ON o.workerFk = account.myUser_getId()
- SET s.isPicked = IF(o.isOnReservationMode, s.isPicked, TRUE)
- WHERE id = NEW.saleFk;
+ JOIN sector se ON se.id = o.sectorFk
+ SET s.isPicked = IF(IFNULL(se.isOnReservationMode, o.isOnReservationMode), s.isPicked, TRUE)
+ WHERE s.id = NEW.saleFk;
END$$
DELIMITER ;
\ No newline at end of file
diff --git a/db/routines/vn/triggers/itemShelving_afterInsert.sql b/db/routines/vn/triggers/itemShelving_afterInsert.sql
deleted file mode 100644
index 92243ca03..000000000
--- a/db/routines/vn/triggers/itemShelving_afterInsert.sql
+++ /dev/null
@@ -1,18 +0,0 @@
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`itemShelving_afterInsert`
- AFTER INSERT ON `itemShelving`
- FOR EACH ROW
-BEGIN
- INSERT INTO itemShelvingLog
- SET itemShelvingFk = NEW.id,
- workerFk = account.myUser_getId(),
- accion = 'CREA REGISTRO',
- itemFk = NEW.itemFk,
- shelvingFk = NEW.shelvingFk,
- visible = NEW.visible,
- `grouping` = NEW.`grouping`,
- packing = NEW.packing,
- available = NEW.available;
-
-END$$
-DELIMITER ;
diff --git a/db/routines/vn/triggers/itemShelving_afterUpdate.sql b/db/routines/vn/triggers/itemShelving_afterUpdate.sql
deleted file mode 100644
index e5e63db43..000000000
--- a/db/routines/vn/triggers/itemShelving_afterUpdate.sql
+++ /dev/null
@@ -1,18 +0,0 @@
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`itemShelving_afterUpdate`
- AFTER UPDATE ON `itemShelving`
- FOR EACH ROW
-BEGIN
- INSERT INTO itemShelvingLog
- SET itemShelvingFk = NEW.id,
- workerFk = account.myUser_getId(),
- accion = 'CAMBIO',
- itemFk = NEW.itemFk,
- shelvingFk = NEW.shelvingFk,
- visible = NEW.visible,
- `grouping` = NEW.`grouping`,
- packing = NEW.packing,
- available = NEW.available;
-
-END$$
-DELIMITER ;
diff --git a/db/routines/vn/triggers/itemShelving_beforeDelete.sql b/db/routines/vn/triggers/itemShelving_beforeDelete.sql
deleted file mode 100644
index 89737a841..000000000
--- a/db/routines/vn/triggers/itemShelving_beforeDelete.sql
+++ /dev/null
@@ -1,15 +0,0 @@
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`itemShelving_beforeDelete`
- BEFORE DELETE ON `itemShelving`
- FOR EACH ROW
-INSERT INTO vn.itemShelvingLog(itemShelvingFk,
- workerFk,
- accion,
- shelvingFk,
- itemFk)
- VALUES( OLD.id,
- account.myUser_getId(),
- 'ELIMINADO',
- OLD.shelvingFk,
- OLD.itemFk)$$
-DELIMITER ;
diff --git a/db/routines/vn/triggers/itemShelving_beforeUpdate.sql b/db/routines/vn/triggers/itemShelving_beforeUpdate.sql
index fabdf8efb..53f85de01 100644
--- a/db/routines/vn/triggers/itemShelving_beforeUpdate.sql
+++ b/db/routines/vn/triggers/itemShelving_beforeUpdate.sql
@@ -9,5 +9,8 @@ BEGIN
SET NEW.userFk = account.myUser_getId();
END IF;
+ IF NEW.shelvingFk <> OLD.shelvingFk THEN
+ SET NEW.movingState = NULL;
+ END IF;
END$$
DELIMITER ;
diff --git a/db/routines/vn/triggers/itemType_afterDelete.sql b/db/routines/vn/triggers/itemType_afterDelete.sql
new file mode 100644
index 000000000..32a1ba31c
--- /dev/null
+++ b/db/routines/vn/triggers/itemType_afterDelete.sql
@@ -0,0 +1,12 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`itemType_afterDelete`
+ AFTER DELETE ON `itemType`
+ FOR EACH ROW
+BEGIN
+ INSERT INTO itemTypeLog
+ SET `action` = 'delete',
+ `changedModel` = 'ItemType',
+ `changedModelId` = OLD.id,
+ `userFk` = account.myUser_getId();
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/triggers/itemType_beforeInsert.sql b/db/routines/vn/triggers/itemType_beforeInsert.sql
new file mode 100644
index 000000000..d33d8fb56
--- /dev/null
+++ b/db/routines/vn/triggers/itemType_beforeInsert.sql
@@ -0,0 +1,8 @@
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`itemType_beforeInsert`
+ BEFORE INSERT ON `itemType`
+ FOR EACH ROW
+BEGIN
+ SET NEW.editorFk = account.myUser_getId();
+END$$
+DELIMITER ;
diff --git a/db/routines/vn/triggers/itemType_beforeUpdate.sql b/db/routines/vn/triggers/itemType_beforeUpdate.sql
index 613ae8bfa..6a03d40d0 100644
--- a/db/routines/vn/triggers/itemType_beforeUpdate.sql
+++ b/db/routines/vn/triggers/itemType_beforeUpdate.sql
@@ -3,6 +3,7 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`itemType_beforeUpdate`
BEFORE UPDATE ON `itemType`
FOR EACH ROW
BEGIN
+ SET NEW.editorFk = account.myUser_getId();
IF NEW.itemPackingTypeFk = '' THEN
SET NEW.itemPackingTypeFk = NULL;
diff --git a/db/routines/vn/triggers/productionConfig_afterDelete.sql b/db/routines/vn/triggers/productionConfig_afterDelete.sql
index 6b6800d4f..bd485d590 100644
--- a/db/routines/vn/triggers/productionConfig_afterDelete.sql
+++ b/db/routines/vn/triggers/productionConfig_afterDelete.sql
@@ -3,7 +3,7 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`productionConfig_afterD
AFTER DELETE ON `productionConfig`
FOR EACH ROW
BEGIN
- INSERT INTO productionConfig
+ INSERT INTO productionConfigLog
SET `action` = 'delete',
`changedModel` = 'ProductionConfig',
`changedModelId` = OLD.id,
diff --git a/db/routines/vn/triggers/route_afterUpdate.sql b/db/routines/vn/triggers/route_afterUpdate.sql
index ec205090e..a15c1a4b7 100644
--- a/db/routines/vn/triggers/route_afterUpdate.sql
+++ b/db/routines/vn/triggers/route_afterUpdate.sql
@@ -2,18 +2,18 @@ DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`route_afterUpdate`
AFTER UPDATE ON `route`
FOR EACH ROW
-BEGIN
+BEGIN
IF IFNULL(NEW.gestdocFk,0) <> IFNULL(OLD.gestdocFk,0) AND NEW.gestdocFk > 0 THEN
-- JGF 09/09/14 cuando se añade un gestdoc a una ruta, se le asigna automagicamente a todos sus Tickets
-
+
-- Inserta el gestdoc en todos los tickets de la ruta
INSERT INTO ticketDms(ticketFk,dmsFk)
SELECT id, NEW.gestdocFk FROM ticket WHERE routeFk = NEW.id
ON DUPLICATE KEY UPDATE dmsFk = NEW.gestdocFk;
- -- Update del firmado
- UPDATE ticket t
- JOIN ticketDms tg ON t.id = tg.ticketFk
+ -- Update del firmado
+ UPDATE ticket t
+ JOIN ticketDms tg ON t.id = tg.ticketFk
SET isSigned = 1 WHERE t.routeFk = NEW.id;
END IF;
@@ -21,7 +21,9 @@ BEGIN
OR !(NEW.kmEnd <=> OLD.kmEnd)
OR !(NEW.workerFk <=> OLD.workerFk)
OR !(NEW.m3 <=> OLD.m3)
- OR !(NEW.agencyModeFk <=> OLD.agencyModeFk)THEN
+ OR !(NEW.agencyModeFk <=> OLD.agencyModeFk)
+ OR !(NEW.dated <=> OLD.dated)
+ OR !(NEW.vehicleFk <=> OLD.vehicleFk)THEN
CALL route_calcCommission(NEW.id);
END IF;
diff --git a/db/routines/vn/triggers/route_beforeInsert.sql b/db/routines/vn/triggers/route_beforeInsert.sql
index 788efe662..0afc9617e 100644
--- a/db/routines/vn/triggers/route_beforeInsert.sql
+++ b/db/routines/vn/triggers/route_beforeInsert.sql
@@ -14,7 +14,7 @@ BEGIN
SELECT IFNULL(b.workCenterFK, r.defaultWorkCenterFk)
FROM vn.routeConfig r
LEFT JOIN vn.business b ON b.workerFk = vUserFk
- AND NEW.created BETWEEN b.started AND IFNULL(b.ended, NEW.created));
+ AND NEW.dated BETWEEN b.started AND IFNULL(b.ended, NEW.dated));
IF ISNULL(NEW.agencyModeFk) THEN
SELECT r.agencyModeFk INTO vDefaultAgencyModeFk
diff --git a/db/routines/vn/triggers/sale_afterInsert.sql b/db/routines/vn/triggers/sale_afterInsert.sql
index f15b17722..1a9ef240a 100644
--- a/db/routines/vn/triggers/sale_afterInsert.sql
+++ b/db/routines/vn/triggers/sale_afterInsert.sql
@@ -23,7 +23,7 @@ BEGIN
JOIN vn.route r ON r.id = t.routeFk
WHERE r.isOk = FALSE
AND s.id = NEW.id
- AND r.created >= util.VN_CURDATE()
+ AND r.dated >= util.VN_CURDATE()
GROUP BY r.id;
END IF;
END$$
diff --git a/db/routines/vn/triggers/sale_afterUpdate.sql b/db/routines/vn/triggers/sale_afterUpdate.sql
index 82da55486..49e5383d0 100644
--- a/db/routines/vn/triggers/sale_afterUpdate.sql
+++ b/db/routines/vn/triggers/sale_afterUpdate.sql
@@ -54,7 +54,7 @@ BEGIN
JOIN vn.route r ON r.id = t.routeFk
WHERE r.isOk = FALSE
AND s.id = NEW.id
- AND r.created >= util.VN_CURDATE()
+ AND r.dated >= util.VN_CURDATE()
GROUP BY r.id;
END IF;
diff --git a/db/routines/vn/triggers/sale_beforeDelete.sql b/db/routines/vn/triggers/sale_beforeDelete.sql
index ad97f8b55..0f72d788b 100644
--- a/db/routines/vn/triggers/sale_beforeDelete.sql
+++ b/db/routines/vn/triggers/sale_beforeDelete.sql
@@ -11,7 +11,7 @@ BEGIN
JOIN vn.route r ON r.id = t.routeFk
WHERE r.isOk = FALSE
AND s.id = OLD.id
- AND r.created >= util.VN_CURDATE()
+ AND r.dated >= util.VN_CURDATE()
GROUP BY r.id;
END IF;
END$$
diff --git a/db/routines/vn/triggers/supplier_beforeInsert.sql b/db/routines/vn/triggers/supplier_beforeInsert.sql
index b141ec8fb..5bbfc79a1 100644
--- a/db/routines/vn/triggers/supplier_beforeInsert.sql
+++ b/db/routines/vn/triggers/supplier_beforeInsert.sql
@@ -4,5 +4,6 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`supplier_beforeInsert`
FOR EACH ROW
BEGIN
SET NEW.editorFk = account.myUser_getId();
+ SET NEW.geoFk = supplier_getGeo(NEW.id);
END$$
DELIMITER ;
diff --git a/db/routines/vn/triggers/supplier_beforeUpdate.sql b/db/routines/vn/triggers/supplier_beforeUpdate.sql
index af730b49d..b502340a3 100644
--- a/db/routines/vn/triggers/supplier_beforeUpdate.sql
+++ b/db/routines/vn/triggers/supplier_beforeUpdate.sql
@@ -40,5 +40,10 @@ BEGIN
SET NEW.isPayMethodChecked = FALSE;
END IF;
+ IF NOT (NEW.provinceFk <=> OLD.provinceFk)
+ OR (NEW.postCode <=> OLD.postCode) THEN
+
+ SET NEW.geoFk = supplier_getGeo(NEW.id);
+ END IF;
END$$
DELIMITER ;
diff --git a/db/routines/vn/triggers/ticketRefund_beforeInsert.sql b/db/routines/vn/triggers/ticketRefund_beforeInsert.sql
index 61d9fe7a2..dd1da6650 100644
--- a/db/routines/vn/triggers/ticketRefund_beforeInsert.sql
+++ b/db/routines/vn/triggers/ticketRefund_beforeInsert.sql
@@ -3,6 +3,8 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`ticketRefund_beforeInse
BEFORE INSERT ON `ticketRefund`
FOR EACH ROW
BEGIN
+ CALL ticketRefund_upsert(NEW.refundTicketFk, NEW.originalTicketFk);
+
SET NEW.editorFk = account.myUser_getId();
END$$
DELIMITER ;
diff --git a/db/routines/vn/triggers/ticketRefund_beforeUpdate.sql b/db/routines/vn/triggers/ticketRefund_beforeUpdate.sql
index 807695de6..f27e3f092 100644
--- a/db/routines/vn/triggers/ticketRefund_beforeUpdate.sql
+++ b/db/routines/vn/triggers/ticketRefund_beforeUpdate.sql
@@ -3,6 +3,8 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`ticketRefund_beforeUpda
BEFORE UPDATE ON `ticketRefund`
FOR EACH ROW
BEGIN
+ CALL ticketRefund_upsert(NEW.refundTicketFk, NEW.originalTicketFk);
+
SET NEW.editorFk = account.myUser_getId();
END$$
DELIMITER ;
diff --git a/db/routines/vn/triggers/ticket_beforeDelete.sql b/db/routines/vn/triggers/ticket_beforeDelete.sql
index 953fa509a..2115175b5 100644
--- a/db/routines/vn/triggers/ticket_beforeDelete.sql
+++ b/db/routines/vn/triggers/ticket_beforeDelete.sql
@@ -8,7 +8,7 @@ BEGIN
FROM vn.route r
WHERE r.isOk = FALSE
AND r.id = OLD.routeFk
- AND r.created >= util.VN_CURDATE()
+ AND r.dated >= util.VN_CURDATE()
GROUP BY r.id;
DELETE FROM sale WHERE ticketFk = OLD.id;
diff --git a/db/routines/vn/triggers/ticket_beforeUpdate.sql b/db/routines/vn/triggers/ticket_beforeUpdate.sql
index 3208a93d0..f86f50485 100644
--- a/db/routines/vn/triggers/ticket_beforeUpdate.sql
+++ b/db/routines/vn/triggers/ticket_beforeUpdate.sql
@@ -22,7 +22,7 @@ BEGIN
FROM `route`
WHERE NOT isOk
AND id IN (OLD.routeFk, NEW.routeFk)
- AND created >= util.VN_CURDATE()
+ AND dated >= util.VN_CURDATE()
GROUP BY id;
END IF;
@@ -45,7 +45,7 @@ BEGIN
JOIN vn.route r ON r.id = t.routeFk
WHERE r.isOk = FALSE
AND t.id = NEW.id
- AND r.created >= util.VN_CURDATE()
+ AND r.dated >= util.VN_CURDATE()
GROUP BY r.id;
SET NEW.shipped = DATE_FORMAT(NEW.shipped, '2000-%m-%d %T');
SET NEW.landed = DATE_FORMAT(NEW.landed, '2000-%m-%d %T');
diff --git a/db/routines/vn/triggers/town_beforeUpdate.sql b/db/routines/vn/triggers/town_beforeUpdate.sql
deleted file mode 100644
index fc1410d5c..000000000
--- a/db/routines/vn/triggers/town_beforeUpdate.sql
+++ /dev/null
@@ -1,10 +0,0 @@
-DELIMITER $$
-CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`town_beforeUpdate`
- BEFORE UPDATE ON `town`
- FOR EACH ROW
-BEGIN
- -- IF !(OLD.geoFk <=> NEW.geoFk) THEN
- -- CALL zoneGeo_throwNotEditable;
- -- END IF;
-END$$
-DELIMITER ;
diff --git a/db/routines/vn/triggers/travel_beforeInsert.sql b/db/routines/vn/triggers/travel_beforeInsert.sql
index 4563c9a81..5356ed537 100644
--- a/db/routines/vn/triggers/travel_beforeInsert.sql
+++ b/db/routines/vn/triggers/travel_beforeInsert.sql
@@ -8,7 +8,11 @@ BEGIN
CALL travel_checkDates(NEW.shipped, NEW.landed);
CALL travel_checkWarehouseIsFeedStock(NEW.warehouseInFk);
-
+
+ IF NEW.isRaid IS NOT NULL OR NEW.daysInForward IS NOT NULL THEN
+ CALL travel_checkRaid(NEW.isRaid, NEW.daysInForward);
+ END IF;
+
IF NEW.awbFk IS NOT NULL THEN
CALL travel_throwAwb(NEW.id);
END IF;
diff --git a/db/routines/vn/triggers/travel_beforeUpdate.sql b/db/routines/vn/triggers/travel_beforeUpdate.sql
index 33578fea1..5a27b43b4 100644
--- a/db/routines/vn/triggers/travel_beforeUpdate.sql
+++ b/db/routines/vn/triggers/travel_beforeUpdate.sql
@@ -7,7 +7,7 @@ BEGIN
SET NEW.editorFk = account.myUser_getId();
- IF NOT (NEW.landed <=> OLD.landed)
+ IF NOT (NEW.landed <=> OLD.landed)
OR NOT (NEW.shipped <=> OLD.shipped) THEN
CALL travel_checkDates(NEW.shipped, NEW.landed);
END IF;
@@ -20,19 +20,23 @@ BEGIN
CALL travel_checkWarehouseIsFeedStock(NEW.warehouseInFk);
END IF;
+ IF NOT (NEW.isRaid <=> OLD.isRaid) OR NOT (NEW.daysInForward <=> OLD.daysInForward) THEN
+ CALL travel_checkRaid(NEW.isRaid, NEW.daysInForward);
+ END IF;
+
IF NOT (NEW.awbFk <=> OLD.awbFk)THEN
- SELECT COUNT(*) INTO vHasAnyInvoiceBooked
+ SELECT COUNT(*) INTO vHasAnyInvoiceBooked
FROM travel t
- JOIN entry e ON e.travelFk = t.id
- JOIN invoiceIn ii ON ii.id = e.invoiceInFk
+ JOIN entry e ON e.travelFk = t.id
+ JOIN invoiceIn ii ON ii.id = e.invoiceInFk
WHERE t.id = NEW.id
- AND ii.isBooked;
-
+ AND ii.isBooked;
+
IF vHasAnyInvoiceBooked THEN
CALL util.throw('The travel has entries with booked invoices');
END IF;
- END IF;
-
+ END IF;
+
IF (NOT(NEW.awbFk <=> OLD.awbFk)) AND NEW.awbFk IS NOT NULL THEN
CALL travel_throwAwb(NEW.id);
END IF;
diff --git a/db/routines/vn/views/expeditionPallet_Print.sql b/db/routines/vn/views/expeditionPallet_Print.sql
index 7b933a0a1..0a445a4a6 100644
--- a/db/routines/vn/views/expeditionPallet_Print.sql
+++ b/db/routines/vn/views/expeditionPallet_Print.sql
@@ -9,8 +9,8 @@ AS SELECT `rs2`.`description` AS `truck`,
`rs`.`id` <=> `rm`.`roadmapStopFk` AS `isMatch`,
`t`.`warehouseFk` AS `warehouseFk`,
IF(
- `r`.`created` > `util`.`VN_CURDATE`() + INTERVAL 1 DAY,
- ucase(dayname(`r`.`created`)),
+ `r`.`dated` > `util`.`VN_CURDATE`() + INTERVAL 1 DAY,
+ ucase(dayname(`r`.`dated`)),
NULL
) AS `nombreDia`
FROM (
diff --git a/db/routines/vn/views/expeditionRoute_Monitor.sql b/db/routines/vn/views/expeditionRoute_Monitor.sql
index 9b46c8237..716702753 100644
--- a/db/routines/vn/views/expeditionRoute_Monitor.sql
+++ b/db/routines/vn/views/expeditionRoute_Monitor.sql
@@ -6,7 +6,7 @@ AS SELECT `r`.`id` AS `routeFk`,
COUNT(DISTINCT `e`.`id`) AS `expeditions`,
COUNT(DISTINCT `es`.`id`) AS `scanned`,
max(`e`.`created`) AS `lastPacked`,
- `r`.`created` AS `created`
+ `r`.`dated` AS `created`
FROM (
(
(
@@ -23,5 +23,5 @@ FROM (
)
LEFT JOIN `vn`.`expeditionScan` `es` ON(`es`.`expeditionFk` = `e`.`id`)
)
-WHERE `r`.`created` >= `util`.`yesterday`()
+WHERE `r`.`dated` >= `util`.`yesterday`()
GROUP BY `r`.`id`
diff --git a/db/routines/vn/views/itemEntryIn.sql b/db/routines/vn/views/itemEntryIn.sql
index 4f7855d2b..60af585f2 100644
--- a/db/routines/vn/views/itemEntryIn.sql
+++ b/db/routines/vn/views/itemEntryIn.sql
@@ -6,7 +6,7 @@ AS SELECT `t`.`warehouseInFk` AS `warehouseInFk`,
`b`.`itemFk` AS `itemFk`,
`b`.`quantity` AS `quantity`,
`t`.`isReceived` AS `isReceived`,
- `e`.`isRaid` AS `isVirtualStock`,
+ `t`.`isRaid` AS `isVirtualStock`,
`e`.`id` AS `entryFk`
FROM (
(
diff --git a/db/routines/vn/views/itemEntryOut.sql b/db/routines/vn/views/itemEntryOut.sql
index 1e8718c53..4793ddbb8 100644
--- a/db/routines/vn/views/itemEntryOut.sql
+++ b/db/routines/vn/views/itemEntryOut.sql
@@ -15,5 +15,5 @@ FROM (
JOIN `vn`.`travel` `t` ON(`e`.`travelFk` = `t`.`id`)
)
WHERE `e`.`isExcludedFromAvailable` = 0
- AND `e`.`isRaid` = 0
+ AND NOT `t`.`isRaid`
AND `b`.`quantity` <> 0
diff --git a/db/routines/vn/views/itemShelvingList.sql b/db/routines/vn/views/itemShelvingList.sql
index 457d6f28a..f2cfeda58 100644
--- a/db/routines/vn/views/itemShelvingList.sql
+++ b/db/routines/vn/views/itemShelvingList.sql
@@ -15,7 +15,7 @@ FROM (
(
(
`vn`.`itemShelving` `ish`
- JOIN `vn`.`shelving` `sh` ON(`sh`.`code` = `ish`.`shelvingFk`)
+ JOIN `vn`.`shelving` `sh` ON(`sh`.`id` = `ish`.`shelvingFk`)
)
JOIN `vn`.`item` `i` ON(`i`.`id` = `ish`.`itemFk`)
)
diff --git a/db/routines/vn/views/itemShelvingPlacementSupplyStock.sql b/db/routines/vn/views/itemShelvingPlacementSupplyStock.sql
index fa1c11314..1ebb6410c 100644
--- a/db/routines/vn/views/itemShelvingPlacementSupplyStock.sql
+++ b/db/routines/vn/views/itemShelvingPlacementSupplyStock.sql
@@ -18,7 +18,7 @@ FROM (
(
(
`vn`.`itemShelving` `ish`
- JOIN `vn`.`shelving` `sh` ON(`sh`.`code` = `ish`.`shelvingFk`)
+ JOIN `vn`.`shelving` `sh` ON(`sh`.`id` = `ish`.`shelvingFk`)
)
LEFT JOIN `vn`.`parking` `p` ON(`p`.`id` = `sh`.`parkingFk`)
)
diff --git a/db/routines/vn/views/itemShelvingSaleSum.sql b/db/routines/vn/views/itemShelvingSaleSum.sql
index 9a402d6f4..60581faa9 100644
--- a/db/routines/vn/views/itemShelvingSaleSum.sql
+++ b/db/routines/vn/views/itemShelvingSaleSum.sql
@@ -13,7 +13,7 @@ FROM (
`vn`.`itemShelvingSale` `iss`
JOIN `vn`.`itemShelving` `ish` ON(`ish`.`id` = `iss`.`itemShelvingFk`)
)
- JOIN `vn`.`shelving` `sh` ON(`sh`.`code` = `ish`.`shelvingFk`)
+ JOIN `vn`.`shelving` `sh` ON(`sh`.`id` = `ish`.`shelvingFk`)
)
JOIN `vn`.`parking` `p` ON(`p`.`id` = `sh`.`parkingFk`)
)
diff --git a/db/routines/vn/views/itemShelvingStock.sql b/db/routines/vn/views/itemShelvingStock.sql
index 41777eaec..725a06f88 100644
--- a/db/routines/vn/views/itemShelvingStock.sql
+++ b/db/routines/vn/views/itemShelvingStock.sql
@@ -21,7 +21,7 @@ FROM (
(
(
`vn`.`itemShelving` `ish`
- LEFT JOIN `vn`.`shelving` `sh` ON(`sh`.`code` = `ish`.`shelvingFk`)
+ LEFT JOIN `vn`.`shelving` `sh` ON(`sh`.`id` = `ish`.`shelvingFk`)
)
LEFT JOIN `vn`.`parking` `p` ON(`p`.`id` = `sh`.`parkingFk`)
)
diff --git a/db/routines/vn/views/itemShelvingStockFull.sql b/db/routines/vn/views/itemShelvingStockFull.sql
index c767823d6..c8a82685c 100644
--- a/db/routines/vn/views/itemShelvingStockFull.sql
+++ b/db/routines/vn/views/itemShelvingStockFull.sql
@@ -19,7 +19,7 @@ FROM (
(
(
`vn`.`itemShelving` `ish`
- JOIN `vn`.`shelving` `sh` ON(`sh`.`code` = `ish`.`shelvingFk`)
+ JOIN `vn`.`shelving` `sh` ON(`sh`.`id` = `ish`.`shelvingFk`)
)
JOIN `vn`.`parking` `p` ON(`p`.`id` = `sh`.`parkingFk`)
)
diff --git a/db/routines/vn/views/lastPurchases.sql b/db/routines/vn/views/lastPurchases.sql
index 3099acd00..3dcaf8c1d 100644
--- a/db/routines/vn/views/lastPurchases.sql
+++ b/db/routines/vn/views/lastPurchases.sql
@@ -31,5 +31,5 @@ FROM (
LEFT JOIN `edi`.`ekt` `ek` ON(`ek`.`id` = `b`.`ektFk`)
)
WHERE `tr`.`landed` BETWEEN `util`.`yesterday`() AND `util`.`tomorrow`()
- AND `e`.`isRaid` = 0
+ AND NOT `tr`.`isRaid`
AND `b`.`stickers` > 0
diff --git a/db/routines/vn/views/workerWithoutTractor.sql b/db/routines/vn/views/workerWithoutTractor.sql
index 205c66599..15b62d4a9 100644
--- a/db/routines/vn/views/workerWithoutTractor.sql
+++ b/db/routines/vn/views/workerWithoutTractor.sql
@@ -10,11 +10,10 @@ FROM (
`vn`.`collection` `c`
JOIN `vn`.`client` `cl` ON(`cl`.`id` = `c`.`workerFk`)
)
- LEFT JOIN `vn`.`machineWorker` `mw` ON(
- `mw`.`workerFk` = `c`.`workerFk`
- AND `mw`.`inTimed` > `util`.`VN_CURDATE`()
+ JOIN `vn`.`operator` `o` ON(
+ `o`.`workerFk` = `c`.`workerFk`
)
)
WHERE `c`.`created` > `util`.`VN_CURDATE`()
- AND `mw`.`workerFk` IS NULL
+ AND `o`.`machineFk` IS NULL
GROUP BY `c`.`workerFk`
diff --git a/db/routines/vn2008/views/Clientes.sql b/db/routines/vn2008/views/Clientes.sql
index 153d875bc..9f8ef712e 100644
--- a/db/routines/vn2008/views/Clientes.sql
+++ b/db/routines/vn2008/views/Clientes.sql
@@ -22,7 +22,6 @@ AS SELECT `c`.`id` AS `id_cliente`,
`c`.`credit` AS `credito`,
`c`.`countryFk` AS `Id_Pais`,
`c`.`isActive` AS `activo`,
- `c`.`gestdocFk` AS `gestdoc_id`,
`c`.`quality` AS `calidad`,
`c`.`payMethodFk` AS `pay_met_id`,
`c`.`created` AS `created`,
diff --git a/db/routines/vn2008/views/Compres_mark.sql b/db/routines/vn2008/views/Compres_mark.sql
deleted file mode 100644
index 7138c4e4c..000000000
--- a/db/routines/vn2008/views/Compres_mark.sql
+++ /dev/null
@@ -1,8 +0,0 @@
-CREATE OR REPLACE DEFINER=`root`@`localhost`
- SQL SECURITY DEFINER
- VIEW `vn2008`.`Compres_mark`
-AS SELECT `bm`.`id` AS `Id_Compra`,
- `bm`.`comment` AS `comment`,
- `bm`.`mark` AS `mark`,
- `bm`.`odbcDate` AS `odbc_date`
-FROM `vn`.`buyMark` `bm`
diff --git a/db/routines/vn2008/views/Cubos.sql b/db/routines/vn2008/views/Cubos.sql
index 4ece9c435..1b23af4fc 100644
--- a/db/routines/vn2008/views/Cubos.sql
+++ b/db/routines/vn2008/views/Cubos.sql
@@ -17,5 +17,6 @@ AS SELECT `p`.`id` AS `Id_Cubo`,
`p`.`upload` AS `Suben`,
`p`.`base` AS `Base`,
`p`.`isBox` AS `box`,
- `p`.`returnCost` AS `costeRetorno`
+ `p`.`returnCost` AS `costeRetorno`,
+ `p`.`isActive` AS `isActive`
FROM `vn`.`packaging` `p`
diff --git a/db/routines/vn2008/views/Entradas.sql b/db/routines/vn2008/views/Entradas.sql
index 63fbaa728..78b73bb24 100644
--- a/db/routines/vn2008/views/Entradas.sql
+++ b/db/routines/vn2008/views/Entradas.sql
@@ -8,7 +8,6 @@ AS SELECT `e`.`id` AS `Id_Entrada`,
`e`.`isExcludedFromAvailable` AS `Inventario`,
`e`.`isConfirmed` AS `Confirmada`,
`e`.`isOrdered` AS `Pedida`,
- `e`.`isRaid` AS `Redada`,
`e`.`commission` AS `comision`,
`e`.`created` AS `odbc_date`,
`e`.`evaNotes` AS `Notas_Eva`,
diff --git a/db/routines/vn2008/views/Entradas_Auto.sql b/db/routines/vn2008/views/Entradas_Auto.sql
deleted file mode 100644
index 5d1266965..000000000
--- a/db/routines/vn2008/views/Entradas_Auto.sql
+++ /dev/null
@@ -1,5 +0,0 @@
-CREATE OR REPLACE DEFINER=`root`@`localhost`
- SQL SECURITY DEFINER
- VIEW `vn2008`.`Entradas_Auto`
-AS SELECT `ev`.`entryFk` AS `Id_Entrada`
-FROM `vn`.`entryVirtual` `ev`
diff --git a/db/routines/vn2008/views/Rutas.sql b/db/routines/vn2008/views/Rutas.sql
index 78b3bb471..c8ade24e9 100644
--- a/db/routines/vn2008/views/Rutas.sql
+++ b/db/routines/vn2008/views/Rutas.sql
@@ -3,7 +3,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost`
VIEW `vn2008`.`Rutas`
AS SELECT `r`.`id` AS `Id_Ruta`,
`r`.`workerFk` AS `Id_Trabajador`,
- `r`.`created` AS `Fecha`,
+ `r`.`dated` AS `Fecha`,
`r`.`vehicleFk` AS `Id_Vehiculo`,
`r`.`agencyModeFk` AS `Id_Agencia`,
`r`.`time` AS `Hora`,
diff --git a/db/routines/vn2008/views/entrySource.sql b/db/routines/vn2008/views/entrySource.sql
index 3a8df41bf..732603617 100644
--- a/db/routines/vn2008/views/entrySource.sql
+++ b/db/routines/vn2008/views/entrySource.sql
@@ -8,7 +8,8 @@ AS SELECT `e`.`gestDocFk` AS `gestdoc_id`,
`e`.`isExcludedFromAvailable` AS `Inventario`,
`e`.`isConfirmed` AS `Confirmada`,
`e`.`isOrdered` AS `Pedida`,
- `e`.`isRaid` AS `Redada`,
+ `tr`.`isRaid` AS `isRaid`,
+ `tr`.`daysInForward` AS `daysInForward`,
`e`.`evaNotes` AS `notas`,
`e`.`supplierFk` AS `Id_Proveedor`,
`tr`.`shipped` AS `shipment`,
diff --git a/db/routines/vn2008/views/travel.sql b/db/routines/vn2008/views/travel.sql
index b55dbf9b6..38dfd40ea 100644
--- a/db/routines/vn2008/views/travel.sql
+++ b/db/routines/vn2008/views/travel.sql
@@ -17,5 +17,7 @@ AS SELECT `t`.`id` AS `id`,
`t`.`cargoSupplierFk` AS `cargoSupplierFk`,
`t`.`totalEntries` AS `totalEntries`,
`t`.`appointment` AS `appointment`,
- `t`.`awbFk` AS `awbFk`
+ `t`.`awbFk` AS `awbFk`,
+ `t`.`isRaid` AS `isRaid`,
+ `t`.`daysInForward` AS `daysInForward`
FROM `vn`.`travel` `t`
diff --git a/db/routines/vn2008/views/v_compres.sql b/db/routines/vn2008/views/v_compres.sql
index 8bd6a4a64..633feb471 100644
--- a/db/routines/vn2008/views/v_compres.sql
+++ b/db/routines/vn2008/views/v_compres.sql
@@ -28,7 +28,6 @@ AS SELECT `TP`.`Id_Tipo` AS `Familia`,
`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`,
@@ -85,6 +84,6 @@ FROM (
)
JOIN `vn2008`.`Cubos` `cb` ON(`cb`.`Id_Cubo` = `C`.`Id_Cubo`)
)
-WHERE `W_IN`.`isFeedStock` = 0
- AND `E`.`Inventario` = 0
- AND `E`.`Redada` = 0
+WHERE NOT `W_IN`.`isFeedStock`
+ AND NOT `E`.`Inventario`
+ AND NOT `TR`.`isRaid`
diff --git a/db/versions/11198-blackPhormium/00-firstScript.sql b/db/versions/11198-blackPhormium/00-firstScript.sql
new file mode 100644
index 000000000..6c181ed21
--- /dev/null
+++ b/db/versions/11198-blackPhormium/00-firstScript.sql
@@ -0,0 +1,7 @@
+UPDATE vn.itemShelving
+ SET isChecked = TRUE
+ WHERE isChecked;
+
+UPDATE vn.itemShelving
+ SET isChecked = FALSE
+ WHERE NOT isChecked;
diff --git a/db/versions/11230-brownEucalyptus/00-addClientObservationType.sql b/db/versions/11230-brownEucalyptus/00-addClientObservationType.sql
new file mode 100644
index 000000000..f69e20611
--- /dev/null
+++ b/db/versions/11230-brownEucalyptus/00-addClientObservationType.sql
@@ -0,0 +1,3 @@
+ALTER TABLE vn.clientObservation DROP COLUMN IF EXISTS observationTypeFk;
+ALTER TABLE vn.clientObservation ADD COLUMN IF NOT EXISTS observationTypeFk TINYINT(3) UNSIGNED NULL;
+ALTER TABLE vn.clientObservation ADD CONSTRAINT clientObservationTypeFk FOREIGN KEY IF NOT EXISTS (observationTypeFk) REFERENCES vn.observationType(id);
diff --git a/db/versions/11230-brownEucalyptus/01-addNewObservation.vn.sql b/db/versions/11230-brownEucalyptus/01-addNewObservation.vn.sql
new file mode 100644
index 000000000..983419111
--- /dev/null
+++ b/db/versions/11230-brownEucalyptus/01-addNewObservation.vn.sql
@@ -0,0 +1,3 @@
+INSERT IGNORE INTO vn.observationType
+ SET description = 'Finance',
+ code = 'finance';
\ No newline at end of file
diff --git a/db/versions/11242-whiteAnthurium/00-firstScript.sql b/db/versions/11242-whiteAnthurium/00-firstScript.sql
new file mode 100644
index 000000000..43dccf374
--- /dev/null
+++ b/db/versions/11242-whiteAnthurium/00-firstScript.sql
@@ -0,0 +1,3 @@
+DELETE FROM salix.ACL
+ WHERE model = 'WorkerLog'
+ AND property = '*';
\ No newline at end of file
diff --git a/db/versions/11251-navyChrysanthemum/00-firstScript.sql b/db/versions/11251-navyChrysanthemum/00-firstScript.sql
new file mode 100644
index 000000000..7c2c69839
--- /dev/null
+++ b/db/versions/11251-navyChrysanthemum/00-firstScript.sql
@@ -0,0 +1,2 @@
+-- Debido a que tardaba mucho en la subida a master, se ha creado una nueva versión para que el proceso no se vea afectado y se ejecute por la noche.
+-- Se crea de nuevo en la versión 11344-grayBamboo
diff --git a/db/versions/11272-azureLilium/00-firstScript.sql b/db/versions/11272-azureLilium/00-firstScript.sql
new file mode 100644
index 000000000..0194ece18
--- /dev/null
+++ b/db/versions/11272-azureLilium/00-firstScript.sql
@@ -0,0 +1,4 @@
+-- Place your SQL code here
+RENAME TABLE vn.stockBuyed TO vn.stockBuyed__;
+ALTER TABLE vn.stockBuyed__
+COMMENT='@deprecated 2024-10-01 rename and refactor to stockBought';
diff --git a/db/versions/11273-goldenDendro/00-firstScript.sql b/db/versions/11273-goldenDendro/00-firstScript.sql
new file mode 100644
index 000000000..2fc6809e5
--- /dev/null
+++ b/db/versions/11273-goldenDendro/00-firstScript.sql
@@ -0,0 +1,22 @@
+CREATE TABLE IF NOT EXISTS `vn`.`itemStateTag` (
+ `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
+ `name` varchar(50) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `name_UNIQUE` (`name`)
+) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT
+ CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+
+INSERT IGNORE INTO `vn`.`itemStateTag` (`name`) VALUES ('Artificial');
+INSERT IGNORE INTO `vn`.`itemStateTag` (`name`) VALUES ('Inactivo');
+INSERT IGNORE INTO `vn`.`itemStateTag` (`name`) VALUES ('Preservado');
+INSERT IGNORE INTO `vn`.`itemStateTag` (`name`) VALUES ('Seco');
+INSERT IGNORE INTO `vn`.`itemStateTag` (`name`) VALUES ('Seco y preservado');
+INSERT IGNORE INTO `vn`.`itemStateTag` (`name`) VALUES ('Estabilizada');
+INSERT IGNORE INTO `vn`.`itemStateTag` (`name`) VALUES ('Natural y seco');
+INSERT IGNORE INTO `vn`.`itemStateTag` (`name`) VALUES ('Preservado y artificial');
+INSERT IGNORE INTO `vn`.`itemStateTag` (`name`) VALUES ('Usado');
+
+UPDATE vn.tag
+ SET isFree=0,
+ sourceTable='itemStateTag'
+ WHERE name= 'Estado';
diff --git a/db/versions/11274-redGerbera/00-firstScript copy 3.sql b/db/versions/11274-redGerbera/00-firstScript copy 3.sql
deleted file mode 100644
index c1f574379..000000000
--- a/db/versions/11274-redGerbera/00-firstScript copy 3.sql
+++ /dev/null
@@ -1 +0,0 @@
-ALTER TABLE vn.autonomy MODIFY COLUMN isUeeMember tinyint(1) DEFAULT FALSE NOT NULL;
\ No newline at end of file
diff --git a/db/versions/11274-redGerbera/00-firstScript copy.sql b/db/versions/11274-redGerbera/00-firstScript2.sql
similarity index 100%
rename from db/versions/11274-redGerbera/00-firstScript copy.sql
rename to db/versions/11274-redGerbera/00-firstScript2.sql
diff --git a/db/versions/11274-redGerbera/00-firstScript copy 2.sql b/db/versions/11274-redGerbera/00-firstScript3.sql
similarity index 100%
rename from db/versions/11274-redGerbera/00-firstScript copy 2.sql
rename to db/versions/11274-redGerbera/00-firstScript3.sql
diff --git a/db/versions/11274-redGerbera/00-firstScript copy 4.sql b/db/versions/11274-redGerbera/00-firstScript5.sql
similarity index 100%
rename from db/versions/11274-redGerbera/00-firstScript copy 4.sql
rename to db/versions/11274-redGerbera/00-firstScript5.sql
diff --git a/db/versions/11274-redGerbera/00-firstScript copy 5.sql b/db/versions/11274-redGerbera/00-firstScript6.sql
similarity index 100%
rename from db/versions/11274-redGerbera/00-firstScript copy 5.sql
rename to db/versions/11274-redGerbera/00-firstScript6.sql
diff --git a/db/versions/11274-redGerbera/00-firstScript copy 6.sql b/db/versions/11274-redGerbera/00-firstScript7.sql
similarity index 100%
rename from db/versions/11274-redGerbera/00-firstScript copy 6.sql
rename to db/versions/11274-redGerbera/00-firstScript7.sql
diff --git a/db/versions/11277-wheatChico/00-firstScript.sql b/db/versions/11277-wheatChico/00-firstScript.sql
new file mode 100644
index 000000000..c2b5963a4
--- /dev/null
+++ b/db/versions/11277-wheatChico/00-firstScript.sql
@@ -0,0 +1,3 @@
+-- Place your SQL code here
+ALTER TABLE hedera.`order` ADD IF NOT EXISTS rowUpdated DATETIME NULL
+ COMMENT 'Timestamp for last updated record in orderRow table';
diff --git a/db/versions/11278-crimsonEucalyptus/00-firstScript.sql b/db/versions/11278-crimsonEucalyptus/00-firstScript.sql
new file mode 100644
index 000000000..f69f75f1d
--- /dev/null
+++ b/db/versions/11278-crimsonEucalyptus/00-firstScript.sql
@@ -0,0 +1,6 @@
+-- Place your SQL code here
+
+ALTER TABLE vn.priceDelta ADD IF NOT EXISTS zoneGeoFk int(11) NULL;
+
+ALTER TABLE vn.priceDelta ADD CONSTRAINT priceDelta_zoneGeo_FK FOREIGN KEY IF NOT EXISTS (zoneGeoFk)
+REFERENCES vn.zoneGeo (`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
diff --git a/db/versions/11279-turquoiseDendro/00-firstScript.sql b/db/versions/11279-turquoiseDendro/00-firstScript.sql
new file mode 100644
index 000000000..a241e6af2
--- /dev/null
+++ b/db/versions/11279-turquoiseDendro/00-firstScript.sql
@@ -0,0 +1,6 @@
+-- Place your SQL code here
+
+ALTER TABLE vn.priceDelta ADD IF NOT EXISTS zoneGeoFk int(11) NULL;
+
+ALTER TABLE vn.priceDelta ADD CONSTRAINT priceDelta_zoneGeo_FK FOREIGN KEY IF NOT EXISTS (zoneGeoFk)
+REFERENCES vn.zoneGeo (`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
\ No newline at end of file
diff --git a/db/versions/11280-goldenCamellia/00-firstScript.sql b/db/versions/11280-goldenCamellia/00-firstScript.sql
new file mode 100644
index 000000000..fd55760c1
--- /dev/null
+++ b/db/versions/11280-goldenCamellia/00-firstScript.sql
@@ -0,0 +1,24 @@
+ALTER TABLE `vn`.`packaging`
+ ADD COLUMN IF NOT EXISTS `isActive` TINYINT(1) DEFAULT 1;
+
+UPDATE vn.packaging
+ SET isActive = FALSE
+ WHERE id IN('06x04x06','07x04x03','1000','100SM','1031','104','105','1060','10x04x06','10x04x07','1100','118','119','1200','129','1300',
+ '134','146','147','148','158','159','17x01x02','17X01X03','17x01x04','17x01x05','18X01X04','198','199',
+ '20P','20x01x03','246','273','278','279','280','290','359','37247','382','40P','453','463','464','465','466',
+ '467','469','471','473','494','508','509','511','512','514','515','516','518','519-50B','575','598-3x6','604','605','606',
+ '607','609','647','67515','676','680','682','685','687','688','691','692','693','694','695','730','751','7808','790','7910',
+ '7920','79450','7950','7952','7960','7976','7982','7986','7988',
+ '7993','8000','8046','8049','8053','8057','8058','8065','8076','8085','8086','8088',
+ '8091','8095','8096','8097','8101','8106','8108','8110','8112','8124','8134','8140','8141','8143','8145','8149','8150',
+ '8170','8174','8192','8200','8210','8249','8270','8275','8288','8300','8350','8375','8399','8400','8420','845','847','8480','8500',
+ '855','858','8600','862','869','871','872','8720','878','879','880','8800','882','885','910','911','912','914','916','917','918','919',
+ '920','921','922','923','924','925','926','927','930','9300','932','934','935','936','938','942','948','9600','980','984','9920',
+ 'B20x16','B43x13','Bande Rota','bb3','Bcesta','BcestaOVAL','BcestaRED','Bcirios','BciriosG','BjarronBLN','BjarronNGR',
+ 'Btazon','Bvelas','cactus200','Caja040','CajaTGLF','CC Alza Pl','CC_falso',
+ 'EB-RSMINA','EMB 1_4','EMB 2_5','espuma','FB-BENCH','granel','Grenex','guzma1200','guzma1400','guzma330','guzma400','guzma650','guzma900','HB-ALEX',
+ 'HB-APOSENT','HB-MAGIC','HB-NATUF','HB-RSMINA','HB-TES-RSR','HB068','HB117','HB2-CIRCA','JB-AROMA','jumboX3','kalan330','kalan400',
+ 'kalan577','kalan900','L12','L120','L14','L2-120','L200','L3-120','L4-120','L44','L6','L6-180','L8','L8-200','MB-BENCH','MBOLA','mc_11',
+ 'mc_13','Msp','NO VALIDO','NO-002','PANIC','PBLG','PISOCC/3','PISOCC/4','PISOCC/5','PISOCC/6',
+ 'procona','QB-CARDENA','QB-PANDERO','QB-TES-RSR','QB7-TOSCA','QB9-TOSCA','RB-BENCH','SemiEuroPa','spolette','t_flori11','T26x23',
+ 'T26x25','T27x24','T27x30','T28x26','T30x24','T33x30','THA50','ti_13','Tumbado','UB-BENCH')
\ No newline at end of file
diff --git a/db/versions/11281-purpleCyca/00-firstScript.sql b/db/versions/11281-purpleCyca/00-firstScript.sql
new file mode 100644
index 000000000..eadba5ae1
--- /dev/null
+++ b/db/versions/11281-purpleCyca/00-firstScript.sql
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS vn.buyMark;
diff --git a/db/versions/11283-redAspidistra/00-firstScript.sql b/db/versions/11283-redAspidistra/00-firstScript.sql
new file mode 100644
index 000000000..a88091297
--- /dev/null
+++ b/db/versions/11283-redAspidistra/00-firstScript.sql
@@ -0,0 +1,3 @@
+ALTER TABLE vn.itemShelving DROP FOREIGN KEY itemShelving_fk2;
+ALTER TABLE vn.itemShelving ADD CONSTRAINT itemShelving_fk2
+ FOREIGN KEY (shelvingFk) REFERENCES vn.shelving(code) ON DELETE RESTRICT ON UPDATE CASCADE;
diff --git a/db/versions/11284-turquoiseLaurel/00-firstScript.sql b/db/versions/11284-turquoiseLaurel/00-firstScript.sql
new file mode 100644
index 000000000..34762faf6
--- /dev/null
+++ b/db/versions/11284-turquoiseLaurel/00-firstScript.sql
@@ -0,0 +1,2 @@
+-- Place your SQL code here
+ALTER TABLE vn.itemShelving ADD IF NOT EXISTS isMoving BOOL DEFAULT FALSE NOT NULL COMMENT 'Indica que se ha marcado este registro para transferirlo a otro sector';
diff --git a/db/versions/11285-orangeErica/00-firstScript.sql b/db/versions/11285-orangeErica/00-firstScript.sql
new file mode 100644
index 000000000..c13571f3a
--- /dev/null
+++ b/db/versions/11285-orangeErica/00-firstScript.sql
@@ -0,0 +1,3 @@
+-- Place your SQL code here
+ALTER TABLE vn.itemShelving DROP COLUMN IF EXISTS isMoving;
+ALTER TABLE vn.itemShelving ADD IF NOT EXISTS movingState ENUM('selected','printed') NULL;
diff --git a/db/versions/11287-azureRaphis/00-firstScript.sql b/db/versions/11287-azureRaphis/00-firstScript.sql
new file mode 100644
index 000000000..77d60eb40
--- /dev/null
+++ b/db/versions/11287-azureRaphis/00-firstScript.sql
@@ -0,0 +1,3 @@
+-- Place your SQL code here
+ALTER TABLE hedera.`order` ADD IF NOT EXISTS rowUpdated DATETIME NULL
+ COMMENT 'Timestamp for last updated record in orderRow table';
\ No newline at end of file
diff --git a/db/versions/11288-purpleFern/00-firstScript.sql b/db/versions/11288-purpleFern/00-firstScript.sql
new file mode 100644
index 000000000..77d60eb40
--- /dev/null
+++ b/db/versions/11288-purpleFern/00-firstScript.sql
@@ -0,0 +1,3 @@
+-- Place your SQL code here
+ALTER TABLE hedera.`order` ADD IF NOT EXISTS rowUpdated DATETIME NULL
+ COMMENT 'Timestamp for last updated record in orderRow table';
\ No newline at end of file
diff --git a/db/versions/11289-azureAralia/00-firstScript.sql b/db/versions/11289-azureAralia/00-firstScript.sql
new file mode 100644
index 000000000..ab091f53f
--- /dev/null
+++ b/db/versions/11289-azureAralia/00-firstScript.sql
@@ -0,0 +1,2 @@
+
+ALTER TABLE vn.sector ADD isOnReservationMode tinyint(1) DEFAULT FALSE NULL;
diff --git a/db/versions/11290-blackOrchid/00-firstScript.sql b/db/versions/11290-blackOrchid/00-firstScript.sql
new file mode 100644
index 000000000..fe568ed6e
--- /dev/null
+++ b/db/versions/11290-blackOrchid/00-firstScript.sql
@@ -0,0 +1,6 @@
+ALTER TABLE `vn`.`operator`
+ADD COLUMN `machineFk` int(11) DEFAULT NULL,
+ADD CONSTRAINT `operator_machine_FK` FOREIGN KEY (`machineFk`) REFERENCES `vn`.`machine` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;
+
+INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId)
+ VALUES ('Machine','*','*','ALLOW','ROLE','productionBoss');
diff --git a/db/versions/11291-purpleChico/00-firstScript.sql b/db/versions/11291-purpleChico/00-firstScript.sql
new file mode 100644
index 000000000..e60b90376
--- /dev/null
+++ b/db/versions/11291-purpleChico/00-firstScript.sql
@@ -0,0 +1,4 @@
+ALTER TABLE vn.docuwareConfig ADD IF NOT EXISTS username varchar(100) NULL;
+ALTER TABLE vn.docuwareConfig ADD IF NOT EXISTS password varchar(100) NULL;
+ALTER TABLE vn.docuwareConfig ADD IF NOT EXISTS token text NULL;
+ALTER TABLE vn.docuwareConfig ADD IF NOT EXISTS expired int(11) NULL;
diff --git a/db/versions/11294-azureFern/00-firstScript.sql b/db/versions/11294-azureFern/00-firstScript.sql
new file mode 100644
index 000000000..2d6ed3a5b
--- /dev/null
+++ b/db/versions/11294-azureFern/00-firstScript.sql
@@ -0,0 +1,3 @@
+-- Place your SQL code here
+ALTER TABLE vn.itemShelving DROP COLUMN IF EXISTS isMoving;
+ALTER TABLE vn.itemShelving ADD IF NOT EXISTS movingState ENUM('selected','printed') NULL;
\ No newline at end of file
diff --git a/db/versions/11295-brownLaurel/00-firstScript.sql b/db/versions/11295-brownLaurel/00-firstScript.sql
new file mode 100644
index 000000000..2d6ed3a5b
--- /dev/null
+++ b/db/versions/11295-brownLaurel/00-firstScript.sql
@@ -0,0 +1,3 @@
+-- Place your SQL code here
+ALTER TABLE vn.itemShelving DROP COLUMN IF EXISTS isMoving;
+ALTER TABLE vn.itemShelving ADD IF NOT EXISTS movingState ENUM('selected','printed') NULL;
\ No newline at end of file
diff --git a/db/versions/11297-graySalal/00-firstScript.sql b/db/versions/11297-graySalal/00-firstScript.sql
new file mode 100644
index 000000000..4d4711306
--- /dev/null
+++ b/db/versions/11297-graySalal/00-firstScript.sql
@@ -0,0 +1,27 @@
+ALTER TABLE vn.itemType
+ ADD editorFk int(10) unsigned DEFAULT NULL NULL,
+ ADD CONSTRAINT itemType_user_FK FOREIGN KEY (editorFk) REFERENCES account.`user`(id);
+
+CREATE TABLE `vn`.`itemTypeLog` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `originFk` int(11) DEFAULT NULL,
+ `userFk` int(10) unsigned DEFAULT NULL,
+ `action` set('insert','update','delete') NOT NULL,
+ `creationDate` timestamp NULL DEFAULT current_timestamp(),
+ `description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
+ `changedModel` enum('ItemType') NOT NULL DEFAULT 'ItemType',
+ `oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
+ `newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
+ `changedModelId` int(11) NOT NULL,
+ `changedModelValue` varchar(45) DEFAULT NULL,
+ `summaryId` varchar(30) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `itemTypeLogUserFk_idx` (`userFk`),
+ KEY `itemTypeLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
+ KEY `itemTypeLog_originFk` (`originFk`,`creationDate`),
+ KEY `itemTypeLog_creationDate_IDX` (`creationDate` DESC) USING BTREE,
+ CONSTRAINT `itemTypeLogUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
+
+INSERT IGNORE INTO salix.ACL (model,property,principalId)
+ VALUES ('ItemTypeLog','find','employee');
diff --git a/db/versions/11297-graySalal/01-firstScript.sql b/db/versions/11297-graySalal/01-firstScript.sql
new file mode 100644
index 000000000..78ce1a540
--- /dev/null
+++ b/db/versions/11297-graySalal/01-firstScript.sql
@@ -0,0 +1,3 @@
+ALTER TABLE vn.itemType
+ ADD CONSTRAINT itemType_itemPackingType_FK FOREIGN KEY (itemPackingTypeFk)
+ REFERENCES vn.itemPackingType(code) ON DELETE RESTRICT ON UPDATE CASCADE;
diff --git a/db/versions/11298-wheatIvy/00-closure.sql b/db/versions/11298-wheatIvy/00-closure.sql
new file mode 100644
index 000000000..7b33939cf
--- /dev/null
+++ b/db/versions/11298-wheatIvy/00-closure.sql
@@ -0,0 +1,3 @@
+ALTER TABLE `vn`.`ticketConfig`
+ADD COLUMN `closureDaysAgo` int(11) NOT NULL DEFAULT 2 COMMENT 'Number of days to look back for ticket closure',
+ADD CONSTRAINT `closureDaysAgo_check` CHECK (`closureDaysAgo` > 0);
diff --git a/db/versions/11300-limeMedeola/00-firstScript.sql b/db/versions/11300-limeMedeola/00-firstScript.sql
new file mode 100644
index 000000000..28b033b4a
--- /dev/null
+++ b/db/versions/11300-limeMedeola/00-firstScript.sql
@@ -0,0 +1,137 @@
+CREATE TABLE IF NOT EXISTS `vn`.`itemFarmingTag` (
+ `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
+ `name` varchar(50) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `name_UNIQUE` (`name`)
+) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT
+ CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+
+INSERT IGNORE INTO `vn`.`itemFarmingTag` (`name`) VALUES ('Enraizado');
+
+UPDATE vn.tag
+ SET isFree=0,
+ sourceTable='itemFarmingTag'
+ WHERE name= 'cultivo';
+
+CREATE TABLE IF NOT EXISTS `vn`.`itemWrappingTag` (
+ `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
+ `name` varchar(50) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `name_UNIQUE` (`name`)
+) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT
+ CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+
+INSERT IGNORE INTO `vn`.`itemWrappingTag` (`name`) VALUES ('Bolsa');
+INSERT IGNORE INTO `vn`.`itemWrappingTag` (`name`) VALUES ('Caja cartón');
+INSERT IGNORE INTO `vn`.`itemWrappingTag` (`name`) VALUES ('Caja decorativa');
+INSERT IGNORE INTO `vn`.`itemWrappingTag` (`name`) VALUES ('Celofán');
+INSERT IGNORE INTO `vn`.`itemWrappingTag` (`name`) VALUES ('Papel kraft');
+INSERT IGNORE INTO `vn`.`itemWrappingTag` (`name`) VALUES ('Plástico');
+INSERT IGNORE INTO `vn`.`itemWrappingTag` (`name`) VALUES ('Variable');
+
+UPDATE vn.tag
+ SET isFree=0,
+ sourceTable='itemWrappingTag'
+ WHERE name= 'Envoltorio';
+
+CREATE TABLE IF NOT EXISTS `vn`.`itemLanguageTag` (
+ `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
+ `name` varchar(50) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `name_UNIQUE` (`name`)
+) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT
+ CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+
+INSERT IGNORE INTO `vn`.`itemLanguageTag` (`name`) VALUES ('Castellano');
+INSERT IGNORE INTO `vn`.`itemLanguageTag` (`name`) VALUES ('Catalán');
+INSERT IGNORE INTO `vn`.`itemLanguageTag` (`name`) VALUES ('Euskera');
+INSERT IGNORE INTO `vn`.`itemLanguageTag` (`name`) VALUES ('Francés');
+INSERT IGNORE INTO `vn`.`itemLanguageTag` (`name`) VALUES ('Gallego');
+INSERT IGNORE INTO `vn`.`itemLanguageTag` (`name`) VALUES ('Inglés');
+INSERT IGNORE INTO `vn`.`itemLanguageTag` (`name`) VALUES ('Portugués');
+
+UPDATE vn.tag
+ SET isFree=0,
+ sourceTable='itemLanguageTag'
+ WHERE name= 'Idioma';
+
+CREATE TABLE IF NOT EXISTS `vn`.`itemStemTag` (
+ `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
+ `name` varchar(50) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `name_UNIQUE` (`name`)
+) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT
+ CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+
+INSERT IGNORE INTO `vn`.`itemStemTag` (`name`) VALUES ('Natural');
+INSERT IGNORE INTO `vn`.`itemStemTag` (`name`) VALUES ('Seminatural');
+INSERT IGNORE INTO `vn`.`itemStemTag` (`name`) VALUES ('Sintético');
+
+UPDATE vn.tag
+ SET isFree=0,
+ sourceTable='itemStemTag'
+ WHERE name= 'Tronco';
+
+
+CREATE TABLE IF NOT EXISTS `vn`.`itemBreederTag` (
+ `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
+ `name` varchar(50) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `name_UNIQUE` (`name`)
+) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT
+ CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+
+INSERT IGNORE INTO `vn`.`itemBreederTag` (`name`) VALUES ('David Austin');
+
+UPDATE vn.tag
+ SET isFree=0,
+ sourceTable='itemBreederTag'
+ WHERE name= 'Obtentor';
+
+CREATE TABLE IF NOT EXISTS `vn`.`itemBaseTag` (
+ `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
+ `name` varchar(50) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `name_UNIQUE` (`name`)
+) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT
+ CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+
+INSERT IGNORE INTO `vn`.`itemBaseTag` (`name`) VALUES ('Biodegradable');
+INSERT IGNORE INTO `vn`.`itemBaseTag` (`name`) VALUES ('Caballete');
+INSERT IGNORE INTO `vn`.`itemBaseTag` (`name`) VALUES ('Cerámica');
+INSERT IGNORE INTO `vn`.`itemBaseTag` (`name`) VALUES ('Cristal');
+INSERT IGNORE INTO `vn`.`itemBaseTag` (`name`) VALUES ('Plástico por inyección');
+INSERT IGNORE INTO `vn`.`itemBaseTag` (`name`) VALUES ('Madera');
+INSERT IGNORE INTO `vn`.`itemBaseTag` (`name`) VALUES ('Plástico');
+INSERT IGNORE INTO `vn`.`itemBaseTag` (`name`) VALUES ('Rígido');
+INSERT IGNORE INTO `vn`.`itemBaseTag` (`name`) VALUES ('Ruedas');
+INSERT IGNORE INTO `vn`.`itemBaseTag` (`name`) VALUES ('Sin soporte rígido');
+
+UPDATE vn.tag
+ SET isFree=0,
+ sourceTable='itemBaseTag'
+ WHERE name= 'Soporte';
+
+CREATE TABLE IF NOT EXISTS `vn`.`itemVatRateTag` (
+ `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
+ `name` varchar(50) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `name_UNIQUE` (`name`)
+) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT
+ CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+
+INSERT IGNORE INTO `vn`.`itemVatRateTag` (`name`) VALUES ('General');
+INSERT IGNORE INTO `vn`.`itemVatRateTag` (`name`) VALUES ('Reducido');
+
+UPDATE vn.tag
+ SET isFree=0,
+ sourceTable='itemVatRateTag'
+ WHERE name= 'Tipo de IVA';
+
+GRANT SELECT, UPDATE, INSERT, DELETE ON TABLE vn.itemFarmingTag TO logisticAssist;
+GRANT SELECT, UPDATE, INSERT, DELETE ON TABLE vn.itemWrappingTag TO logisticAssist;
+GRANT SELECT, UPDATE, INSERT, DELETE ON TABLE vn.itemLanguageTag TO logisticAssist;
+GRANT SELECT, UPDATE, INSERT, DELETE ON TABLE vn.itemStemTag TO logisticAssist;
+GRANT SELECT, UPDATE, INSERT, DELETE ON TABLE vn.itemWrappingTag TO logisticAssist;
+GRANT SELECT, UPDATE, INSERT, DELETE ON TABLE vn.itemBaseTag TO logisticAssist;
+GRANT SELECT, UPDATE, INSERT, DELETE ON TABLE vn.itemBreederTag TO logisticAssist;
\ No newline at end of file
diff --git a/db/versions/11302-limeTulip/00-firstScript.sql b/db/versions/11302-limeTulip/00-firstScript.sql
new file mode 100644
index 000000000..7bda31b64
--- /dev/null
+++ b/db/versions/11302-limeTulip/00-firstScript.sql
@@ -0,0 +1,13 @@
+
+UPDATE `vn`.`client` c
+ JOIN `vn`.`country` co ON co.id=c.countryFk
+SET c.hasDailyInvoice = co.hasDailyInvoice
+WHERE co.hasDailyInvoice IS NOT NULL
+ AND c.hasDailyInvoice = FALSE;
+
+UPDATE `vn`.`client` c
+ JOIN `vn`.`province` p ON p.id=c.provinceFk
+ JOIN `vn`.`autonomy` a ON a.id = p.autonomyFk
+SET c.hasDailyInvoice = a.hasDailyInvoice
+WHERE a.hasDailyInvoice IS NOT NULL
+ AND c.hasDailyInvoice = FALSE;
diff --git a/db/versions/11308-redCymbidium/00-firstScript.sql b/db/versions/11308-redCymbidium/00-firstScript.sql
new file mode 100644
index 000000000..fe76cb600
--- /dev/null
+++ b/db/versions/11308-redCymbidium/00-firstScript.sql
@@ -0,0 +1,25 @@
+CREATE TABLE IF NOT EXISTS `vn`.`itemCampaign` (
+ `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
+ dated date NOT NULL,
+ itemFk int(11) NOT NULL,
+ quantity decimal(10,2) NOT NULL,
+ total decimal(10,2) NOT NULL,
+ campaign varchar(100) NOT NULL,
+ UNIQUE KEY `itemCampaign_UNIQUE` (`dated`,`itemFk`),
+ CONSTRAINT itemCampaign_item_FK FOREIGN KEY (itemFk) REFERENCES vn.item(id) ON DELETE RESTRICT ON UPDATE CASCADE
+)
+ENGINE=InnoDB
+DEFAULT CHARSET=utf8mb3
+COLLATE=utf8mb3_unicode_ci
+COMMENT='Tallos confirmados por día en los días de más producción de una campaña. La tabla está pensada para que sea una foto.';
+
+ALTER TABLE vn.campaign
+ ADD previousDays int(10) unsigned DEFAULT 30 NOT NULL COMMENT 'Días previos para calcular e insertar en la tabla itemCampaign';
+
+UPDATE vn.campaign
+ SET previousDays = 90
+ WHERE code = 'allSaints';
+
+UPDATE vn.campaign
+ SET previousDays = 60
+ WHERE code IN ('valentinesDay', 'mothersDay');
diff --git a/db/versions/11311-tealFern/00-firstScript.sql b/db/versions/11311-tealFern/00-firstScript.sql
new file mode 100644
index 000000000..909747f3c
--- /dev/null
+++ b/db/versions/11311-tealFern/00-firstScript.sql
@@ -0,0 +1 @@
+ALTER TABLE vn.client CHANGE gestdocFk gestdocFk__ int(11) DEFAULT NULL NULL COMMENT '@deprecated 2024-10-17';
\ No newline at end of file
diff --git a/db/versions/11312-navyAralia/00-firstScript.sql b/db/versions/11312-navyAralia/00-firstScript.sql
new file mode 100644
index 000000000..452b1feed
--- /dev/null
+++ b/db/versions/11312-navyAralia/00-firstScript.sql
@@ -0,0 +1,23 @@
+ALTER TABLE vn.workerRelatives DROP FOREIGN KEY workerRelatives_disabilityGradeFk;
+ALTER TABLE vn.workerRelatives DROP FOREIGN KEY workerRelatives_workerFk;
+
+INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId)
+ VALUES
+ ('WorkerRelative','updateAttributes','*','ALLOW','ROLE','hr'),
+ ('WorkerRelative','crud','WRITE','ALLOW','ROLE','hr'),
+ ('WorkerRelative','findById','*','ALLOW','ROLE','hr'),
+ ('WorkerRelative','find','*','ALLOW','ROLE','hr'),
+ ('WorkerRelative','upsert','*','ALLOW','ROLE','hr'),
+ ('WorkerRelative','filter','*','ALLOW','ROLE','hr'),
+ ('WorkerIrpf','updateAttributes','*','ALLOW','ROLE','hr'),
+ ('WorkerIrpf','crud','*','ALLOW','ROLE','hr'),
+ ('WorkerIrpf','findById','*','ALLOW','ROLE','hr'),
+ ('WorkerIrpf','find','*','ALLOW','ROLE','hr'),
+ ('WorkerIrpf','upsert','*','ALLOW','ROLE','hr'),
+ ('WorkerIrpf','filter','*','ALLOW','ROLE','hr'),
+ ('DisabilityGrade','updateAttributes','*','ALLOW','ROLE','hr'),
+ ('DisabilityGrade','crud','*','ALLOW','ROLE','hr'),
+ ('DisabilityGrade','findById','*','ALLOW','ROLE','hr'),
+ ('DisabilityGrade','find','*','ALLOW','ROLE','hr'),
+ ('DisabilityGrade','upsert','*','ALLOW','ROLE','hr');
+
diff --git a/db/versions/11314-redTulip/00-restrictedAsterisk.sql b/db/versions/11314-redTulip/00-restrictedAsterisk.sql
new file mode 100644
index 000000000..20f1b4380
--- /dev/null
+++ b/db/versions/11314-redTulip/00-restrictedAsterisk.sql
@@ -0,0 +1,3 @@
+DELETE FROM `salix`.`ACL`
+WHERE `model` = 'Worker'
+ AND `property` IN ('find', 'findById', 'findOne');
diff --git a/db/versions/11315-grayCamellia/00-firstScript.sql b/db/versions/11315-grayCamellia/00-firstScript.sql
new file mode 100644
index 000000000..60eea0e01
--- /dev/null
+++ b/db/versions/11315-grayCamellia/00-firstScript.sql
@@ -0,0 +1,3 @@
+DELETE FROM salix.ACL
+ WHERE property = 'labelPdf'
+ AND model = 'Item';
diff --git a/db/versions/11316-chocolateErica/00-firstScript.sql b/db/versions/11316-chocolateErica/00-firstScript.sql
new file mode 100644
index 000000000..9f2f15bdd
--- /dev/null
+++ b/db/versions/11316-chocolateErica/00-firstScript.sql
@@ -0,0 +1,7 @@
+ALTER TABLE vn.travel ADD IF NOT EXISTS daysInForward INT UNSIGNED DEFAULT 0 NOT NULL
+ COMMENT 'Indica que sus entradas son redadas: 0 significa que no es un travel de redadas, y un valor distinto a 0 indica el número de días para el landed respecto a hoy';
+
+ALTER TABLE vn.entry CHANGE isRaid isRaid_ tinyint(1) DEFAULT 0 NOT NULL COMMENT '@deprecated 2024-11-05';
+
+RENAME TABLE vn.entryVirtual TO vn.entryVirtual__;
+ALTER TABLE vn.entryVirtual__ COMMENT='@deprecated 2024-11-05';
diff --git a/db/versions/11317-silverCordyline/00-firstScript.sql b/db/versions/11317-silverCordyline/00-firstScript.sql
new file mode 100644
index 000000000..35dffcd64
--- /dev/null
+++ b/db/versions/11317-silverCordyline/00-firstScript.sql
@@ -0,0 +1,9 @@
+
+USE vn;
+RENAME TABLE machineWorker TO machineWorker__;
+ALTER TABLE machineWorker__ COMMENT = '@deprecated 2024-10-23 not used';
+
+RENAME TABLE machineWorkerConfig TO machineWorkerConfig__;
+ALTER TABLE machineWorkerConfig__ COMMENT = '@deprecated 2024-10-23 not used';
+
+DELETE FROM salix.ACL WHERE model = 'MachineWorker';
diff --git a/db/versions/11319-redEucalyptus/00-firstScript.sql b/db/versions/11319-redEucalyptus/00-firstScript.sql
new file mode 100644
index 000000000..62bd64f4a
--- /dev/null
+++ b/db/versions/11319-redEucalyptus/00-firstScript.sql
@@ -0,0 +1,3 @@
+USE vn;
+
+ALTER TABLE vn.expeditionState ADD scanOrder int(11) DEFAULT NULL NULL COMMENT 'Indica la posición al cargar la furgoneta';
diff --git a/db/versions/11320-salmonRose/00-firstScript.sql b/db/versions/11320-salmonRose/00-firstScript.sql
new file mode 100644
index 000000000..cd3431fee
--- /dev/null
+++ b/db/versions/11320-salmonRose/00-firstScript.sql
@@ -0,0 +1,11 @@
+INSERT INTO hedera.message (code, description)
+ VALUES ('orderLinesWithZero','There are empty lines. Please delete them');
+
+INSERT INTO hedera.messageI18n (code, lang, description)
+ VALUES ('orderLinesWithZero','es','Hay líneas vacías. Por favor, elimínelas');
+
+INSERT INTO hedera.messageI18n (code, lang, description)
+ VALUES ('orderLinesWithZero','fr','Il y a des lignes vides. Veuillez les supprimer');
+
+INSERT INTO hedera.messageI18n (code, lang, description)
+ VALUES ('orderLinesWithZero','pt','Existem linhas vazias. Por favor, apague-os');
\ No newline at end of file
diff --git a/db/versions/11321-wheatChrysanthemum/00-firstScript.sql b/db/versions/11321-wheatChrysanthemum/00-firstScript.sql
new file mode 100644
index 000000000..e3ba70e2c
--- /dev/null
+++ b/db/versions/11321-wheatChrysanthemum/00-firstScript.sql
@@ -0,0 +1,3 @@
+INSERT INTO vn.report (name, `method`)
+ VALUES ('LabelItemBarcode','Items/{id}/label-barcode-pdf'),
+ ('LabelItemQr','Items/{id}/label-qr-pdf');
diff --git a/db/versions/11322-azureAspidistra/00-entryAcl.sql b/db/versions/11322-azureAspidistra/00-entryAcl.sql
new file mode 100644
index 000000000..836737d4b
--- /dev/null
+++ b/db/versions/11322-azureAspidistra/00-entryAcl.sql
@@ -0,0 +1,40 @@
+-- Eliminar registros existentes donde property = '*'
+DELETE FROM `salix`.ACL WHERE model = 'entry' AND property = '*';
+
+-- Insertar permisos para los métodos solicitados en el modelo Entry
+INSERT INTO `salix`.ACL (model, property, accessType, permission, principalType, principalId)
+VALUES
+ -- Permisos para administrative
+ ('Entry', 'upsert', 'WRITE', 'ALLOW', 'ROLE', 'administrative'),
+ ('Entry', 'updateAttributes', 'WRITE', 'ALLOW', 'ROLE', 'administrative'),
+ ('Entry', 'isBooked', 'READ', 'ALLOW', 'ROLE', 'administrative'),
+ ('Entry', 'findById', 'READ', 'ALLOW', 'ROLE', 'administrative'),
+ ('Entry', 'find', 'READ', 'ALLOW', 'ROLE', 'administrative'),
+ ('Entry', 'filter', 'READ', 'ALLOW', 'ROLE', 'administrative'),
+ ('Entry', 'count', 'READ', 'ALLOW', 'ROLE', 'administrative'),
+ ('Entry', 'getEntry', 'READ', 'ALLOW', 'ROLE', 'administrative'),
+ ('Entry', 'getBuys', 'READ', 'ALLOW', 'ROLE', 'administrative'),
+ ('Entry', 'findOne', 'READ', 'ALLOW', 'ROLE', 'administrative'),
+ ('Entry', 'deleteBuys', 'WRITE', 'ALLOW', 'ROLE', 'administrative'),
+ ('Entry', 'editLatestBuys', 'WRITE', 'ALLOW', 'ROLE', 'administrative'),
+ ('Entry', 'importBuys', 'WRITE', 'ALLOW', 'ROLE', 'administrative'),
+ ('Entry', 'importBuysPreview', 'READ', 'ALLOW', 'ROLE', 'administrative'),
+ ('Entry', 'lastItemBuys', 'READ', 'ALLOW', 'ROLE', 'administrative'),
+ ('Entry', 'latestBuysFilter', 'READ', 'ALLOW', 'ROLE', 'administrative'),
+
+ -- Permisos para buyer (excluyendo isBooked)
+ ('Entry', 'upsert', 'WRITE', 'ALLOW', 'ROLE', 'buyer'),
+ ('Entry', 'updateAttributes', 'WRITE', 'ALLOW', 'ROLE', 'buyer'),
+ ('Entry', 'findById', 'READ', 'ALLOW', 'ROLE', 'buyer'),
+ ('Entry', 'find', 'READ', 'ALLOW', 'ROLE', 'buyer'),
+ ('Entry', 'filter', 'READ', 'ALLOW', 'ROLE', 'buyer'),
+ ('Entry', 'count', 'READ', 'ALLOW', 'ROLE', 'buyer'),
+ ('Entry', 'getEntry', 'READ', 'ALLOW', 'ROLE', 'buyer'),
+ ('Entry', 'getBuys', 'READ', 'ALLOW', 'ROLE', 'buyer'),
+ ('Entry', 'findOne', 'READ', 'ALLOW', 'ROLE', 'buyer'),
+ ('Entry', 'deleteBuys', 'WRITE', 'ALLOW', 'ROLE', 'buyer'),
+ ('Entry', 'editLatestBuys', 'WRITE', 'ALLOW', 'ROLE', 'buyer'),
+ ('Entry', 'importBuys', 'WRITE', 'ALLOW', 'ROLE', 'buyer'),
+ ('Entry', 'importBuysPreview', 'READ', 'ALLOW', 'ROLE', 'buyer'),
+ ('Entry', 'lastItemBuys', 'READ', 'ALLOW', 'ROLE', 'buyer'),
+ ('Entry', 'latestBuysFilter', 'READ', 'ALLOW', 'ROLE', 'buyer');
diff --git a/db/versions/11324-salmonCataractarum/00-firstScript.sql b/db/versions/11324-salmonCataractarum/00-firstScript.sql
new file mode 100644
index 000000000..5c17ed549
--- /dev/null
+++ b/db/versions/11324-salmonCataractarum/00-firstScript.sql
@@ -0,0 +1,71 @@
+CREATE TABLE IF NOT EXISTS `vn`.`itemTextureTag` (
+ `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
+ `name` varchar(50) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `name_UNIQUE` (`name`)
+) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT
+ CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Natural y encerado');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Natural y esponjoso');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Natural y foam');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Natural y látex');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Arenosa');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Aterciopelado');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Engomado');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Flocado');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Foam');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Gasa');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Goma');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Látex');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Latón');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Mate');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Metálico');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Natural');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Natural y engomado');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Plastificado');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Plastificado y engomado');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Plastificado y rugoso');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Pluma');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Plástico');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Plástico engomado');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Poliéster');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Poliéster texturizado');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Rugoso');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Rígido');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Seminatural');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Silicona');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Suave');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela con brillo');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela con texturas');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela dura');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela engomada');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela escarchada');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela flocada');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela flocada engomada');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela foam');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela micro peach');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela plastificada');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela plástico engomado');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela poliéster');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela PVC');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela ratan');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela rigida');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela rugosa');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela rústica');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela sintética');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela y cristal');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela y foam');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela y goma');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela y látex');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela y madera');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela y plástico');
+INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela y seco');
+
+UPDATE vn.tag
+ SET isFree=0,
+ sourceTable='itemTextureTag'
+ WHERE name= 'Textura';
+
+GRANT SELECT, UPDATE, INSERT, DELETE ON TABLE vn.itemTextureTag TO logisticAssist;
diff --git a/db/versions/11325-navyEucalyptus/00-firstScript.sql b/db/versions/11325-navyEucalyptus/00-firstScript.sql
new file mode 100644
index 000000000..8bc4bd82b
--- /dev/null
+++ b/db/versions/11325-navyEucalyptus/00-firstScript.sql
@@ -0,0 +1,7 @@
+UPDATE salix.ACL
+ SET property='buyLabelSupplier'
+ WHERE property = 'buyLabel'
+ AND model = 'Entry';
+
+INSERT IGNORE INTO salix.ACL (model,property,principalId)
+ VALUES ('Entry','buyLabel','employee');
diff --git a/db/versions/11326-limeOrchid/00-firstScript.sql b/db/versions/11326-limeOrchid/00-firstScript.sql
new file mode 100644
index 000000000..64d772043
--- /dev/null
+++ b/db/versions/11326-limeOrchid/00-firstScript.sql
@@ -0,0 +1,7 @@
+DELETE FROM vn.report
+ WHERE `name` = 'LabelItemQr';
+
+UPDATE vn.report
+ SET `method` = 'Entries/{id}/{labelType}/buy-label',
+ `name` = 'LabelBuy'
+ WHERE `name` = 'LabelItemBarcode';
diff --git a/db/versions/11327-maroonOak/00-firstScript.sql b/db/versions/11327-maroonOak/00-firstScript.sql
new file mode 100644
index 000000000..a51ee3fff
--- /dev/null
+++ b/db/versions/11327-maroonOak/00-firstScript.sql
@@ -0,0 +1,185 @@
+CREATE TABLE IF NOT EXISTS `vn`.`sim` (
+ `code` VARCHAR(25) COMMENT 'No se ha puesto BIGINT por incompatibilidad con Access',
+ `line` VARCHAR(15) NOT NULL CHECK (`line` REGEXP '^[0-9]+$'),
+ `ext` INT(4) NOT NULL,
+ `pin` VARCHAR(4) NOT NULL CHECK (`pin` REGEXP '^[0-9]+$'),
+ `puk` VARCHAR(15) NOT NULL CHECK (`pin` REGEXP '^[0-9]+$'),
+ PRIMARY KEY (`code`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+
+ALTER TABLE vn.deviceProductionUser CHANGE simSerialNumber simFk VARCHAR(25) DEFAULT NULL NULL;
+ALTER TABLE vn.deviceProductionUser MODIFY COLUMN simFk VARCHAR(25) DEFAULT NULL NULL;
+
+INSERT IGNORE INTO `vn`.`sim` (`line`, `ext`, `pin`, `code`, `puk`) VALUES
+ ('621188151', 2209, '1486', '3456985220092508','14213470'),
+ ('621188152', 2210, '8765', '3456985220092509','99473093'),
+ ('621188153', 2211, '3064', '3456985220092510','52967210'),
+ ('621188759', 2081, '3700', '3456985220123637','56600999'),
+ ('621188760', 2082, '3259', '345698522023638','87492404'),
+ ('621188761', 2083, '2790', '3456985220123639','94009456'),
+ ('621188762', 2084, '2480', '3456985220123644','1484999'),
+ ('621188763', 2085, '6876', '3456985220123641','36577064'),
+ ('621188766', 2086, '7775', '3456985220123642','80761698'),
+ ('621188769', 2088, '4027', '3456985220123643','37921712'),
+ ('621188771', 2089, '8797', '3456985220123640','63092540'),
+ ('621188772', 2090, '8404', '3456985220123645','21014997'),
+ ('621188773', 2091, '5481', '3456985220123646','16317277'),
+ ('621188774', 2092, '9632', '3456985220123647','22235994'),
+ ('621188775', 2093, '4654', '3456985220123648','28506486'),
+ ('621188838', 2094, '1392', '3456985220123649','29498627'),
+ ('621188839', 2095, '7774', '3456985220123650','46263490'),
+ ('621188840', 2096, '7304', '3456985220123658','8212044'),
+ ('621188841', 2097, '5569', '3456985220123652','81597658'),
+ ('621188842', 2098, '4944', '3456985220123653','24961501'),
+ ('621188843', 2099, '5142', '3456985220123654','17035634'),
+ ('621188844', 2111, '7245', '3456985220123655','90231951'),
+ ('621188846', 2110, '6590', '3456985220123656','72201537'),
+ ('667680207', 2564, '4042', '34569832200759166','48401979'),
+ ('667680315', 2565, '7143', '34569832200759372','32143252'),
+ ('667680318', 2566, '6342', '34569832200759364','39597112'),
+ ('667680413', 2567, '5580', '34569832200759356','32786992'),
+ ('667680463', 2568, '0171', '34569832200759349','34240853'),
+ ('667688217', 2569, '2500', '34569832200759331','5687589'),
+ ('633603945', 2212, '7129', '34569832200759323','51554019'),
+ ('622130186', 2213, '4826', '34569832200759307','19623551'),
+ ('633973424', 2214, '8535', '34569832200759299','94619307'),
+ ('633703828', 2215, '8628', '34569832200759281','22468012'),
+ ('622025110', 2216, '2399', '34569832200759273','34602918'),
+ ('622924867', 2217, '5665', '34569832200759265','26920216'),
+ ('722409630', 2218, '5211', '34569832200759240','93750137'),
+ ('623590529', 2219, '0493', '34569832200759208','47077088'),
+ ('633243462', 2220, '6902', '34569832200759174','6421962'),
+ ('633047286', 2221, '5592', '34569832200759182','32069439'),
+ ('744716801', 2112, '9184', '34569832200759190','57049814'),
+ ('655995021', 2131, '8896', '34569852202049093','19497356'),
+ ('685522718', 2132, '1955', '34569852202049101','28519879'),
+ ('674587213', 2994, '2006', '34569332200223743','62360135'),
+ ('674587227', 2993, '9271', '34569332200223750','81628192'),
+ ('674587229', 2993, '0900', '34569332200223768','91119071'),
+ ('674587231', 2992, '5007', '34569332200223776','45826232'),
+ ('674587234', 2991, '1378', '34569332200223784','91245744'),
+ ('674587240', 2990, '0905', '34569332200223792','13083224'),
+ ('674587245', 2989, '9059', '34569332200223800','15291807'),
+ ('674587250', 2988, '8188', '34569332200223818','83017918'),
+ ('674587254', 2987, '2962', '34569332200223826','92809271'),
+ ('674587256', 2986, '0358', '34569332200223834','81067040'),
+ ('674592713', 2570, '2537', '34569332200230672','82325850'),
+ ('697832478', 2579, '0936', '34568732200494825','49658372'),
+ ('697832176', 2571, '5944', '34568732200494742','19039461'),
+ ('697832477', 2572, '5138', '34568732200494759','25712504'),
+ ('697832178', 2573, '4597', '34568732200494767','66241760'),
+ ('697832182', 2574, '9241', '34568732200494775','07342562'),
+ ('697832196', 2575, '2995', '34568732200494783','53929026'),
+ ('697832214', 2576, '7434', '34568732200494791','49698432'),
+ ('697832230', 2577, '7004', '34568732200494809','21578612'),
+ ('697832235', 2578, '9674', '34568732200494817','93090700'),
+ ('673420375', 2599, '5430', '34562052300117259','35911412'),
+ ('673420367', 2598, '8402', '34562052300117242','924654'),
+ ('673420361', 2597, '5125', '34562052300117234','12027970'),
+ ('673420355', 2596, '5069', '34562052300117226','34978149'),
+ ('673420348', 2595, '8911', '34562052300117218','4228121'),
+ ('673420346', 2594, '2461', '34562052300117200','67670772'),
+ ('673420345', 2593, '2226', '34562052300117192','90586404'),
+ ('673420306', 2592, '3355', '34562052300117184','97850017'),
+ ('673420257', 2591, '9395', '34562052300117176','50713786'),
+ ('673420231', 2590, '1378', '34562052300117168','50151763'),
+ ('673420223', 2589, '9580', '34562052300117150','99534550'),
+ ('673420216', 2588, '4955', '34562052300117143','317554'),
+ ('673420203', 2587, '6742', '34562052300117135','69321531'),
+ ('673420201', 2586, '1659', '34562052300117127','54720480'),
+ ('673420199', 2585, '7823', '34562052300117119','22923796'),
+ ('673420198', 2584, '1787', '34562052300117101','54414630'),
+ ('673420168', 2583, '6334', '34562052300117093','50694894'),
+ ('673420147', 2582, '8951', '34562052300117085','1402535'),
+ ('673420125', 2581, '3068', '34562052300117077','86216200'),
+ ('673420124', 2580, '9517', '34562052300117069','42504099'),
+ ('600294609', 2715, '7474', '34569832304894588','55923317'),
+ ('600084713', 2703, '8342', '34569832304894570','8392636'),
+ ('600084732', 2704, '1625', '34569832304894513','75477452'),
+ ('600084850', 2705, '9896', '34569832304894653','28589813'),
+ ('600084951', 2706, '5520', '34569832304894661','75353012'),
+ ('600084978', 2707, '2698', '34569832304894679','9005523'),
+ ('600085403', 2708, '0837', '34569832304894646','77051152'),
+ ('600085513', 2709, '3106', '34569832304894687','41571002'),
+ ('600293916', 2712, '8990', '34569832304894620','95188676'),
+ ('600294160', 2714, '6376', '34569832304894703','79879896'),
+ ('671919529', 2975, '9184', '34569832304806236','7535392'),
+ ('671919942', 2981, '0328', '34569832304806269','31052894'),
+ ('671919530', 2976, '0344', '34569832304806251','89860304'),
+ ('671919533', 2977, '0668', '34569832304806244','42921771'),
+ ('671919535', 2978, '0105', '34569832304806277','31009417'),
+ ('671919537', 2979, '0881', '34569832304806285','33479769'),
+ ('671919540', 2980, '9874', '34569832304806293','14103929'),
+ ('671919525', 2972, '2089', '34569832304806301','45903729'),
+ ('671919527', 2973, '8206', '34569832304806368','1586035'),
+ ('671919528', 2974, '2532', '34569832304806327','62310124'),
+ ('673668717', 2836, '7973', '34562032301044223','15635496'),
+ ('673668734', 2837, '4457', '34562032301044231','18313118'),
+ ('673668738', 2824, '2911', '34562032301044249','30875583'),
+ ('673668745', 2838, '7253', '34562032301044256','62754222'),
+ ('673668796', 2839, '0068', '34562032301044264','15556829'),
+ ('673668803', 2840, '2386', '34562032301044272','17572287'),
+ ('673669591', 2850, '3833', '34562032301044280','34828896'),
+ ('673668808', 2841, '3584', '34562032301044298','16234497'),
+ ('673670102', 2851, '3554', '34562032301044306','23652625'),
+ ('673670131', 2852, '4412', '34562032301044314','88611709'),
+ ('673670135', 2827, '6058', '34562032301044322','53918579'),
+ ('673670201', 2828, '8066', '34562032301044330','92369343'),
+ ('673670225', 2829, '4592', '34562032301044348','24126635'),
+ ('673670236', 2830, '2974', '34562032301044355','88608465'),
+ ('673671485', 2849, '0349', '34562032301044363','44944874'),
+ ('673461977', 2871, '1728', '34562032400157090','46975780'),
+ ('673461975', 2870, '4734', '34562032400157082','69628432'),
+ ('673461972', 2867, '6276', '34562032400157058','53338365'),
+ ('673461979', 2872, '6043', '34562032400157108','36525197'),
+ ('673461958', 2859, '3164', '34562032400156977','58947831'),
+ ('673461957', 2857, '8685', '34562032400156969','15826386'),
+ ('673461944', 2853, '1073', '34562032400156910','20452195'),
+ ('673461974', 2869, '7121', '34562032400157074','32044645'),
+ ('673461973', 2868, '8022', '34562032400157066','29282044'),
+ ('673461971', 2866, '3089', '34562032400157041','66149978'),
+ ('673461969', 2865, '7555', '34562032400157033','78391293'),
+ ('673461960', 2860, '5203', '34562032400156985','37138232'),
+ ('673461952', 2855, '6915', '34562032400156936','62724661'),
+ ('673461949', 2854, '8706', '34562032400156928','5594345'),
+ ('673461966', 2863, '2496', '34562032400157017','93450666'),
+ ('673461968', 2864, '3703', '34562032400157025','23208841'),
+ ('673461963', 2862, '9364', '34562032400157009','29712130'),
+ ('673462719', 2873, '9387', '34562032400156951','50434348'),
+ ('673461962', 2861, '8441', '34562032400156993','39686909'),
+ ('673461956', 2826, '5392', '34562032400156944','5496107'),
+ ('673465284', 2694, '1523', '34562032400171349','14554994'),
+ ('673465282', 2692, '4645', '34562032400171323','24871187'),
+ ('673465283', 2693, '5253', '34562032400171331','28303238'),
+ ('673465841', 2696, '0849', '34562032400171257','21673222'),
+ ('673465258', 2679, '4140', '34562032400171174','39793881'),
+ ('673465263', 2680, '6922', '34562032400171182','12253261'),
+ ('673465265', 2681, '9112', '34562032400171190','93894366'),
+ ('673465267', 2682, '3259', '34562032400171208','2342189'),
+ ('673465268', 2683, '8540', '34562032400171216','63886925'),
+ ('673465285', 2695, '4167', '34562032400171356','79227618'),
+ ('673465270', 2684, '4292', '34562032400171224','19216349'),
+ ('673465272', 2685, '4007', '34562032400171232','14396903'),
+ ('673465273', 2686, '6894', '34562032400171240','13569394'),
+ ('673465274', 2687, '5268', '34562032400171265','59453667'),
+ ('673465275', 2688, '0232', '34562032400171273','62324713'),
+ ('673465276', 2689, '2720', '34562032400171281','65977200'),
+ ('673465843', 2698, '4773', '34562032400171364','78387158'),
+ ('673465842', 2697, '3729', '34562032400171315','94201789'),
+ ('673465280', 2691, '0503', '34562032400171307','12298533'),
+ ('673465279', 2690, '8239', '34562032400171299','76183877');
+
+UPDATE vn.deviceProductionUser
+ SET simFk = NULL
+ WHERE id IN (
+ SELECT dpu.id
+ FROM vn.deviceProductionUser dpu
+ LEFT JOIN vn.sim s ON s.code = dpu.simFk
+ WHERE s.code IS NULL
+ AND dpu.simFk IS NOT NULL
+ );
+
+ALTER TABLE vn.deviceProductionUser ADD CONSTRAINT deviceProductionUser_sim_FK
+ FOREIGN KEY (simFk) REFERENCES vn.sim(code) ON DELETE RESTRICT ON UPDATE CASCADE;
+
+GRANT SELECT, INSERT, DELETE, UPDATE ON TABLE vn.sim TO hr;
diff --git a/db/versions/11330-greenMoss/00-firstScript.sql b/db/versions/11330-greenMoss/00-firstScript.sql
new file mode 100644
index 000000000..127c8e40e
--- /dev/null
+++ b/db/versions/11330-greenMoss/00-firstScript.sql
@@ -0,0 +1,16 @@
+CREATE TABLE IF NOT EXISTS vn.saySimpleCountry(
+ countryFk MEDIUMINT(8) UNSIGNED,
+ channel INT(4) COMMENT 'channel de whatsapp de saySimple',
+ PRIMARY KEY (countryFk),
+ CONSTRAINT `saySimpleCountry_FK` FOREIGN KEY (`countryFk`) REFERENCES vn.country (`id`) ON UPDATE CASCADE
+);
+
+CREATE TABLE IF NOT EXISTS vn.saySimpleConfig(
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ url VARCHAR(255) NOT NULL
+);
+
+INSERT IGNORE INTO vn.saySimpleCountry (countryFk, channel)
+ VALUES (19, 1169),
+ (8, 1183),
+ (NULL, 1320);
\ No newline at end of file
diff --git a/db/versions/11331-bronzeBirch/00-firstScript.sql b/db/versions/11331-bronzeBirch/00-firstScript.sql
new file mode 100644
index 000000000..ada374182
--- /dev/null
+++ b/db/versions/11331-bronzeBirch/00-firstScript.sql
@@ -0,0 +1,2 @@
+ALTER TABLE vn.supplier ADD companySize ENUM('small', 'medium', 'big') NULL;
+
diff --git a/db/versions/11332-tealErica/00-firstScript.sql b/db/versions/11332-tealErica/00-firstScript.sql
new file mode 100644
index 000000000..a7870632f
--- /dev/null
+++ b/db/versions/11332-tealErica/00-firstScript.sql
@@ -0,0 +1,4 @@
+ALTER TABLE vn.travel ADD IF NOT EXISTS isRaid tinyint(1) DEFAULT 0 NOT NULL COMMENT 'Redada';
+
+ALTER TABLE vn.travel MODIFY COLUMN daysInForward int(10) unsigned DEFAULT NULL
+ COMMENT 'Cuando es una redada, indica el número de días que se añadirán a la fecha de hoy para establecer el landed. NULL si no es una redada';
\ No newline at end of file
diff --git a/db/versions/11336-chocolateRaphis/00-firstScript.sql b/db/versions/11336-chocolateRaphis/00-firstScript.sql
new file mode 100644
index 000000000..c86dc39e9
--- /dev/null
+++ b/db/versions/11336-chocolateRaphis/00-firstScript.sql
@@ -0,0 +1,8 @@
+DELETE FROM salix.ACL
+ WHERE property IN ('cmrs', 'cmr', 'downloadCmrsZip')
+ AND model = 'Route';
+
+INSERT INTO salix.ACL (model,property,principalId)
+ VALUES ('Cmr','filter','production'),
+ ('Cmr','downloadZip','production'),
+ ('Cmr','print','production')
\ No newline at end of file
diff --git a/db/versions/11337-limeAsparagus/00-firstScript.sql b/db/versions/11337-limeAsparagus/00-firstScript.sql
new file mode 100644
index 000000000..4cfedc8a8
--- /dev/null
+++ b/db/versions/11337-limeAsparagus/00-firstScript.sql
@@ -0,0 +1 @@
+ALTER TABLE vn.productionConfig DROP COLUMN hasNewLabelMrwMethod;
diff --git a/db/versions/11338-brownMonstera/00-firstScript.sql b/db/versions/11338-brownMonstera/00-firstScript.sql
new file mode 100644
index 000000000..9752bb90d
--- /dev/null
+++ b/db/versions/11338-brownMonstera/00-firstScript.sql
@@ -0,0 +1,2 @@
+-- Place your SQL code here
+RENAME TABLE vn.stockBuyed__ TO vn.stockBuyed;
diff --git a/db/versions/11339-goldenMastic/00-firstScript.sql b/db/versions/11339-goldenMastic/00-firstScript.sql
new file mode 100644
index 000000000..f1da5798a
--- /dev/null
+++ b/db/versions/11339-goldenMastic/00-firstScript.sql
@@ -0,0 +1 @@
+ALTER TABLE vn.dua ADD comment TEXT DEFAULT NULL NULL;
diff --git a/db/versions/11341-pinkSalal/00-firstScript.sql b/db/versions/11341-pinkSalal/00-firstScript.sql
new file mode 100644
index 000000000..2c9e912d9
--- /dev/null
+++ b/db/versions/11341-pinkSalal/00-firstScript.sql
@@ -0,0 +1,5 @@
+
+ALTER TABLE vn.travel ADD IF NOT EXISTS isRaid tinyint(1) DEFAULT 0 NOT NULL COMMENT 'Redada';
+
+ALTER TABLE vn.travel MODIFY COLUMN daysInForward int(10) unsigned DEFAULT NULL
+ COMMENT 'Cuando es una redada, indica el número de días que se añadirán a la fecha de hoy para establecer el landed. NULL si no es una redada';
diff --git a/db/versions/11342-crimsonDendro/00-itemShelving.sql b/db/versions/11342-crimsonDendro/00-itemShelving.sql
new file mode 100644
index 000000000..4d083bf97
--- /dev/null
+++ b/db/versions/11342-crimsonDendro/00-itemShelving.sql
@@ -0,0 +1,6 @@
+CREATE OR REPLACE TEMPORARY TABLE tmp.tItemShelving
+ (PRIMARY KEY (id))
+ ENGINE = MEMORY
+ SELECT ish.id, s.id shelvingFk
+ FROM vn.itemShelving ish
+ JOIN vn.shelving s ON s.code = ish.shelvingFk COLLATE utf8mb3_unicode_ci;
diff --git a/db/versions/11342-crimsonDendro/01-itemShelving.sql b/db/versions/11342-crimsonDendro/01-itemShelving.sql
new file mode 100644
index 000000000..23099ac6b
--- /dev/null
+++ b/db/versions/11342-crimsonDendro/01-itemShelving.sql
@@ -0,0 +1,2 @@
+ALTER TABLE vn.itemShelving DROP FOREIGN KEY itemShelving_fk2,
+ MODIFY COLUMN shelvingFk int(11) NOT NULL;
diff --git a/db/versions/11342-crimsonDendro/02-itemShelving.sql b/db/versions/11342-crimsonDendro/02-itemShelving.sql
new file mode 100644
index 000000000..9d0e65d0b
--- /dev/null
+++ b/db/versions/11342-crimsonDendro/02-itemShelving.sql
@@ -0,0 +1,3 @@
+UPDATE vn.itemShelving ish
+ JOIN tmp.tItemShelving tish ON tish.id = ish.id
+ SET ish.shelvingFk = tish.shelvingFk;
\ No newline at end of file
diff --git a/db/versions/11342-crimsonDendro/03-itemShelving.sql b/db/versions/11342-crimsonDendro/03-itemShelving.sql
new file mode 100644
index 000000000..cb9825bfc
--- /dev/null
+++ b/db/versions/11342-crimsonDendro/03-itemShelving.sql
@@ -0,0 +1,4 @@
+ALTER TABLE vn.itemShelving
+ ADD CONSTRAINT itemShelving_shelving_FK FOREIGN KEY (shelvingFk) REFERENCES vn.shelving(id)
+ ON DELETE RESTRICT
+ ON UPDATE CASCADE;
diff --git a/db/versions/11342-crimsonDendro/04-itemShelvingLog.sql b/db/versions/11342-crimsonDendro/04-itemShelvingLog.sql
new file mode 100644
index 000000000..1135b9d09
--- /dev/null
+++ b/db/versions/11342-crimsonDendro/04-itemShelvingLog.sql
@@ -0,0 +1,8 @@
+/*
+CREATE OR REPLACE TEMPORARY TABLE tmp.tItemShelvingLog
+ (PRIMARY KEY (id))
+ ENGINE = MEMORY
+ SELECT ishl.id, s.id shelvingFk
+ FROM vn.itemShelvingLog ishl
+ JOIN vn.shelving s ON s.code = ishl.shelvingFk COLLATE utf8mb3_unicode_ci;
+*/
diff --git a/db/versions/11342-crimsonDendro/05-itemShelvingLog.sql b/db/versions/11342-crimsonDendro/05-itemShelvingLog.sql
new file mode 100644
index 000000000..b0e3b55cc
--- /dev/null
+++ b/db/versions/11342-crimsonDendro/05-itemShelvingLog.sql
@@ -0,0 +1 @@
+-- ALTER TABLE vn.itemShelvingLog MODIFY COLUMN shelvingFk int(11) NOT NULL;
diff --git a/db/versions/11342-crimsonDendro/06-itemShelvingLog.sql b/db/versions/11342-crimsonDendro/06-itemShelvingLog.sql
new file mode 100644
index 000000000..f97f61e42
--- /dev/null
+++ b/db/versions/11342-crimsonDendro/06-itemShelvingLog.sql
@@ -0,0 +1,7 @@
+/*
+UPDATE vn.itemShelvingLog ishl
+ JOIN tmp.tItemShelvingLog tishl ON tishl.id = ishl.id
+ SET ishl.shelvingFk = tishl.shelvingFk;
+
+DROP TEMPORARY TABLE tmp.tItemShelvingLog;
+*/
\ No newline at end of file
diff --git a/db/versions/11343-silverAsparagus/00-firstScript.sql b/db/versions/11343-silverAsparagus/00-firstScript.sql
new file mode 100644
index 000000000..bcee42eea
--- /dev/null
+++ b/db/versions/11343-silverAsparagus/00-firstScript.sql
@@ -0,0 +1,9 @@
+INSERT INTO salix.ACL (model, property, accessType, principalId)
+ VALUES ('Collection', 'create', 'WRITE', 'productionBoss'),
+ ('Collection', 'upsert', 'WRITE', 'productionBoss'),
+ ('Collection', 'replaceById', 'WRITE', 'productionBoss'),
+ ('Collection', 'updateAll', 'WRITE', 'productionBoss'),
+ ('Collection', 'updateAttributes', 'WRITE', 'productionBoss'),
+ ('Collection', 'deleteById', 'WRITE', 'productionBoss'),
+ ('Collection', 'destroyAll', 'WRITE', 'productionBoss'),
+ ('Collection', 'destroyById', 'WRITE', 'productionBoss');
diff --git a/db/versions/11344-grayBamboo/00-firstScript.sql b/db/versions/11344-grayBamboo/00-firstScript.sql
new file mode 100644
index 000000000..1fbd2a0d8
--- /dev/null
+++ b/db/versions/11344-grayBamboo/00-firstScript.sql
@@ -0,0 +1,3 @@
+UPDATE vn.sale
+ SET originalQuantity = quantity
+ WHERE originalQuantity IS NULL
\ No newline at end of file
diff --git a/db/versions/11344-grayBamboo/01-firstScript.sql b/db/versions/11344-grayBamboo/01-firstScript.sql
new file mode 100644
index 000000000..e3e08e0aa
--- /dev/null
+++ b/db/versions/11344-grayBamboo/01-firstScript.sql
@@ -0,0 +1 @@
+ALTER TABLE vn.sale MODIFY COLUMN originalQuantity decimal(10,2) DEFAULT 0.00 NOT NULL COMMENT 'Se utiliza para notificar a través de rocket los cambios de quantity';
\ No newline at end of file
diff --git a/db/versions/11345-salmonEucalyptus/00-firstScript.sql b/db/versions/11345-salmonEucalyptus/00-firstScript.sql
new file mode 100644
index 000000000..ecbc36c40
--- /dev/null
+++ b/db/versions/11345-salmonEucalyptus/00-firstScript.sql
@@ -0,0 +1,2 @@
+ALTER TABLE account.user CHANGE recoverPass recoverPass__ tinyint(3) unsigned NOT NULL DEFAULT 1 COMMENT '@deprecated 2024-11-13';
+ALTER TABLE account.user CHANGE sync sync__ tinyint(4) NOT NULL DEFAULT 0 COMMENT '@deprecated 2024-11-13';
\ No newline at end of file
diff --git a/db/versions/11346-yellowPhormium/00-address.sql b/db/versions/11346-yellowPhormium/00-address.sql
new file mode 100644
index 000000000..f91d0ae9f
--- /dev/null
+++ b/db/versions/11346-yellowPhormium/00-address.sql
@@ -0,0 +1,23 @@
+ALTER TABLE vn.address
+ ADD geoFk int(11) DEFAULT NULL NULL AFTER isLogifloraAllowed,
+ ADD CONSTRAINT address_zoneGeo_FK FOREIGN KEY (geoFk)
+ REFERENCES vn.zoneGeo(id) ON DELETE RESTRICT ON UPDATE CASCADE;
+
+CREATE OR REPLACE TEMPORARY TABLE tmp.tAddressGeo
+ (PRIMARY KEY (id))
+ ENGINE = MEMORY
+ SELECT a.id, p.geoFk
+ FROM vn.address a
+ JOIN vn.town t ON t.provinceFk = a.provinceFk
+ JOIN vn.postCode p ON p.townFk = t.id
+ AND (p.code = a.postalCode OR a.postalCode IS NULL)
+ JOIN vn.zoneGeo zg ON zg.id = p.geoFk
+ GROUP BY a.id
+ ORDER BY (a.city SOUNDS LIKE t.`name`) DESC,
+ (p.code = a.postalCode) DESC;
+
+UPDATE vn.address a
+ JOIN tmp.tAddressGeo tag ON tag.id = a.id
+ SET a.geoFk = tag.geoFk;
+
+DROP TEMPORARY TABLE tmp.tAddressGeo;
diff --git a/db/versions/11346-yellowPhormium/01-client.sql b/db/versions/11346-yellowPhormium/01-client.sql
new file mode 100644
index 000000000..cb6fe41e8
--- /dev/null
+++ b/db/versions/11346-yellowPhormium/01-client.sql
@@ -0,0 +1,26 @@
+ALTER TABLE vn.client
+ CHANGE hasDailyInvoice hasDailyInvoice tinyint(1) DEFAULT 0 NOT NULL
+ COMMENT 'Indica si el cliente requiere facturación diaria por defecto se copiará lo que tenga country.hasDailyInvoice'
+ AFTER recommendedCredit,
+ ADD geoFk int(11) DEFAULT NULL NULL AFTER hasDailyInvoice,
+ ADD CONSTRAINT client_zoneGeo_FK FOREIGN KEY (geoFk)
+ REFERENCES vn.zoneGeo(id) ON DELETE RESTRICT ON UPDATE CASCADE;
+
+CREATE OR REPLACE TEMPORARY TABLE tmp.tClientGeo
+ (PRIMARY KEY (id))
+ ENGINE = MEMORY
+ SELECT c.id, p.geoFk
+ FROM vn.client c
+ JOIN vn.town t ON t.provinceFk = c.provinceFk
+ JOIN vn.postCode p ON p.townFk = t.id
+ AND (p.code = c.postcode OR c.postcode IS NULL)
+ JOIN vn.zoneGeo zg ON zg.id = p.geoFk
+ GROUP BY c.id
+ ORDER BY (c.city SOUNDS LIKE t.`name`) DESC,
+ (p.code = c.postcode) DESC;
+
+UPDATE vn.client c
+ JOIN tmp.tClientGeo tcg ON tcg.id = c.id
+ SET c.geoFk = tcg.geoFk;
+
+DROP TEMPORARY TABLE tmp.tClientGeo;
diff --git a/db/versions/11346-yellowPhormium/02-supplier.sql b/db/versions/11346-yellowPhormium/02-supplier.sql
new file mode 100644
index 000000000..4e866525e
--- /dev/null
+++ b/db/versions/11346-yellowPhormium/02-supplier.sql
@@ -0,0 +1,27 @@
+ALTER TABLE vn.supplier
+ CHANGE companySize companySize enum('small','medium','big') CHARACTER SET utf8mb3
+ COLLATE utf8mb3_general_ci DEFAULT NULL NULL AFTER stamp,
+ ADD geoFk int(11) DEFAULT NULL NULL AFTER companySize,
+ ADD CONSTRAINT supplier_zoneGeo_FK FOREIGN KEY (geoFk)
+ REFERENCES vn.zoneGeo(id) ON DELETE RESTRICT ON UPDATE CASCADE;
+
+CREATE OR REPLACE TEMPORARY TABLE tmp.tSupplierGeo
+ (PRIMARY KEY (id))
+ ENGINE = MEMORY
+ SELECT s.id, p.geoFk
+ FROM vn.supplier s
+ JOIN vn.town t ON t.provinceFk = s.provinceFk
+ JOIN vn.postCode p ON p.townFk = t.id
+ AND (p.code = s.postCode OR s.postCode IS NULL)
+ LEFT JOIN vn.supplierAddress sad ON sad.supplierFk = s.id
+ JOIN vn.zoneGeo zg ON zg.id = p.geoFk
+ GROUP BY s.id
+ ORDER BY (s.city SOUNDS LIKE t.`name`) DESC,
+ (p.code = s.postCode) DESC,
+ (p.code = sad.postalCode) DESC;
+
+UPDATE vn.supplier s
+ JOIN tmp.tSupplierGeo tsg ON tsg.id = s.id
+ SET s.geoFk = tsg.geoFk;
+
+DROP TEMPORARY TABLE tmp.tSupplierGeo;
diff --git a/db/versions/11347-redErica/00-firstScript.sql b/db/versions/11347-redErica/00-firstScript.sql
new file mode 100644
index 000000000..5da1d6096
--- /dev/null
+++ b/db/versions/11347-redErica/00-firstScript.sql
@@ -0,0 +1,9 @@
+DROP TABLE IF EXISTS vn.saySimpleConfig;
+
+CREATE TABLE vn.saySimpleConfig(
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ url VARCHAR(255) NOT NULL,
+ defaultChannel VARCHAR(128)
+);
+
+ALTER TABLE vn.saySimpleCountry MODIFY COLUMN channel VARCHAR(128);
\ No newline at end of file
diff --git a/db/versions/11348-bronzeCamellia/00-firstScript.sql b/db/versions/11348-bronzeCamellia/00-firstScript.sql
new file mode 100644
index 000000000..fa466f1a4
--- /dev/null
+++ b/db/versions/11348-bronzeCamellia/00-firstScript.sql
@@ -0,0 +1,2 @@
+ALTER TABLE vn.clientObservation MODIFY COLUMN observationTypeFk tinyint(3) unsigned DEFAULT 4 NOT NULL;
+UPDATE vn.clientObservation SET observationTypeFk=4 WHERE observationTypeFk=0;
diff --git a/db/versions/11349-azureBamboo/00-firstScript.sql b/db/versions/11349-azureBamboo/00-firstScript.sql
new file mode 100644
index 000000000..09c919b79
--- /dev/null
+++ b/db/versions/11349-azureBamboo/00-firstScript.sql
@@ -0,0 +1,7 @@
+
+
+UPDATE salix.ACL
+ SET principalId = 'deliveryAssistant'
+WHERE model = 'Ticket'
+ AND property = 'updateAttributes'
+ AND principalId = "delivery";
diff --git a/db/versions/11350-silverArborvitae/00-firstScript.sql b/db/versions/11350-silverArborvitae/00-firstScript.sql
new file mode 100644
index 000000000..b5e87133e
--- /dev/null
+++ b/db/versions/11350-silverArborvitae/00-firstScript.sql
@@ -0,0 +1,2 @@
+ALTER TABLE vn.shelvingLog
+ MODIFY COLUMN changedModel enum('Shelving', 'ItemShelving') CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT 'Shelving' NOT NULL;
diff --git a/db/versions/11351-bronzeMedeola/00-firstScript.sql b/db/versions/11351-bronzeMedeola/00-firstScript.sql
new file mode 100644
index 000000000..c94447a89
--- /dev/null
+++ b/db/versions/11351-bronzeMedeola/00-firstScript.sql
@@ -0,0 +1,2 @@
+
+ALTER TABLE vn.itemConfig ADD defaultPackingTypeFk VARCHAR(1) DEFAULT 'H' NULL;
diff --git a/db/versions/11352-blackErica/00-firstScript.sql b/db/versions/11352-blackErica/00-firstScript.sql
new file mode 100644
index 000000000..659f50161
--- /dev/null
+++ b/db/versions/11352-blackErica/00-firstScript.sql
@@ -0,0 +1,3 @@
+-- Place your SQL code here
+INSERT IGNORE INTO salix.ACL (model, property, accessType, permission, principalType, principalId)
+ VALUES('InventoryConfig', 'find', 'READ', 'ALLOW', 'ROLE', 'buyer');
\ No newline at end of file
diff --git a/db/versions/11353-wheatCymbidium/00-firstScript.sql b/db/versions/11353-wheatCymbidium/00-firstScript.sql
new file mode 100644
index 000000000..557ffab9e
--- /dev/null
+++ b/db/versions/11353-wheatCymbidium/00-firstScript.sql
@@ -0,0 +1,15 @@
+
+
+USE vn;
+
+INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId)
+VALUES('RouteAction', 'find', 'READ', 'ALLOW', 'ROLE', 'delivery');
+
+INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId)
+VALUES('RouteComplement', 'find', 'READ', 'ALLOW', 'ROLE', 'delivery');
+
+INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId)
+VALUES('RouteComplement', 'create', 'WRITE', 'ALLOW', 'ROLE', 'delivery');
+
+INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId)
+VALUES('RouteComplement', 'deleteById', 'WRITE', 'ALLOW', 'ROLE', 'delivery');
\ No newline at end of file
diff --git a/db/versions/11354-aquaMastic/00-firstScript.sql b/db/versions/11354-aquaMastic/00-firstScript.sql
new file mode 100644
index 000000000..dda3f4752
--- /dev/null
+++ b/db/versions/11354-aquaMastic/00-firstScript.sql
@@ -0,0 +1,2 @@
+RENAME TABLE vn.workerTimeControlParams TO vn.workerTimeControlParams__;
+ALTER TABLE vn.workerTimeControlParams__ COMMENT='@deprecated 2024-11-19';
\ No newline at end of file
diff --git a/db/versions/11355-pinkMedeola/00-firstScript.sql b/db/versions/11355-pinkMedeola/00-firstScript.sql
new file mode 100644
index 000000000..fc89b386c
--- /dev/null
+++ b/db/versions/11355-pinkMedeola/00-firstScript.sql
@@ -0,0 +1,3 @@
+-- Place your SQL code here
+INSERT IGNORE INTO vn.saySimpleConfig (url, defaultChannel)
+ VALUES ('https://verdnatura.saysimple.io/start-conversation', 1320);
\ No newline at end of file
diff --git a/db/versions/11357-whiteGerbera/00-firstScript.sql b/db/versions/11357-whiteGerbera/00-firstScript.sql
new file mode 100644
index 000000000..c10ec4d26
--- /dev/null
+++ b/db/versions/11357-whiteGerbera/00-firstScript.sql
@@ -0,0 +1,4 @@
+ALTER TABLE vn.travel ADD IF NOT EXISTS isRaid tinyint(1) DEFAULT 0 NOT NULL COMMENT 'Redada';
+
+ALTER TABLE vn.travel MODIFY COLUMN daysInForward int(10) unsigned DEFAULT NULL
+ COMMENT 'Cuando es una redada, indica el número de días que se añadirán a la fecha de hoy para establecer el landed. NULL si no es una redada';
diff --git a/db/versions/11358-maroonPhormium/00-firstScript.sql b/db/versions/11358-maroonPhormium/00-firstScript.sql
new file mode 100644
index 000000000..88762e5aa
--- /dev/null
+++ b/db/versions/11358-maroonPhormium/00-firstScript.sql
@@ -0,0 +1,51 @@
+
+ ALTER TABLE vn.routeCommission ADD IF NOT EXISTS countryFk mediumint(8) unsigned DEFAULT NULL NULL;
+ ALTER TABLE vn.routeCommission ADD IF NOT EXISTS isKmTruckRate TINYINT(1) DEFAULT NULL NULL;
+
+ ALTER TABLE vn.routeCommission DROP FOREIGN KEY IF EXISTS routeCommission_country_FK;
+ ALTER TABLE vn.routeCommission ADD CONSTRAINT routeCommission_country_FK FOREIGN KEY (countryFk)
+ REFERENCES vn.country(id) ON DELETE RESTRICT ON UPDATE CASCADE;
+
+ CREATE TABLE IF NOT EXISTS vn.workCenterCommission (
+ `workCenterFk` INT(11) NOT NULL,
+ `deliveryManAdjustment` DECIMAL(4,2) DEFAULT NULL
+ COMMENT 'Número de trabajadores para equilibrar los repartidores de diferentes centros.
+ Utilizado en repartidores de grafana',
+ `distributionM3Category1` decimal(5,2) DEFAULT NULL,
+ `distributionM3Category2` decimal(5,2) DEFAULT NULL,
+ `distributionCat4M3` DECIMAL(5,2) DEFAULT NULL
+ COMMENT 'Comisión por gestión de la distribución Cat IV',
+ `distributionCat5M3` DECIMAL(5,2) DEFAULT NULL
+ COMMENT 'Comisión por gestión de la distribución Cat V',
+ PRIMARY KEY (`workCenterFk`),
+ CONSTRAINT `workCenterCommission_workCenterFk` FOREIGN KEY (`workCenterFk`)
+ REFERENCES `workCenter` (`id`) ON UPDATE CASCADE ON DELETE RESTRICT
+ );
+
+ UPDATE vn.routeCommission rc
+ JOIN (SELECT id, countryFk, isKmTruckRate
+ FROM (SELECT r.id, c.countryFk, v.isKmTruckRate
+ FROM vn.route r
+ JOIN vn.routeCommission rc ON rc.routeFk = r.id
+ LEFT JOIN vn.ticket t ON t.routeFk = r.id
+ LEFT JOIN vn.client c ON c.id = t.clientFk
+ LEFT JOIN vn.vehicle v ON v.id = r.vehicleFk
+ WHERE r.created >= '2023-12-01'
+ GROUP BY r.id, c.countryFk
+ ORDER BY r.id, COUNT(*) DESC
+ LIMIT 100000000000
+ )sub
+ GROUP BY id
+ )sub ON sub.id = rc.routeFk
+ SET rc.isKmTruckRate = sub.isKmTruckRate,
+ rc.countryFk = sub.countryFk;
+
+ ALTER TABLE vn.workerDistributionCategory ADD IF NOT EXISTS countryFk mediumint(8) unsigned DEFAULT NULL NULL;
+ ALTER TABLE vn.workerDistributionCategory ADD IF NOT EXISTS isKmTruckRate TINYINT(1) DEFAULT NULL NULL;
+
+ ALTER TABLE vn.workerDistributionCategory DROP FOREIGN KEY IF EXISTS workerDistributionCategory_country_FK;
+ ALTER TABLE vn.workerDistributionCategory ADD CONSTRAINT workerDistributionCategory_country_FK FOREIGN KEY (countryFk)
+ REFERENCES vn.country(id) ON DELETE RESTRICT ON UPDATE CASCADE;
+
+ ALTER TABLE vn.workerDistributionCategory ADD IF NOT EXISTS commissionSplitWorkers INT UNSIGNED NOT NULL DEFAULT 1
+ COMMENT 'Número de enrutadores entr los que se reparte la comsión';
diff --git a/db/versions/11359-navyPaniculata/00-firstScript.sql b/db/versions/11359-navyPaniculata/00-firstScript.sql
new file mode 100644
index 000000000..de057b540
--- /dev/null
+++ b/db/versions/11359-navyPaniculata/00-firstScript.sql
@@ -0,0 +1,8 @@
+DELETE FROM vn.stateI18n
+ WHERE `name` IN ('Billed', 'Facturado', 'Assisted preparation', 'Preparación asistida', 'Shipped', 'Embarcado', 'Stowaway OK', 'Polizón OK');
+
+UPDATE vn.`state` SET nextStateFk = 43
+ WHERE nextStateFk IN (11, 27, 30, 32, 41);
+
+DELETE FROM vn.`state`
+ WHERE code IN ('INVOICED', 'ASSISTED_PREPARATION', 'BOARD', 'OK STOWAWAY', 'PARTIAL_PREPARATION');
\ No newline at end of file
diff --git a/db/versions/11362-limeLilium/00-firstScript.sql b/db/versions/11362-limeLilium/00-firstScript.sql
new file mode 100644
index 000000000..4a7c5b742
--- /dev/null
+++ b/db/versions/11362-limeLilium/00-firstScript.sql
@@ -0,0 +1,4 @@
+
+
+INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId)
+VALUES('SaleGroup', 'find', 'READ', 'ALLOW', 'ROLE', 'production');
\ No newline at end of file
diff --git a/db/versions/11363-silverCarnation/00-firstScript.sql b/db/versions/11363-silverCarnation/00-firstScript.sql
new file mode 100644
index 000000000..8c2e68ff4
--- /dev/null
+++ b/db/versions/11363-silverCarnation/00-firstScript.sql
@@ -0,0 +1,7 @@
+ALTER TABLE vn.workCenterCommission ADD IF NOT EXISTS deliveryM3Cat4 DECIMAL(5,2) DEFAULT NULL NULL;
+ALTER TABLE vn.workCenterCommission ADD IF NOT EXISTS deliveryM3Cat5 DECIMAL(5,2) DEFAULT NULL NULL;
+
+INSERT IGNORE INTO vn.workCenterCommission (workCenterFk, deliveryM3Cat4, deliveryM3Cat5)
+ VALUES (5,8.0,8.0);
+
+
diff --git a/db/versions/11366-navyBirch/00-firstScript.sql b/db/versions/11366-navyBirch/00-firstScript.sql
new file mode 100644
index 000000000..4d56c13b8
--- /dev/null
+++ b/db/versions/11366-navyBirch/00-firstScript.sql
@@ -0,0 +1,2 @@
+RENAME TABLE vn.itemShelvingLog TO vn.itemShelvingLog__;
+ALTER TABLE vn.itemShelvingLog__ COMMENT='@deprecated 2024-11-26';
diff --git a/db/versions/11367-grayOrchid/00-deprecate.sql b/db/versions/11367-grayOrchid/00-deprecate.sql
new file mode 100644
index 000000000..19e82419e
--- /dev/null
+++ b/db/versions/11367-grayOrchid/00-deprecate.sql
@@ -0,0 +1,7 @@
+ALTER TABLE `vn`.`creditInsurance` DROP COLUMN `creditClassification__`;
+ALTER TABLE `vn`.`worker` DROP COLUMN `isF11Allowed__`;
+ALTER TABLE `util`.`config` DROP COLUMN `dbVersion__`;
+ALTER TABLE `util`.`config` DROP COLUMN `hasTriggersDisabled__`;
+ALTER TABLE `vn`.`agencyMode` DROP COLUMN `showAgencyName__`;
+DROP TABLE `account`.`accountLog__`;
+DROP TABLE `vn`.`silexACL__`;
diff --git a/db/versions/11368-whiteAspidistra/00-firstScript.sql b/db/versions/11368-whiteAspidistra/00-firstScript.sql
new file mode 100644
index 000000000..f36832805
--- /dev/null
+++ b/db/versions/11368-whiteAspidistra/00-firstScript.sql
@@ -0,0 +1,48 @@
+ USE vn;
+
+ DROP TRIGGER IF EXISTS invoiceIn_beforeUpdate;
+
+ UPDATE invoiceIn
+ SET cplusRectificationTypeFk = NULL
+ WHERE cplusRectificationTypeFk = 1;
+
+ DELETE IGNORE FROM cplusRectificationType WHERE id = 1;
+
+ UPDATE cplusRectificationType
+ SET id = 1
+ WHERE id = 3;
+
+DELIMITER $$
+CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`invoiceIn_beforeUpdate`
+ BEFORE UPDATE ON `invoiceIn`
+ FOR EACH ROW
+BEGIN
+ DECLARE vWithholdingSageFk INT;
+
+ IF NOT (NEW.supplierRef <=> OLD.supplierRef) AND NOT util.checkPrintableChars(NEW.supplierRef) THEN
+ CALL util.throw('The invoiceIn reference contains invalid characters');
+ END IF;
+
+ SET NEW.editorFk = account.myUser_getId();
+
+ IF (SELECT COUNT(*) FROM invoiceIn
+ WHERE supplierRef = NEW.supplierRef
+ AND supplierFk = NEW.supplierFk
+ AND YEAR(issued) = YEAR(NEW.issued)
+ AND id <> NEW.id
+ ) THEN
+ CALL util.throw('reference duplicated');
+ END IF;
+
+ IF NEW.supplierFk != OLD.supplierFk THEN
+ CALL supplier_checkIsActive(NEW.supplierFk);
+ SELECT withholdingSageFk INTO vWithholdingSageFk
+ FROM supplier
+ WHERE id = NEW.supplierFk;
+ SET NEW.withholdingSageFk = vWithholdingSageFk;
+ END IF;
+
+END$$
+DELIMITER ;
+
+
diff --git a/db/versions/11368-whiteAspidistra/01-acls.sql b/db/versions/11368-whiteAspidistra/01-acls.sql
new file mode 100644
index 000000000..6ac98db43
--- /dev/null
+++ b/db/versions/11368-whiteAspidistra/01-acls.sql
@@ -0,0 +1,23 @@
+INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId)
+ VALUES('SiiTypeInvoiceIn', 'find', 'READ', 'ALLOW', 'ROLE', 'salesPerson');
+
+DROP TABLE IF EXISTS vn.invoiceInCorrection;
+
+CREATE TABLE `invoiceInCorrection` (
+ `correctingFk` mediumint(8) unsigned NOT NULL COMMENT 'Factura rectificativa',
+ `correctedFk` mediumint(8) unsigned NOT NULL COMMENT 'Factura rectificada',
+ `cplusRectificationTypeFk` int(10) unsigned NOT NULL,
+ `siiTypeInvoiceInFk` int(10) unsigned NOT NULL,
+ `invoiceCorrectionTypeFk` int(11) NOT NULL DEFAULT 3,
+ PRIMARY KEY (`correctingFk`),
+ KEY `invoiceInCorrection_correctedFk` (`correctedFk`),
+ KEY `invoiceInCorrection_cplusRectificationTypeFk` (`cplusRectificationTypeFk`),
+ KEY `invoiceInCorrection_siiTypeInvoiceIn` (`siiTypeInvoiceInFk`),
+ KEY `invoiceInCorrection_invoiceCorrectionTypeFk` (`invoiceCorrectionTypeFk`),
+ CONSTRAINT `invoiceInCorrection_correctedFk` FOREIGN KEY (`correctedFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `invoiceInCorrection_correctingFk` FOREIGN KEY (`correctingFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `invoiceInCorrection_cplusRectificationTypeFk` FOREIGN KEY (`cplusRectificationTypeFk`) REFERENCES `cplusRectificationType` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `invoiceInCorrection_invoiceCorrectionTypeFk` FOREIGN KEY (`invoiceCorrectionTypeFk`) REFERENCES `invoiceCorrectionType` (`id`) ON UPDATE CASCADE,
+ CONSTRAINT `invoiceInCorrection_siiTypeInvoiceIn` FOREIGN KEY (`siiTypeInvoiceInFk`) REFERENCES `siiTypeInvoiceIn` (`id`) ON UPDATE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+
diff --git a/db/versions/11369-azureChrysanthemum/00-firstScript.sql b/db/versions/11369-azureChrysanthemum/00-firstScript.sql
new file mode 100644
index 000000000..3a86c0c59
--- /dev/null
+++ b/db/versions/11369-azureChrysanthemum/00-firstScript.sql
@@ -0,0 +1,5 @@
+ALTER TABLE vn.duaInvoiceIn DROP KEY IF EXISTS duaFk_UNIQUE;
+ALTER TABLE vn.duaInvoiceIn DROP KEY IF EXISTS duaInvoiceIn_unique;
+ALTER TABLE vn.duaInvoiceIn ADD CONSTRAINT duaInvoiceIn_unique
+ UNIQUE KEY (invoiceInFk);
+
diff --git a/db/versions/11371-salmonRuscus/00-firstScript.sql b/db/versions/11371-salmonRuscus/00-firstScript.sql
new file mode 100644
index 000000000..306ec451e
--- /dev/null
+++ b/db/versions/11371-salmonRuscus/00-firstScript.sql
@@ -0,0 +1 @@
+ALTER TABLE vn.route ADD dated DATE;
\ No newline at end of file
diff --git a/db/versions/11371-salmonRuscus/01-firstScript.sql b/db/versions/11371-salmonRuscus/01-firstScript.sql
new file mode 100644
index 000000000..14c8989d8
--- /dev/null
+++ b/db/versions/11371-salmonRuscus/01-firstScript.sql
@@ -0,0 +1 @@
+UPDATE vn.route SET dated = created;
\ No newline at end of file
diff --git a/db/versions/11371-salmonRuscus/02-firstScript.sql b/db/versions/11371-salmonRuscus/02-firstScript.sql
new file mode 100644
index 000000000..42666b89c
--- /dev/null
+++ b/db/versions/11371-salmonRuscus/02-firstScript.sql
@@ -0,0 +1,2 @@
+ALTER TABLE vn.route
+MODIFY COLUMN dated DATE NOT NULL;
\ No newline at end of file
diff --git a/db/versions/11371-salmonRuscus/03-firstScript.sql b/db/versions/11371-salmonRuscus/03-firstScript.sql
new file mode 100644
index 000000000..b7776d31d
--- /dev/null
+++ b/db/versions/11371-salmonRuscus/03-firstScript.sql
@@ -0,0 +1,2 @@
+ALTER TABLE vn.route
+MODIFY COLUMN created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;
\ No newline at end of file
diff --git a/db/versions/11372-azureMedeola/00-firstScript.sql b/db/versions/11372-azureMedeola/00-firstScript.sql
new file mode 100644
index 000000000..53295e9f8
--- /dev/null
+++ b/db/versions/11372-azureMedeola/00-firstScript.sql
@@ -0,0 +1,2 @@
+INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId)
+ VALUES ('Worker','canCreateAbsenceInPast','WRITE','ALLOW','ROLE','hr');
diff --git a/db/versions/11373-pinkMastic/00-firstScript.sql b/db/versions/11373-pinkMastic/00-firstScript.sql
new file mode 100644
index 000000000..2d7cd4dc7
--- /dev/null
+++ b/db/versions/11373-pinkMastic/00-firstScript.sql
@@ -0,0 +1,107 @@
+INSERT IGNORE INTO vn.saySimpleCountry
+ SET countryFk = 1,
+ channel = '1320';
+
+UPDATE vn.saySimpleConfig
+ SET defaultChannel = '1819';
+
+INSERT IGNORE INTO pbx.prefix (country, prefix) VALUES
+ ('ES', '0034'),
+ ('IT', '0039'),
+ ('DE', '0049'),
+ ('RO', '0040'),
+ ('NL', '0031'),
+ ('BE', '0032'),
+ ('RU', '007'),
+ ('PT', '00351'),
+ ('LT', '00370'),
+ ('UA', '00380'),
+ ('CO', '0057'),
+ ('FI', '00358'),
+ ('EC', '00593'),
+ ('LB', '00961'),
+ ('IL', '00972'),
+ ('TH', '0066'),
+ ('PA', '00507'),
+ ('GB', '0044'),
+ ('FR', '0033'),
+ ('PL', '0048'),
+ ('MX', '0052'),
+ ('MA', '00212'),
+ ('AI', '001268'),
+ ('GH', '00233'),
+ ('SE', '0046'),
+ ('AE', '00971'),
+ ('KE', '00254'),
+ ('AD', '00376'),
+ ('AO', '00244'),
+ ('LU', '00352'),
+ ('BY', '00375'),
+ ('MD', '00373'),
+ ('DK', '0045'),
+ ('ET', '00251'),
+ ('AU', '0061'),
+ ('CA', '0001'),
+ ('CL', '0056'),
+ ('CN', '0086'),
+ ('CR', '00506'),
+ ('GT', '00502'),
+ ('CI', '00225'),
+ ('PE', '0051'),
+ ('LK', '0094'),
+ ('ZA', '0027'),
+ ('TR', '0090'),
+ ('ZW', '00263'),
+ ('MY', '0060'),
+ ('NZ', '0064'),
+ ('IE', '00353'),
+ ('MN', '00976'),
+ ('SV', '00503'),
+ ('ZM', '00260'),
+ ('JP', '0081'),
+ ('RW', '00250'),
+ ('AL', '00355'),
+ ('KW', '00965'),
+ ('SG', '0065'),
+ ('SR', '00597'),
+ ('KR', '0082'),
+ ('US', '0001'),
+ ('RS', '00381'),
+ ('AT', '0043'),
+ ('EG', '0020'),
+ ('LV', '00371'),
+ ('CY', '00357'),
+ ('CZ', '00420'),
+ ('BB', '001246'),
+ ('SK', '00421'),
+ ('IN', '0091'),
+ ('DZ', '00213'),
+ ('BR', '0055'),
+ ('GR', '0030'),
+ ('MC', '00377'),
+ ('SI', '00386'),
+ ('GP', '00590'),
+ ('NO', '0047'),
+ ('CH', '0041'),
+ ('AR', '0054'),
+ ('CU', '0053'),
+ ('GQ', '00240'),
+ ('GN', '00224'),
+ ('HN', '00504'),
+ ('ML', '00223'),
+ ('NI', '00505'),
+ ('PK', '0092'),
+ ('PY', '00595'),
+ ('SN', '00221'),
+ ('UY', '00598'),
+ ('VE', '0058'),
+ ('BG', '00359'),
+ ('GE', '00995'),
+ ('EE', '00372'),
+ ('SA', '00966'),
+ ('RN', '00234'),
+ ('HK', '00852'),
+ ('GI', '00350'),
+ ('CM', '00237'),
+ ('HU', '0036'),
+ ('AM', '00374');
\ No newline at end of file
diff --git a/db/versions/11375-navyIvy/00-firstScript.sql b/db/versions/11375-navyIvy/00-firstScript.sql
new file mode 100644
index 000000000..a90aaf519
--- /dev/null
+++ b/db/versions/11375-navyIvy/00-firstScript.sql
@@ -0,0 +1,2 @@
+ALTER TABLE vn.ticket DROP FOREIGN KEY tickets_zone_fk;
+ALTER TABLE vn.ticket ADD CONSTRAINT tickets_zone_fk FOREIGN KEY (zoneFk) REFERENCES vn.`zone`(id) ON DELETE SET NULL ON UPDATE CASCADE;
diff --git a/db/versions/11376-pinkBamboo/00-firstScript.sql b/db/versions/11376-pinkBamboo/00-firstScript.sql
new file mode 100644
index 000000000..0c1e71a2f
--- /dev/null
+++ b/db/versions/11376-pinkBamboo/00-firstScript.sql
@@ -0,0 +1,2 @@
+ALTER TABLE vn.`zone` MODIFY COLUMN `price` DECIMAL(10,2);
+
diff --git a/db/versions/11377-pinkCarnation/00-firstScript.sql b/db/versions/11377-pinkCarnation/00-firstScript.sql
new file mode 100644
index 000000000..fdbd7e836
--- /dev/null
+++ b/db/versions/11377-pinkCarnation/00-firstScript.sql
@@ -0,0 +1,5 @@
+-- Place your SQL code here
+
+
+ALTER TABLE vn.productionConfig ADD IF NOT EXISTS itemOrderReviewHours int(11) DEFAULT 24 NULL
+COMMENT 'Horas que no se tienen en cuenta para comprobar orden en el almacén, null para desactivar revisión';
diff --git a/db/versions/11378-orangeAsparagus/00-firstScript.sql b/db/versions/11378-orangeAsparagus/00-firstScript.sql
new file mode 100644
index 000000000..a030b7e05
--- /dev/null
+++ b/db/versions/11378-orangeAsparagus/00-firstScript.sql
@@ -0,0 +1 @@
+DROP TABLE vn.quadmindsApiConfig;
diff --git a/db/versions/11379-yellowCordyline/00-firstScript.sql b/db/versions/11379-yellowCordyline/00-firstScript.sql
new file mode 100644
index 000000000..8d90ee90c
--- /dev/null
+++ b/db/versions/11379-yellowCordyline/00-firstScript.sql
@@ -0,0 +1,20 @@
+CREATE TABLE `vn`.`osrmConfig` (
+ `id` int(10) unsigned NOT NULL,
+ `url` varchar(100) NOT NULL COMMENT 'Dirección base de la API',
+ `tolerance` decimal(6,6) NOT NULL DEFAULT 0 COMMENT 'Tolerancia entre las coordenadas enviadas y las retornadas',
+ PRIMARY KEY (`id`),
+ CONSTRAINT `osrmConfig_check` CHECK (`id` = 1)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
+
+-- Para que no de error al añadir la FK de zone
+UPDATE vn.zone
+ SET price = 0.1
+ WHERE price = 0;
+
+ALTER TABLE vn.`zone`
+ ADD addressFk int(11) DEFAULT NULL COMMENT 'Punto de distribución de donde salen para repartir',
+ ADD CONSTRAINT zone_address_FK FOREIGN KEY (addressFk) REFERENCES vn.address(id) ON DELETE RESTRICT ON UPDATE CASCADE;
+
+ALTER TABLE vn.zoneConfig
+ ADD defaultAddressFk int(11) DEFAULT NULL NULL COMMENT 'Punto de distribución por defecto',
+ ADD CONSTRAINT zoneConfig_address_FK FOREIGN KEY (defaultAddressFk) REFERENCES vn.address(id) ON DELETE RESTRICT ON UPDATE CASCADE;
diff --git a/db/versions/11379-yellowCordyline/01-secScript.sql b/db/versions/11379-yellowCordyline/01-secScript.sql
new file mode 100644
index 000000000..30479229e
--- /dev/null
+++ b/db/versions/11379-yellowCordyline/01-secScript.sql
@@ -0,0 +1,5 @@
+INSERT IGNORE INTO salix.ACL (model,property,accessType,permission,principalType,principalId)
+ VALUES ('OsrmConfig','optimize','READ','ALLOW','ROLE','employee'),
+ ('Route', 'optimizePriority','*','ALLOW','ROLE','employee');
+INSERT IGNORE INTO vn.osrmConfig (id,url,tolerance)
+ VALUES (1,'https://router.project-osrm.org', 0.002);
diff --git a/db/versions/11384-grayAnthurium/00-firstScript.sql b/db/versions/11384-grayAnthurium/00-firstScript.sql
new file mode 100644
index 000000000..b3a7f3da2
--- /dev/null
+++ b/db/versions/11384-grayAnthurium/00-firstScript.sql
@@ -0,0 +1,3 @@
+ALTER TABLE vn.mistakeType
+ ADD `time` int(10) NULL COMMENT 'Segundos que se suelen tardar en arreglar el fallo',
+ ADD code varchar(50) DEFAULT NULL NULL AFTER id;
diff --git a/db/versions/11385-yellowOrchid/00-firstScript.sql b/db/versions/11385-yellowOrchid/00-firstScript.sql
new file mode 100644
index 000000000..287e9fcab
--- /dev/null
+++ b/db/versions/11385-yellowOrchid/00-firstScript.sql
@@ -0,0 +1,5 @@
+RENAME TABLE vn.inventoryFailure TO vn.inventoryFailure__;
+ALTER TABLE vn.inventoryFailure__ COMMENT='@deprecated 2024-12-16';
+
+RENAME TABLE vn.inventoryFailureCause TO vn.inventoryFailureCause__;
+ALTER TABLE vn.inventoryFailureCause__ COMMENT='@deprecated 2024-12-16';
diff --git a/db/versions/11390-goldenPalmetto/00-firstScript.sql b/db/versions/11390-goldenPalmetto/00-firstScript.sql
new file mode 100644
index 000000000..adcc76e4f
--- /dev/null
+++ b/db/versions/11390-goldenPalmetto/00-firstScript.sql
@@ -0,0 +1,3 @@
+
+ALTER TABLE vn.country
+ ADD CONSTRAINT country_unique_name UNIQUE KEY (name);
diff --git a/db/versions/11391-redPalmetto/00-itemAlter.sql b/db/versions/11391-redPalmetto/00-itemAlter.sql
new file mode 100644
index 000000000..fc47d5fc0
--- /dev/null
+++ b/db/versions/11391-redPalmetto/00-itemAlter.sql
@@ -0,0 +1,2 @@
+ALTER TABLE `vn`.`item`
+ADD COLUMN `isCustomInspectionRequired` TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Indicates if the item requires physical inspection at customs';
diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js
index 0a3892c86..52177b231 100644
--- a/e2e/helpers/selectors.js
+++ b/e2e/helpers/selectors.js
@@ -791,7 +791,7 @@ export default {
},
createRouteView: {
worker: 'vn-route-create vn-worker-autocomplete[ng-model="$ctrl.route.workerFk"]',
- createdDatePicker: 'vn-route-create vn-date-picker[ng-model="$ctrl.route.created"]',
+ createdDatePicker: 'vn-route-create vn-date-picker[ng-model="$ctrl.route.dated"]',
vehicleAuto: 'vn-route-create vn-autocomplete[ng-model="$ctrl.route.vehicleFk"]',
agency: 'vn-route-create vn-autocomplete[ng-model="$ctrl.route.agencyModeFk"]',
description: 'vn-route-create [ng-model="$ctrl.route.description"]',
diff --git a/e2e/paths/02-client/08_add_notes.spec.js b/e2e/paths/02-client/08_add_notes.spec.js
deleted file mode 100644
index d0c483a11..000000000
--- a/e2e/paths/02-client/08_add_notes.spec.js
+++ /dev/null
@@ -1,42 +0,0 @@
-import selectors from '../../helpers/selectors';
-import getBrowser from '../../helpers/puppeteer';
-
-describe('Client Add notes path', () => {
- let browser;
- let page;
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('employee', 'client');
- await page.accessToSearchResult('Bruce Banner');
- await page.accessToSection('client.card.note.index');
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it(`should reach the notes index`, async() => {
- await page.waitForState('client.card.note.index');
- });
-
- it(`should click on the add note button`, async() => {
- await page.waitToClick(selectors.clientNotes.addNoteFloatButton);
- await page.waitForState('client.card.note.create');
- });
-
- it(`should create a note`, async() => {
- await page.waitForSelector(selectors.clientNotes.note);
- await page.type(`${selectors.clientNotes.note} textarea`, 'Meeting with Black Widow 21st 9am');
- await page.waitToClick(selectors.clientNotes.saveButton);
- const message = await page.waitForSnackbar();
-
- expect(message.text).toContain('Data saved!');
- });
-
- it('should confirm the note was created', async() => {
- const result = await page.waitToGetProperty(selectors.clientNotes.firstNoteText, 'innerText');
-
- expect(result).toEqual('Meeting with Black Widow 21st 9am');
- });
-});
diff --git a/e2e/paths/02-client/21_defaulter.spec.js b/e2e/paths/02-client/21_defaulter.spec.js
index 2bb3d6254..01f394bc8 100644
--- a/e2e/paths/02-client/21_defaulter.spec.js
+++ b/e2e/paths/02-client/21_defaulter.spec.js
@@ -28,12 +28,12 @@ describe('Client defaulter path', () => {
const salesPersonName =
await page.waitToGetProperty(selectors.clientDefaulter.firstSalesPersonName, 'innerText');
- expect(clientName).toEqual('Bruce Banner');
- expect(salesPersonName).toEqual('developer');
+ expect(clientName).toEqual('Ororo Munroe');
+ expect(salesPersonName).toEqual('salesperson');
});
it('should first observation not changed', async() => {
- const expectedObservation = 'Meeting with Black Widow 21st 9am';
+ const expectedObservation = 'Madness, as you know, is like gravity, all it takes is a little push';
const result = await page.waitToGetProperty(selectors.clientDefaulter.firstObservation, 'value');
expect(result).toContain(expectedObservation);
@@ -62,13 +62,4 @@ describe('Client defaulter path', () => {
await page.write(selectors.clientDefaulter.observation, 'My new observation');
await page.waitToClick(selectors.clientDefaulter.saveButton);
});
-
- it('should first observation changed', async() => {
- const message = await page.waitForSnackbar();
- await page.waitForSelector(selectors.clientDefaulter.firstObservation);
- const result = await page.waitToGetProperty(selectors.clientDefaulter.firstObservation, 'value');
-
- expect(message.text).toContain('Observation saved!');
- expect(result).toContain('My new observation');
- });
});
diff --git a/e2e/paths/07-order/01_summary.spec.js b/e2e/paths/07-order/01_summary.spec.js
deleted file mode 100644
index 9df481ef6..000000000
--- a/e2e/paths/07-order/01_summary.spec.js
+++ /dev/null
@@ -1,46 +0,0 @@
-import getBrowser from '../../helpers/puppeteer';
-
-const $ = {
- id: 'vn-order-summary vn-one:nth-child(1) > vn-label-value:nth-child(1) span',
- alias: 'vn-order-summary vn-one:nth-child(1) > vn-label-value:nth-child(2) span',
- consignee: 'vn-order-summary vn-one:nth-child(2) > vn-label-value:nth-child(6) span',
- subtotal: 'vn-order-summary vn-one.taxes > p:nth-child(1)',
- vat: 'vn-order-summary vn-one.taxes > p:nth-child(2)',
- total: 'vn-order-summary vn-one.taxes > p:nth-child(3)',
- sale: 'vn-order-summary vn-tbody > vn-tr',
-};
-
-describe('Order summary path', () => {
- let browser;
- let page;
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('employee', 'order');
- await page.accessToSearchResult('16');
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it('should reach the order summary section and check data', async() => {
- await page.waitForState('order.card.summary');
-
- const id = await page.innerText($.id);
- const alias = await page.innerText($.alias);
- const consignee = await page.innerText($.consignee);
- const subtotal = await page.innerText($.subtotal);
- const vat = await page.innerText($.vat);
- const total = await page.innerText($.total);
- const sale = await page.countElement($.sale);
-
- expect(id).toEqual('16');
- expect(alias).toEqual('Many places');
- expect(consignee).toEqual('address 26 - Gotham (Province one)');
- expect(subtotal.length).toBeGreaterThan(1);
- expect(vat.length).toBeGreaterThan(1);
- expect(total.length).toBeGreaterThan(1);
- expect(sale).toBeGreaterThan(0);
- });
-});
diff --git a/e2e/paths/07-order/02_basic_data.spec.js b/e2e/paths/07-order/02_basic_data.spec.js
deleted file mode 100644
index b2c21b071..000000000
--- a/e2e/paths/07-order/02_basic_data.spec.js
+++ /dev/null
@@ -1,69 +0,0 @@
-import selectors from '../../helpers/selectors.js';
-import getBrowser from '../../helpers/puppeteer';
-
-const $ = {
- form: 'vn-order-basic-data form',
- observation: 'vn-order-basic-data form [vn-name="note"]',
- saveButton: `vn-order-basic-data form button[type=submit]`,
- acceptButton: '.vn-confirm.shown button[response="accept"]'
-};
-
-describe('Order edit basic data path', () => {
- let browser;
- let page;
-
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
-
- await page.loginAndModule('employee', 'order');
- await page.accessToSearchResult('1');
- await page.accessToSection('order.card.basicData');
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- describe('when confirmed order', () => {
- it('should not be able to change the client', async() => {
- const message = await page.sendForm($.form, {
- client: 'Tony Stark',
- address: 'Tony Stark',
- });
-
- expect(message.text).toContain(`You can't make changes on the basic data`);
- });
- });
-
- describe('when new order', () => {
- it('should create an order and edit its basic data', async() => {
- await page.waitToClick(selectors.globalItems.returnToModuleIndexButton);
- await page.waitToClick($.acceptButton);
- await page.waitForContentLoaded();
- await page.waitToClick(selectors.ordersIndex.createOrderButton);
- await page.waitForState('order.create');
-
- await page.autocompleteSearch(selectors.createOrderView.client, 'Jessica Jones');
- await page.pickDate(selectors.createOrderView.landedDatePicker);
- await page.autocompleteSearch(selectors.createOrderView.agency, 'Other agency');
- await page.waitToClick(selectors.createOrderView.createButton);
- await page.waitForState('order.card.catalog');
-
- await page.accessToSection('order.card.basicData');
-
- const values = {
- client: 'Tony Stark',
- address: 'Tony Stark',
- agencyMode: 'Other agency'
- };
-
- const message = await page.sendForm($.form, values);
- await page.reloadSection('order.card.basicData');
- const formValues = await page.fetchForm($.form, Object.keys(values));
-
- expect(message.isSuccess).toBeTrue();
- expect(formValues).toEqual(values);
- });
- });
-});
diff --git a/e2e/paths/07-order/03_lines.spec.js b/e2e/paths/07-order/03_lines.spec.js
deleted file mode 100644
index 718ea5ce5..000000000
--- a/e2e/paths/07-order/03_lines.spec.js
+++ /dev/null
@@ -1,48 +0,0 @@
-import selectors from '../../helpers/selectors.js';
-import getBrowser from '../../helpers/puppeteer';
-
-describe('Order lines', () => {
- let browser;
- let page;
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('employee', 'order');
- await page.accessToSearchResult('8');
- await page.accessToSection('order.card.line');
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it('should check the order subtotal', async() => {
- const result = await page
- .waitToGetProperty(selectors.orderLine.orderSubtotal, 'innerText');
-
- expect(result).toContain('112.30');
- });
-
- it('should delete the first line in the order', async() => {
- await page.waitToClick(selectors.orderLine.firstLineDeleteButton);
- await page.waitToClick(selectors.orderLine.confirmButton);
- const message = await page.waitForSnackbar();
-
- expect(message.text).toContain('Data saved!');
- });
-
- it('should confirm the order subtotal has changed', async() => {
- await page.waitForTextInElement(selectors.orderLine.orderSubtotal, '92.80');
- const result = await page
- .waitToGetProperty(selectors.orderLine.orderSubtotal, 'innerText');
-
- expect(result).toContain('92.80');
- });
-
- it('should confirm the whole order and redirect to ticket index filtered by clientFk', async() => {
- await page.waitToClick(selectors.orderLine.confirmOrder);
-
- await page.expectURL('ticket/index');
- await page.expectURL('clientFk');
- });
-});
diff --git a/e2e/paths/07-order/04_catalog.spec.js b/e2e/paths/07-order/04_catalog.spec.js
deleted file mode 100644
index b8a20e938..000000000
--- a/e2e/paths/07-order/04_catalog.spec.js
+++ /dev/null
@@ -1,97 +0,0 @@
-import selectors from '../../helpers/selectors.js';
-import getBrowser from '../../helpers/puppeteer';
-
-describe('Order catalog', () => {
- let browser;
- let page;
-
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('employee', 'order');
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it('should open the create new order form', async() => {
- await page.waitToClick(selectors.ordersIndex.createOrderButton);
- await page.waitForState('order.create');
- });
-
- it('should create a new order', async() => {
- await page.autocompleteSearch(selectors.createOrderView.client, 'Tony Stark');
- await page.pickDate(selectors.createOrderView.landedDatePicker);
- await page.autocompleteSearch(selectors.createOrderView.agency, 'Other agency');
- await page.waitToClick(selectors.createOrderView.createButton);
- await page.waitForState('order.card.catalog');
- });
-
- it('should add the realm and type filters and obtain results', async() => {
- await page.waitToClick(selectors.orderCatalog.plantRealmButton);
- await page.autocompleteSearch(selectors.orderCatalog.type, 'Anthurium');
- await page.waitForNumberOfElements('section.product', 4);
- const result = await page.countElement('section.product');
-
- expect(result).toEqual(4);
- });
-
- it('should perfom an "OR" search for the item tag colors silver and brown', async() => {
- await page.waitToClick(selectors.orderCatalog.openTagSearch);
- await page.autocompleteSearch(selectors.orderCatalog.tag, 'Color');
- await page.autocompleteSearch(selectors.orderCatalog.firstTagAutocomplete, 'silver');
- await page.waitToClick(selectors.orderCatalog.addTagButton);
- await page.autocompleteSearch(selectors.orderCatalog.secondTagAutocomplete, 'brown');
- await page.waitToClick(selectors.orderCatalog.searchTagButton);
- await page.waitForNumberOfElements('section.product', 4);
- });
-
- it('should perfom an "OR" search for the item tag tallos 2 and 9', async() => {
- await page.waitToClick(selectors.orderCatalog.openTagSearch);
- await page.autocompleteSearch(selectors.orderCatalog.tag, 'Tallos');
- await page.write(selectors.orderCatalog.firstTagValue, '2');
- await page.waitToClick(selectors.orderCatalog.addTagButton);
- await page.write(selectors.orderCatalog.secondTagValue, '9');
- await page.waitToClick(selectors.orderCatalog.searchTagButton);
- await page.waitForNumberOfElements('section.product', 2);
- });
-
- it('should perform a general search for category', async() => {
- await page.write(selectors.orderCatalog.itemTagValue, 'concussion');
- await page.keyboard.press('Enter');
- await page.waitForNumberOfElements('section.product', 2);
- });
-
- it('should perfom an "AND" search for the item tag tallos 2', async() => {
- await page.waitToClick(selectors.orderCatalog.openTagSearch);
- await page.autocompleteSearch(selectors.orderCatalog.tag, 'Tallos');
- await page.write(selectors.orderCatalog.firstTagValue, '2');
- await page.waitToClick(selectors.orderCatalog.searchTagButton);
- await page.waitForNumberOfElements('section.product', 1);
- });
-
- it('should remove the tag filters and have 4 results', async() => {
- await page.waitForContentLoaded();
- await page.waitToClick(selectors.orderCatalog.sixthFilterRemoveButton);
- await page.waitForContentLoaded();
- await page.waitToClick(selectors.orderCatalog.fifthFilterRemoveButton);
- await page.waitForContentLoaded();
- await page.waitToClick(selectors.orderCatalog.fourthFilterRemoveButton);
- await page.waitForContentLoaded();
- await page.waitToClick(selectors.orderCatalog.thirdFilterRemoveButton);
-
- await page.waitForNumberOfElements('.product', 4);
- const result = await page.countElement('section.product');
-
- expect(result).toEqual(4);
- });
-
- it('should search for an item by id', async() => {
- await page.accessToSearchResult('2');
- await page.waitForNumberOfElements('section.product', 1);
- const result = await page.countElement('section.product');
-
- expect(result).toEqual(1);
- });
-});
diff --git a/e2e/paths/07-order/05_index.spec.js b/e2e/paths/07-order/05_index.spec.js
deleted file mode 100644
index 23769766c..000000000
--- a/e2e/paths/07-order/05_index.spec.js
+++ /dev/null
@@ -1,34 +0,0 @@
-import selectors from '../../helpers/selectors.js';
-import getBrowser from '../../helpers/puppeteer';
-
-describe('Order Index', () => {
- let browser;
- let page;
-
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('employee', 'order');
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it(`should check the second search result doesn't contain a total of 0€`, async() => {
- await page.waitToClick(selectors.globalItems.searchButton);
- const result = await page.waitToGetProperty(selectors.ordersIndex.secondSearchResultTotal, 'innerText');
-
- expect(result).not.toContain('0.00');
- });
-
- it('should search including empty orders', async() => {
- await page.waitToClick(selectors.ordersIndex.openAdvancedSearch);
- await page.waitToClick(selectors.ordersIndex.advancedSearchShowEmptyCheckbox);
- await page.waitToClick(selectors.ordersIndex.advancedSearchButton);
- await page.waitForTextInElement(selectors.ordersIndex.secondSearchResultTotal, '0.00');
- const result = await page.waitToGetProperty(selectors.ordersIndex.secondSearchResultTotal, 'innerText');
-
- expect(result).toContain('0.00');
- });
-});
diff --git a/e2e/paths/10-travel/01_create.spec.js b/e2e/paths/10-travel/01_create.spec.js
deleted file mode 100644
index 98ade4852..000000000
--- a/e2e/paths/10-travel/01_create.spec.js
+++ /dev/null
@@ -1,42 +0,0 @@
-import selectors from '../../helpers/selectors.js';
-import getBrowser from '../../helpers/puppeteer';
-
-describe('Travel create path', () => {
- let browser;
- let page;
-
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('buyer', 'travel');
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it('should create a new travel and check it was created with the correct data', async() => {
- const date = Date.vnNew();
- date.setDate(15);
- date.setUTCHours(0, 0, 0, 0);
-
- await page.waitToClick(selectors.travelIndex.newTravelButton);
- await page.waitForState('travel.create');
-
- const values = {
- reference: 'Testing reference',
- agencyMode: 'inhouse pickup',
- shipped: date,
- landed: date,
- warehouseOut: 'Warehouse One',
- warehouseIn: 'Warehouse Five'
- };
-
- const message = await page.sendForm('vn-travel-create form', values);
- await page.waitForState('travel.card.basicData');
- const formValues = await page.fetchForm('vn-travel-basic-data form', Object.keys(values));
-
- expect(message.isSuccess).toBeTrue();
- expect(formValues).toEqual(values);
- });
-});
diff --git a/e2e/paths/10-travel/02_basic_data_and_log.spec.js b/e2e/paths/10-travel/02_basic_data_and_log.spec.js
deleted file mode 100644
index 701e6b1b4..000000000
--- a/e2e/paths/10-travel/02_basic_data_and_log.spec.js
+++ /dev/null
@@ -1,97 +0,0 @@
-import selectors from '../../helpers/selectors.js';
-import getBrowser from '../../helpers/puppeteer';
-
-describe('Travel basic data path', () => {
- let browser;
- let page;
-
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('buyer', 'travel');
- await page.write(selectors.travelIndex.generalSearchFilter, '3');
- await page.keyboard.press('Enter');
- await page.accessToSection('travel.card.basicData');
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it('should reach the thermograph section', async() => {
- await page.waitForState('travel.card.basicData');
- });
-
- it('should set a wrong delivery date then receive an error on submit', async() => {
- await page.loginAndModule('buyer', 'travel');
- await page.write(selectors.travelIndex.generalSearchFilter, '4');
- await page.keyboard.press('Enter');
- await page.accessToSection('travel.card.basicData');
- await page.waitForState('travel.card.basicData');
-
- const lastMonth = Date.vnNew();
- lastMonth.setMonth(lastMonth.getMonth() - 2);
-
- await page.pickDate(selectors.travelBasicData.deliveryDate, lastMonth);
- await page.waitToClick(selectors.travelBasicData.save);
- const message = await page.waitForSnackbar();
-
- expect(message.text).toContain('Landing cannot be lesser than shipment');
- });
-
- it('should undo the changes', async() => {
- await page.clearInput(selectors.travelBasicData.reference);
- await page.write(selectors.travelBasicData.reference, 'totally pointless ref');
- await page.waitToClick(selectors.travelBasicData.undoChanges);
- const result = await page.waitToGetProperty(selectors.travelBasicData.reference, 'value');
-
- expect(result).toEqual('fourth travel');
- });
-
- it('should now edit the whole form then save', async() => {
- await page.clearInput(selectors.travelBasicData.reference);
- await page.write(selectors.travelBasicData.reference, 'new reference!');
- await page.autocompleteSearch(selectors.travelBasicData.agency, 'Entanglement');
- await page.autocompleteSearch(selectors.travelBasicData.outputWarehouse, 'Warehouse Three');
- await page.autocompleteSearch(selectors.travelBasicData.inputWarehouse, 'Warehouse Four');
- await page.waitToClick(selectors.travelBasicData.delivered);
- await page.waitToClick(selectors.travelBasicData.received);
- await page.waitToClick(selectors.travelBasicData.save);
- const message = await page.waitForSnackbar();
-
- expect(message.text).toContain('Data saved!');
- });
-
- it('should reload the section and check the reference was saved', async() => {
- await page.reloadSection('travel.card.basicData');
- const result = await page.waitToGetProperty(selectors.travelBasicData.reference, 'value');
-
- expect(result).toEqual('new reference!');
- });
-
- it('should check the agency was saved', async() => {
- const result = await page.waitToGetProperty(selectors.travelBasicData.agency, 'value');
-
- expect(result).toEqual('Entanglement');
- });
-
- it('should check the output warehouse date was saved', async() => {
- const result = await page.waitToGetProperty(selectors.travelBasicData.outputWarehouse, 'value');
-
- expect(result).toEqual('Warehouse Three');
- });
-
- it('should check the input warehouse date was saved', async() => {
- const result = await page.waitToGetProperty(selectors.travelBasicData.inputWarehouse, 'value');
-
- expect(result).toEqual('Warehouse Four');
- });
-
- it(`should check the delivered checkbox was saved even tho it doesn't make sense`, async() => {
- await page.waitForClassPresent(selectors.travelBasicData.delivered, 'checked');
- });
-
- it(`should check the received checkbox was saved even tho it doesn't make sense`, async() => {
- await page.waitForClassPresent(selectors.travelBasicData.received, 'checked');
- });
-});
diff --git a/e2e/paths/10-travel/03_descriptor.spec.js b/e2e/paths/10-travel/03_descriptor.spec.js
deleted file mode 100644
index f066a74ca..000000000
--- a/e2e/paths/10-travel/03_descriptor.spec.js
+++ /dev/null
@@ -1,36 +0,0 @@
-import selectors from '../../helpers/selectors.js';
-import getBrowser from '../../helpers/puppeteer';
-
-describe('Travel descriptor path', () => {
- let browser;
- let page;
-
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('buyer', 'travel');
- await page.write(selectors.travelIndex.generalSearchFilter, '3');
- await page.keyboard.press('Enter');
- await page.waitForState('travel.card.summary');
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it('should click the descriptor button to navigate to the travel index showing all travels with current agency', async() => {
- await page.waitToClick(selectors.travelDescriptor.filterByAgencyButton);
- await page.waitForState('travel.index');
- const result = await page.countElement(selectors.travelIndex.anySearchResult);
-
- expect(result).toBeGreaterThanOrEqual(1);
- });
-
- it('should navigate to the first search result', async() => {
- await page.waitToClick(selectors.travelIndex.firstSearchResult);
- await page.waitForState('travel.card.summary');
- const state = await page.getState();
-
- expect(state).toBe('travel.card.summary');
- });
-});
diff --git a/e2e/paths/10-travel/04_extra_community.spec.js b/e2e/paths/10-travel/04_extra_community.spec.js
deleted file mode 100644
index c5975c958..000000000
--- a/e2e/paths/10-travel/04_extra_community.spec.js
+++ /dev/null
@@ -1,42 +0,0 @@
-import selectors from '../../helpers/selectors.js';
-import getBrowser from '../../helpers/puppeteer';
-
-describe('Travel extra community path', () => {
- let browser;
- let page;
-
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('buyer', 'travel');
- await page.accessToSection('travel.extraCommunity');
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it('should edit the travel reference and the locked kilograms', async() => {
- await page.waitToClick(selectors.travelExtraCommunity.removeContinentFilter);
- await page.waitForSpinnerLoad();
- await page.writeOnEditableTD(selectors.travelExtraCommunity.firstTravelReference, 'edited reference');
- await page.waitForSpinnerLoad();
- await page.writeOnEditableTD(selectors.travelExtraCommunity.firstTravelLockedKg, '1500');
-
- const message = await page.waitForSnackbar();
-
- expect(message.text).toContain('Data saved!');
- });
-
- it('should reload the index and confirm the reference and locked kg were edited', async() => {
- await page.accessToSection('travel.index');
- await page.accessToSection('travel.extraCommunity');
- await page.waitToClick(selectors.travelExtraCommunity.removeContinentFilter);
- await page.waitForTextInElement(selectors.travelExtraCommunity.firstTravelReference, 'edited reference');
- const reference = await page.getProperty(selectors.travelExtraCommunity.firstTravelReference, 'innerText');
- const lockedKg = await page.getProperty(selectors.travelExtraCommunity.firstTravelLockedKg, 'innerText');
-
- expect(reference).toContain('edited reference');
- expect(lockedKg).toContain(1500);
- });
-});
diff --git a/e2e/paths/10-travel/06_search_panel.spec.js b/e2e/paths/10-travel/06_search_panel.spec.js
deleted file mode 100644
index 420ceaf48..000000000
--- a/e2e/paths/10-travel/06_search_panel.spec.js
+++ /dev/null
@@ -1,62 +0,0 @@
-import selectors from '../../helpers/selectors.js';
-import getBrowser from '../../helpers/puppeteer';
-
-describe('Travel search panel path', () => {
- let browser;
- let page;
- let httpRequest;
-
- beforeAll(async() => {
- browser = await getBrowser();
- page = browser.page;
- await page.loginAndModule('buyer', 'travel');
- page.on('request', req => {
- if (req.url().includes(`Travels/filter`))
- httpRequest = req.url();
- });
- });
-
- afterAll(async() => {
- await browser.close();
- });
-
- it('should filter using all the fields', async() => {
- await page.click(selectors.travelIndex.chip);
- await page.write(selectors.travelIndex.generalSearchFilter, 'travel');
- await page.keyboard.press('Enter');
-
- expect(httpRequest).toContain('search=travel');
-
- await page.click(selectors.travelIndex.chip);
- await page.autocompleteSearch(selectors.travelIndex.agencyFilter, 'Entanglement');
-
- expect(httpRequest).toContain('agencyModeFk');
-
- await page.click(selectors.travelIndex.chip);
- await page.autocompleteSearch(selectors.travelIndex.warehouseOutFilter, 'Warehouse One');
-
- expect(httpRequest).toContain('warehouseOutFk');
-
- await page.click(selectors.travelIndex.chip);
- await page.autocompleteSearch(selectors.travelIndex.warehouseInFilter, 'Warehouse Two');
-
- expect(httpRequest).toContain('warehouseInFk');
-
- await page.click(selectors.travelIndex.chip);
- await page.overwrite(selectors.travelIndex.scopeDaysFilter, '15');
- await page.keyboard.press('Enter');
-
- expect(httpRequest).toContain('scopeDays=15');
-
- await page.click(selectors.travelIndex.chip);
- await page.autocompleteSearch(selectors.travelIndex.continentFilter, 'Asia');
-
- expect(httpRequest).toContain('continent');
-
- await page.click(selectors.travelIndex.chip);
- await page.write(selectors.travelIndex.totalEntriesFilter, '1');
- await page.keyboard.press('Enter');
-
- expect(httpRequest).toContain('totalEntries=1');
- });
-});
diff --git a/front/core/components/snackbar/snackbar.js b/front/core/components/snackbar/snackbar.js
index b380c47c3..cce285d14 100644
--- a/front/core/components/snackbar/snackbar.js
+++ b/front/core/components/snackbar/snackbar.js
@@ -27,18 +27,6 @@ export default class Controller extends Component {
setTimeout(() => element.classList.add('shown'), 30);
shape.element = element;
- if (data.additionalData && this.vnToken.token) {
- this.additionalData = data.additionalData;
- let supportButton = document.createElement('i');
- supportButton.setAttribute('class', 'material-icons clickable');
- supportButton.addEventListener('click', () => this.$.supportDialog.show());
- element.appendChild(supportButton);
-
- let buttonIcon = 'support_agent';
- buttonIcon = document.createTextNode(buttonIcon);
- supportButton.appendChild(buttonIcon);
- }
-
if (shape.type)
element.classList.add(shape.type);
diff --git a/front/core/components/support-dialog/index.js b/front/core/components/support-dialog/index.js
index d15c14b4a..82f086184 100644
--- a/front/core/components/support-dialog/index.js
+++ b/front/core/components/support-dialog/index.js
@@ -9,13 +9,6 @@ export default class Controller extends Dialog {
responseHandler(response) {
if (response !== 'accept')
return super.responseHandler(response);
-
- this.$http.post('Ostickets/send-to-support', {
- reason: this.reason,
- additionalData: this.additionalData
- })
- .then(() => super.responseHandler(response))
- .then(() => this.vnApp.showSuccess(this.$t('Email sended!')));
}
}
diff --git a/front/core/services/app.js b/front/core/services/app.js
index b8fcc43e1..816167835 100644
--- a/front/core/services/app.js
+++ b/front/core/services/app.js
@@ -66,10 +66,24 @@ export default class App {
]}
};
-
- if (this.logger.$params.q)
- newRoute = newRoute.concat(`?table=${this.logger.$params.q}`);
+ const hasId = !isNaN(parseInt(route.split('/')[1]));
+ if (this.logger.$params.q) {
+ let tableValue = this.logger.$params.q;
+ if (Array.isArray(tableValue)) {
+ const [key, param1, param2] = tableValue;
+ const payload = key === 'createForm'
+ ? {[param1]: param2}
+ : {[key]: param1};
+ newRoute += `?${key}=${JSON.stringify(payload)}`;
+ } else {
+ const q = JSON.parse(tableValue);
+ if (typeof q === 'number')
+ tableValue = JSON.stringify({id: tableValue});
+ newRoute = newRoute.concat(`?table=${tableValue}`);
+ }
+ } else if (!hasId && this.logger.$params.id && newRoute.indexOf(this.logger.$params.id) < 0)
+ newRoute = newRoute.concat(`${this.logger.$params.id}`);
return this.logger.$http.get('Urls/findOne', {filter})
.then(res => {
diff --git a/loopback/common/methods/vn-model/printService.js b/loopback/common/methods/vn-model/printService.js
index 12a6a67cc..ed784229b 100644
--- a/loopback/common/methods/vn-model/printService.js
+++ b/loopback/common/methods/vn-model/printService.js
@@ -2,7 +2,7 @@ const {Report, Email} = require('vn-print');
module.exports = Self => {
Self.printReport = async function(ctx, id, reportName) {
- const args = Object.assign({}, ctx.args);
+ const args = Object.assign({id}, ctx.args);
const params = {lang: ctx.req.getLocale()};
delete args.ctx;
diff --git a/loopback/locale/en.json b/loopback/locale/en.json
index ea84cb6eb..80da13ae5 100644
--- a/loopback/locale/en.json
+++ b/loopback/locale/en.json
@@ -223,7 +223,6 @@
"Shelving not valid": "Shelving not valid",
"printerNotExists": "The printer does not exist",
"There are not picking tickets": "There are not picking tickets",
- "ticketCommercial": "The ticket {{ ticket }} for the salesperson {{ salesMan }} is in preparation. (automatically generated message)",
"This password can only be changed by the user themselves": "This password can only be changed by the user themselves",
"They're not your subordinate": "They're not your subordinate",
"InvoiceIn is already booked": "InvoiceIn is already booked",
@@ -240,5 +239,16 @@
"There is already a tray with the same height": "There is already a tray with the same height",
"The height must be greater than 50cm": "The height must be greater than 50cm",
"The maximum height of the wagon is 200cm": "The maximum height of the wagon is 200cm",
- "The quantity claimed cannot be greater than the quantity of the line": "The quantity claimed cannot be greater than the quantity of the line"
-}
+ "The quantity claimed cannot be greater than the quantity of the line": "The quantity claimed cannot be greater than the quantity of the line",
+ "There are tickets for this area, delete them first": "There are tickets for this area, delete them first",
+ "You do not have permission to modify the booked field": "You do not have permission to modify the booked field",
+ "Invalid or expired verification code": "Invalid or expired verification code",
+ "ticketLostExpedition": "The ticket [{{ticketId}}]({{{ticketUrl}}}) has the following lost expedition:{{ expeditionId }}",
+ "The raid information is not correct": "The raid information is not correct",
+ "Payment method is required": "Payment method is required",
+ "Sales already moved": "Sales already moved",
+ "Holidays to past days not available": "Holidays to past days not available",
+ "Price cannot be blank": "Price cannot be blank",
+ "There are tickets to be invoiced": "There are tickets to be invoiced",
+ "The address of the customer must have information about Incoterms and Customs Agent": "The address of the customer must have information about Incoterms and Customs Agent"
+}
\ No newline at end of file
diff --git a/loopback/locale/es.json b/loopback/locale/es.json
index 796c945e8..fcee0e111 100644
--- a/loopback/locale/es.json
+++ b/loopback/locale/es.json
@@ -350,6 +350,7 @@
"Cmr file does not exist": "El archivo del cmr no existe",
"You are not allowed to modify the alias": "No estás autorizado a modificar el alias",
"The address of the customer must have information about Incoterms and Customs Agent": "El consignatario del cliente debe tener informado Incoterms y Agente de aduanas",
+ "No invoice series found for these parameters": "No se encontró una serie para estos parámetros",
"The line could not be marked": "La linea no puede ser marcada",
"Through this procedure, it is not possible to modify the password of users with verified email": "Mediante este procedimiento, no es posible modificar la contraseña de usuarios con correo verificado",
"They're not your subordinate": "No es tu subordinado/a.",
@@ -358,7 +359,6 @@
"This workCenter is already assigned to this agency": "Este centro de trabajo ya está asignado a esta agencia",
"Select ticket or client": "Elija un ticket o un client",
"It was not able to create the invoice": "No se pudo crear la factura",
- "ticketCommercial": "El ticket {{ ticket }} para el vendedor {{ salesMan }} está en preparación. (mensaje generado automáticamente)",
"Incoterms and Customs agent are required for a non UEE member": "Se requieren Incoterms y agente de aduanas para un no miembro de la UEE",
"You can not use the same password": "No puedes usar la misma contraseña",
"This PDA is already assigned to another user": "Este PDA ya está asignado a otro usuario",
@@ -381,5 +381,22 @@
"The entry does not have stickers": "La entrada no tiene etiquetas",
"This buyer has already made a reservation for this date": "Este comprador ya ha hecho una reserva para esta fecha",
"No valid travel thermograph found": "No se encontró un termógrafo válido",
- "The quantity claimed cannot be greater than the quantity of the line": "La cantidad reclamada no puede ser mayor que la cantidad de la línea"
+ "The quantity claimed cannot be greater than the quantity of the line": "La cantidad reclamada no puede ser mayor que la cantidad de la línea",
+ "type cannot be blank": "Se debe rellenar el tipo",
+ "There are tickets for this area, delete them first": "Hay tickets para esta sección, borralos primero",
+ "There is no company associated with that warehouse": "No hay ninguna empresa asociada a ese almacén",
+ "You do not have permission to modify the booked field": "No tienes permisos para modificar el campo contabilizada",
+ "ticketLostExpedition": "El ticket [{{ticketId}}]({{{ticketUrl}}}) tiene la siguiente expedición perdida:{{ expeditionId }}",
+ "The web user's email already exists": "El correo del usuario web ya existe",
+ "Sales already moved": "Ya han sido transferidas",
+ "The raid information is not correct": "La información de la redada no es correcta",
+ "No trips found because input coordinates are not connected": "No se encontraron rutas porque las coordenadas de entrada no están conectadas",
+ "This request is not supported": "Esta solicitud no es compatible",
+ "Invalid options or too many coordinates": "Opciones invalidas o demasiadas coordenadas",
+ "No address has coordinates": "Ninguna dirección tiene coordenadas",
+ "An item type with the same code already exists": "Un tipo con el mismo código ya existe",
+ "Holidays to past days not available": "Las vacaciones a días pasados no están disponibles",
+ "All tickets have a route order": "Todos los tickets tienen orden de ruta",
+ "Price cannot be blank": "Price cannot be blank",
+ "There are tickets to be invoiced": "La zona tiene tickets por facturar"
}
diff --git a/loopback/locale/fr.json b/loopback/locale/fr.json
index a6648b186..9941358be 100644
--- a/loopback/locale/fr.json
+++ b/loopback/locale/fr.json
@@ -123,8 +123,8 @@
"Added sale to ticket": "J'ai ajouté la ligne suivante au ticket [{{ticketId}}]({{{ticketUrl}}}): {{{addition}}}",
"Changed sale discount": "J'ai changé le rabais des lignes suivantes du ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
"Created claim": "J'ai créé la réclamation [{{claimId}}]({{{claimUrl}}}) des lignes suivantes du ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
- "Changed sale price": " le prix de [{{itemId}} {{concept}}]({{{itemUrl}}}) ({{quantity}}) de {{oldPrice}}€ ➔ *{{newPrice}}€* du ticket [{{ticketId}}]({{{ticketUrl}}})",,
- "Changed sale quantity": "J'ai changé {{changes}} du ticket [{{ticketId}}]({{{ticketUrl}}})",
+ "Changed sale price": " le prix de [{{itemId}} {{concept}}]({{{itemUrl}}}) ({{quantity}}) de {{oldPrice}}€ ➔ *{{newPrice}}€* du ticket [{{ticketId}}]({{{ticketUrl}}})",
+ "Changed sale quantity": "J'ai changé {{changes}} du ticket [{{ticketId}}]({{{ticketUrl}}})",
"Changes in sales": "la quantité de {{itemId}} {{concept}} de {{oldQuantity}} ➔ {{newQuantity}}",
"State": "État",
"regular": "normal",
@@ -350,6 +350,7 @@
"Cmr file does not exist": "Le fichier cmr n'existe pas",
"You are not allowed to modify the alias": "Vous n'êtes pas autorisé à modifier l'alias",
"The address of the customer must have information about Incoterms and Customs Agent": "L'adresse du client doit contenir des informations sur les Incoterms et l'agent des douanes",
+ "No invoice series found for these parameters": "Aucune série de facture trouvée pour ces paramètres",
"The line could not be marked": "La ligne ne peut pas être marquée",
"This password can only be changed by the user themselves": "Ce mot de passe ne peut être modifié que par l'utilisateur lui-même",
"They're not your subordinate": "Ce n'est pas votre subordonné.",
@@ -362,5 +363,8 @@
"It has been invoiced but the PDF of refund not be generated": "Il a été facturé mais le PDF de remboursement n'a pas été généré",
"Cannot send mail": "Impossible d'envoyer le mail",
"Original invoice not found": "Facture originale introuvable",
- "The quantity claimed cannot be greater than the quantity of the line": "Le montant réclamé ne peut pas être supérieur au montant de la ligne"
+ "The quantity claimed cannot be greater than the quantity of the line": "Le montant réclamé ne peut pas être supérieur au montant de la ligne",
+ "You do not have permission to modify the booked field": "Vous n'avez pas la permission de modifier le champ comptabilisé",
+ "ticketLostExpedition": "Le ticket [{{ticketId}}]({{{ticketUrl}}}) a l'expédition perdue suivante : {{expeditionId}}",
+ "The web user's email already exists": "L'email de l'internaute existe déjà"
}
diff --git a/loopback/locale/pt.json b/loopback/locale/pt.json
index a43f0e780..e84b30f3d 100644
--- a/loopback/locale/pt.json
+++ b/loopback/locale/pt.json
@@ -124,7 +124,7 @@
"Changed sale discount": "Desconto da venda alterado no ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
"Created claim": "Reclamação criada [{{claimId}}]({{{claimUrl}}}) no ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}",
"Changed sale price": "Preço da venda alterado para [{{itemId}} {{concept}}]({{{itemUrl}}}) ({{quantity}}) de {{oldPrice}}€ ➔ *{{newPrice}}€* no ticket [{{ticketId}}]({{{ticketUrl}}})",
- "Changed sale quantity": "Quantidade da venda alterada para {{changes}} no ticket [{{ticketId}}]({{{ticketUrl}}})",
+ "Changed sale quantity": "Quantidade da venda alterada para {{changes}} no ticket [{{ticketId}}]({{{ticketUrl}}})",
"Changes in sales": " [{{itemId}} {{concept}}]({{{itemUrl}}}) de {{oldQuantity}} ➔ *{{newQuantity}}* ",
"State": "Estado",
"regular": "normal",
@@ -350,6 +350,7 @@
"Cmr file does not exist": "O arquivo CMR não existe",
"You are not allowed to modify the alias": "Você não tem permissão para modificar o alias",
"The address of the customer must have information about Incoterms and Customs Agent": "O endereço do cliente deve ter informações sobre Incoterms e Agente Aduaneiro",
+ "No invoice series found for these parameters": "Nenhuma série de fatura encontrada para esses parâmetros",
"The line could not be marked": "A linha não pôde ser marcada",
"This password can only be changed by the user themselves": "Esta senha só pode ser alterada pelo próprio usuário",
"They're not your subordinate": "Eles não são seus subordinados.",
@@ -360,7 +361,9 @@
"It was not able to create the invoice": "Não foi possível criar a fatura",
"The invoices have been created but the PDFs could not be generated": "Foi faturado, mas o PDF não pôde ser gerado",
"It has been invoiced but the PDF of refund not be generated": "Foi faturado mas não foi gerado o PDF do reembolso",
- "Original invoice not found": "Fatura original não encontrada",
+ "Original invoice not found": "Fatura original não encontrada",
"Cannot send mail": "Não é possível enviar o email",
- "The quantity claimed cannot be greater than the quantity of the line": "O valor reclamado não pode ser superior ao valor da linha"
+ "The quantity claimed cannot be greater than the quantity of the line": "O valor reclamado não pode ser superior ao valor da linha",
+ "ticketLostExpedition": "O ticket [{{ticketId}}]({{{ticketUrl}}}) tem a seguinte expedição perdida: {{expeditionId}}",
+ "The web user's email already exists": "O e-mail do utilizador da web já existe."
}
diff --git a/modules/account/back/locale/vn-user/en.yml b/modules/account/back/locale/vn-user/en.yml
index 51de7c40d..f911ee1eb 100644
--- a/modules/account/back/locale/vn-user/en.yml
+++ b/modules/account/back/locale/vn-user/en.yml
@@ -15,7 +15,5 @@ columns:
image: image
hasGrant: has grant
userFk: user
- recoverPass: recover password
role: role
- sync: pending sync
lastPassChange: password changed
diff --git a/modules/account/back/locale/vn-user/es.yml b/modules/account/back/locale/vn-user/es.yml
index 85e8bc0dc..c05dd872c 100644
--- a/modules/account/back/locale/vn-user/es.yml
+++ b/modules/account/back/locale/vn-user/es.yml
@@ -15,7 +15,5 @@ columns:
image: imagen
hasGrant: puede delegar
userFk: usuario
- recoverPass: recuperar contraseña
role: rol
- sync: Pendiente de sincronizar
lastPassChange: contraseña modificada
diff --git a/modules/account/back/methods/account/sync.js b/modules/account/back/methods/account/sync.js
index 1026c5020..b38e4dd37 100644
--- a/modules/account/back/methods/account/sync.js
+++ b/modules/account/back/methods/account/sync.js
@@ -29,14 +29,14 @@ module.exports = Self => {
const models = Self.app.models;
const myOptions = {};
let tx;
-
+
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
- };
+ }
try {
const user = await models.VnUser.findOne({
diff --git a/modules/account/back/models/sip.json b/modules/account/back/models/sip.json
index f2e2221b5..dbcef3b9e 100644
--- a/modules/account/back/models/sip.json
+++ b/modules/account/back/models/sip.json
@@ -25,7 +25,12 @@
"type": "belongsTo",
"model": "VnUser",
"foreignKey": "user_id"
+ },
+ "queueMember": {
+ "type": "belongsTo",
+ "model": "QueueMember",
+ "foreignKey": "extension",
+ "primaryKey": "extension"
}
}
-}
-
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/modules/claim/back/methods/claim/filter.js b/modules/claim/back/methods/claim/filter.js
index f60b6572e..bacdd4021 100644
--- a/modules/claim/back/methods/claim/filter.js
+++ b/modules/claim/back/methods/claim/filter.js
@@ -80,6 +80,12 @@ module.exports = Self => {
description: 'The claimResponsible id',
http: {source: 'query'}
},
+ {
+ arg: 'zoneFk',
+ type: 'string',
+ description: 'The zone name',
+ http: {source: 'query'}
+ },
{
arg: 'myTeam',
type: 'boolean',
@@ -174,6 +180,8 @@ module.exports = Self => {
to.setHours(23, 59, 59, 999);
return {'cl.created': {between: [value, to]}};
+ case 'zoneFk':
+ return {'t.zoneFk': value};
case 'myTeam':
if (value)
return {'cl.workerFk': {inq: teamMembersId}};
@@ -195,11 +203,15 @@ module.exports = Self => {
u.name AS workerName,
cs.code stateCode,
cs.description stateDescription,
- cl.created
+ cl.created,
+ z.name zoneName,
+ z.id zoneId
FROM claim cl
LEFT JOIN client c ON c.id = cl.clientFk
LEFT JOIN account.user u ON u.id = cl.workerFk
- LEFT JOIN claimState cs ON cs.id = cl.claimStateFk`
+ LEFT JOIN claimState cs ON cs.id = cl.claimStateFk
+ LEFT JOIN ticket t ON t.id = cl.ticketFk
+ LEFT JOIN zone z ON z.id = t.zoneFk`
);
stmt.merge(conn.makeSuffix(filter));
diff --git a/modules/claim/back/methods/claim/updateClaim.js b/modules/claim/back/methods/claim/updateClaim.js
index 326192385..563b5b53d 100644
--- a/modules/claim/back/methods/claim/updateClaim.js
+++ b/modules/claim/back/methods/claim/updateClaim.js
@@ -85,16 +85,11 @@ module.exports = Self => {
const updatedClaim = await claim.updateAttributes(args, myOptions);
const salesPerson = claim.client().salesPersonUser();
- if (salesPerson) {
- if (changedPickup && updatedClaim.pickup)
- await notifyPickUp(ctx, salesPerson.id, claim);
-
- if (args.claimStateFk) {
- const newState = await models.ClaimState.findById(args.claimStateFk, null, myOptions);
- await notifyStateChange(ctx, salesPerson.id, claim, newState.description);
- if (newState.code == 'canceled')
- await notifyStateChange(ctx, claim.workerFk, claim, newState.description);
- }
+ if (salesPerson && args.claimStateFk) {
+ const newState = await models.ClaimState.findById(args.claimStateFk, null, myOptions);
+ await notifyStateChange(ctx, salesPerson.id, claim, newState.description);
+ if (newState.code == 'canceled')
+ await notifyStateChange(ctx, claim.workerFk, claim, newState.description);
}
if (tx) await tx.commit();
@@ -119,18 +114,4 @@ module.exports = Self => {
});
await models.Chat.sendCheckingPresence(ctx, workerId, message);
}
-
- async function notifyPickUp(ctx, workerId, claim) {
- const models = Self.app.models;
- const url = await models.Url.getUrl();
- const $t = ctx.req.__; // $translate
-
- const message = $t('Claim will be picked', {
- claimId: claim.id,
- clientName: claim.client().name,
- claimUrl: `${url}claim/${claim.id}/summary`,
- claimPickup: $t(claim.pickup)
- });
- await models.Chat.sendCheckingPresence(ctx, workerId, message);
- }
};
diff --git a/modules/client/back/methods/client/canBeInvoiced.js b/modules/client/back/methods/client/canBeInvoiced.js
index cdb865500..536606b0b 100644
--- a/modules/client/back/methods/client/canBeInvoiced.js
+++ b/modules/client/back/methods/client/canBeInvoiced.js
@@ -2,7 +2,7 @@ const UserError = require('vn-loopback/util/user-error');
module.exports = function(Self) {
Self.remoteMethod('canBeInvoiced', {
- description: 'Change property isEqualizated in all client addresses',
+ description: 'Check if a client can be invoiced',
accessType: 'READ',
accepts: [
{
@@ -38,7 +38,7 @@ module.exports = function(Self) {
Object.assign(myOptions, options);
const client = await models.Client.findById(id, {
- fields: ['id', 'isTaxDataChecked', 'hasToInvoice', 'payMethodFk'],
+ fields: ['id', 'isTaxDataChecked', 'hasToInvoice', 'payMethodFk', 'isActive'],
include:
{
relation: 'payMethod',
@@ -53,9 +53,6 @@ module.exports = function(Self) {
if (client.payMethod().code === 'wireTransfer' && !company.supplierAccountFk)
throw new UserError('The company has not informed the supplier account for bank transfers');
- if (client.isTaxDataChecked && client.hasToInvoice)
- return true;
-
- return false;
+ return client.isTaxDataChecked && client.hasToInvoice && client.isActive;
};
};
diff --git a/modules/client/back/methods/client/createWithUser.js b/modules/client/back/methods/client/createWithUser.js
index 06b885ab8..1d5e71fca 100644
--- a/modules/client/back/methods/client/createWithUser.js
+++ b/modules/client/back/methods/client/createWithUser.js
@@ -1,3 +1,4 @@
+/* eslint max-len: ["error", { "code": 150 }]*/
const UserError = require('vn-loopback/util/user-error');
module.exports = function(Self) {
@@ -43,6 +44,23 @@ module.exports = function(Self) {
};
try {
+ const province = await models.Province.findOne({
+ where: {id: data.provinceFk},
+ fields: ['autonomyFk']
+ });
+
+ const autonomy = province ? await models.Autonomy.findOne({
+ where: {id: province.autonomyFk},
+ fields: ['hasDailyInvoice']
+ }) : null;
+
+ const country = await models.Country.findOne({
+ where: {id: data.countryFk},
+ fields: ['hasDailyInvoice']
+ });
+
+ const hasDailyInvoice = (autonomy?.hasDailyInvoice ?? country?.hasDailyInvoice) || false;
+
const account = await models.VnUser.create(user, myOptions);
const client = await Self.create({
id: account.id,
@@ -57,7 +75,8 @@ module.exports = function(Self) {
provinceFk: data.provinceFk,
countryFk: data.countryFk,
isEqualizated: data.isEqualizated,
- businessTypeFk: data.businessTypeFk
+ businessTypeFk: data.businessTypeFk,
+ hasDailyInvoice: hasDailyInvoice
}, myOptions);
const address = await models.Address.create({
@@ -80,6 +99,8 @@ module.exports = function(Self) {
return client;
} catch (e) {
if (tx) await tx.rollback();
+ if (e.message && e.message.includes(`Email already exists`)) throw new UserError(`The web user's email already exists`);
+
throw e;
}
};
diff --git a/modules/client/back/methods/client/filter.js b/modules/client/back/methods/client/filter.js
index f805c4be9..7df973f19 100644
--- a/modules/client/back/methods/client/filter.js
+++ b/modules/client/back/methods/client/filter.js
@@ -1,4 +1,3 @@
-
const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
const buildFilter = require('vn-loopback/util/filter').buildFilter;
const mergeFilters = require('vn-loopback/util/filter').mergeFilters;
diff --git a/modules/client/back/methods/client/specs/canBeInvoiced.spec.js b/modules/client/back/methods/client/specs/canBeInvoiced.spec.js
index 397be3c92..4012b7409 100644
--- a/modules/client/back/methods/client/specs/canBeInvoiced.spec.js
+++ b/modules/client/back/methods/client/specs/canBeInvoiced.spec.js
@@ -8,6 +8,8 @@ describe('client canBeInvoiced()', () => {
const activeCtx = {
accessToken: {userId: userId}
};
+ let tx;
+ let options;
beforeAll(async() => {
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
@@ -15,60 +17,45 @@ describe('client canBeInvoiced()', () => {
});
});
+ beforeEach(async() => {
+ tx = await models.Client.beginTransaction({});
+ options = {transaction: tx};
+ });
+
+ afterEach(async() => {
+ await tx.rollback();
+ });
+
it('should return falsy for a client without the data checked', async() => {
- const tx = await models.Client.beginTransaction({});
+ const client = await models.Client.findById(clientId, null, options);
+ await client.updateAttribute('isTaxDataChecked', false, options);
- try {
- const options = {transaction: tx};
+ const canBeInvoiced = await models.Client.canBeInvoiced(clientId, companyId, options);
- const client = await models.Client.findById(clientId, null, options);
- await client.updateAttribute('isTaxDataChecked', false, options);
+ expect(canBeInvoiced).toEqual(false);
+ });
- const canBeInvoiced = await models.Client.canBeInvoiced(clientId, companyId, options);
+ it('should return falsy for a client not active', async() => {
+ const client = await models.Client.findById(clientId, null, options);
+ await client.updateAttribute('isActive', false, options);
- expect(canBeInvoiced).toEqual(false);
+ const canBeInvoiced = await models.Client.canBeInvoiced(clientId, companyId, options);
- await tx.rollback();
- } catch (e) {
- await tx.rollback();
- throw e;
- }
+ expect(canBeInvoiced).toEqual(false);
});
it('should return falsy for a client with invoicing disabled', async() => {
- const tx = await models.Client.beginTransaction({});
+ const client = await models.Client.findById(clientId, null, options);
+ await client.updateAttribute('hasToInvoice', false, options);
- try {
- const options = {transaction: tx};
+ const canBeInvoiced = await models.Client.canBeInvoiced(clientId, companyId, options);
- const client = await models.Client.findById(clientId, null, options);
- await client.updateAttribute('hasToInvoice', false, options);
-
- const canBeInvoiced = await models.Client.canBeInvoiced(clientId, companyId, options);
-
- expect(canBeInvoiced).toEqual(false);
-
- await tx.rollback();
- } catch (e) {
- await tx.rollback();
- throw e;
- }
+ expect(canBeInvoiced).toEqual(false);
});
it('should return truthy for an invoiceable client', async() => {
- const tx = await models.Client.beginTransaction({});
+ const canBeInvoiced = await models.Client.canBeInvoiced(clientId, companyId, options);
- try {
- const options = {transaction: tx};
-
- const canBeInvoiced = await models.Client.canBeInvoiced(clientId, companyId, options);
-
- expect(canBeInvoiced).toEqual(true);
-
- await tx.rollback();
- } catch (e) {
- await tx.rollback();
- throw e;
- }
+ expect(canBeInvoiced).toEqual(true);
});
});
diff --git a/modules/client/back/methods/client/specs/createWithUser.spec.js b/modules/client/back/methods/client/specs/createWithUser.spec.js
index 5b1ff5da9..8cff96ac5 100644
--- a/modules/client/back/methods/client/specs/createWithUser.spec.js
+++ b/modules/client/back/methods/client/specs/createWithUser.spec.js
@@ -1,67 +1,78 @@
const models = require('vn-loopback/server/server').models;
+
describe('Client Create', () => {
- const newAccount = {
- userName: 'deadpool',
- email: 'deadpool@marvel.com',
- fi: '16195279J',
- name: 'Wade',
- socialName: 'DEADPOOL MARVEL',
- street: 'WALL STREET',
- city: 'New York',
- businessTypeFk: 'florist',
- provinceFk: 1
- };
- const newAccountWithoutEmail = JSON.parse(JSON.stringify(newAccount));
- delete newAccountWithoutEmail.email;
+ let options;
+ let tx;
beforeAll.mockLoopBackContext();
- it(`should not find deadpool as he's not created yet`, async() => {
- const tx = await models.Client.beginTransaction({});
+ beforeEach(async() => {
+ tx = await models.Client.beginTransaction({});
+ options = {transaction: tx};
+ });
+ afterEach(async() => await tx.rollback());
+
+ it('should not find deadpool as he is not created yet', async() => {
try {
- const options = {transaction: tx};
+ const account = await models.VnUser.findOne({where: {name: 'deadpool'}}, options);
+ const client = await models.Client.findOne({where: {name: 'Wade'}}, options);
- const account = await models.VnUser.findOne({where: {name: newAccount.userName}}, options);
- const client = await models.Client.findOne({where: {name: newAccount.name}}, options);
-
- expect(account).toEqual(null);
- expect(client).toEqual(null);
-
- await tx.rollback();
+ expect(account).toBeNull();
+ expect(client).toBeNull();
} catch (e) {
await tx.rollback();
throw e;
}
});
- it('should not create a new account', async() => {
- const tx = await models.Client.beginTransaction({});
-
+ it('should throw an error when creating a new account without email', async() => {
let error;
+ const newAccountWithoutEmail = {
+ userName: 'deadpool',
+ fi: '16195279J',
+ name: 'Wade',
+ socialName: 'DEADPOOL MARVEL',
+ street: 'WALL STREET',
+ city: 'New York',
+ businessTypeFk: 'florist',
+ provinceFk: 1
+ };
+
try {
- const options = {transaction: tx};
await models.Client.createWithUser(newAccountWithoutEmail, options);
-
- await tx.rollback();
} catch (e) {
- error = e.message;
-
- await tx.rollback();
+ error = e;
}
- expect(error).toEqual(`An email is necessary`);
+ expect(error.message).toEqual('An email is necessary');
});
- it('should create a new account', async() => {
- const tx = await models.Client.beginTransaction({});
+ it('should create a new account with dailyInvoice', async() => {
+ const newAccount = {
+ userName: 'deadpool',
+ email: 'deadpool@marvel.com',
+ fi: '16195279J',
+ name: 'Wade',
+ socialName: 'DEADPOOL MARVEL',
+ street: 'WALL STREET',
+ city: 'New York',
+ businessTypeFk: 'florist',
+ provinceFk: 1
+ };
try {
- const options = {transaction: tx};
+ const province = await models.Province.findById(newAccount.provinceFk, {
+ fields: ['id', 'name', 'autonomyFk'],
+ include: {
+ relation: 'autonomy'
+ }
+ }, options);
const client = await models.Client.createWithUser(newAccount, options);
const account = await models.VnUser.findOne({where: {name: newAccount.userName}}, options);
+ expect(province.autonomy().hasDailyInvoice).toBeTruthy();
expect(account.name).toEqual(newAccount.userName);
expect(client.id).toEqual(account.id);
expect(client.name).toEqual(newAccount.name);
@@ -69,8 +80,38 @@ describe('Client Create', () => {
expect(client.fi).toEqual(newAccount.fi);
expect(client.socialName).toEqual(newAccount.socialName);
expect(client.businessTypeFk).toEqual(newAccount.businessTypeFk);
-
+ expect(client.hasDailyInvoice).toBeTruthy();
+ } catch (e) {
await tx.rollback();
+ throw e;
+ }
+ });
+
+ it('should create a new account without dailyInvoice', async() => {
+ const newAccount = {
+ userName: 'deadpool',
+ email: 'deadpool@marvel.com',
+ fi: '16195279J',
+ name: 'Wade',
+ socialName: 'DEADPOOL MARVEL',
+ street: 'WALL STREET',
+ city: 'New York',
+ businessTypeFk: 'florist',
+ provinceFk: 3
+ };
+
+ try {
+ const province = await models.Province.findById(newAccount.provinceFk, {
+ fields: ['id', 'name', 'autonomyFk'],
+ include: {
+ relation: 'autonomy'
+ }
+ }, options);
+
+ const client = await models.Client.createWithUser(newAccount, options);
+
+ expect(province.autonomy.hasDailyInvoice).toBeFalsy();
+ expect(client.hasDailyInvoice).toBeFalsy();
} catch (e) {
await tx.rollback();
throw e;
@@ -78,26 +119,25 @@ describe('Client Create', () => {
});
it('should not be able to create a user if exists', async() => {
- const tx = await models.Client.beginTransaction({});
-
let error;
-
+ const newAccount = {
+ userName: 'deadpool',
+ email: 'deadpool@marvel.com',
+ fi: '16195279J',
+ name: 'Wade',
+ socialName: 'DEADPOOL MARVEL',
+ street: 'WALL STREET',
+ city: 'New York',
+ businessTypeFk: 'florist',
+ provinceFk: 1
+ };
try {
- const options = {transaction: tx};
-
await models.Client.createWithUser(newAccount, options);
- const client = await models.Client.createWithUser(newAccount, options);
-
- expect(client).toBeNull();
-
- await tx.rollback();
+ await models.Client.createWithUser(newAccount, options);
} catch (e) {
- await tx.rollback();
error = e;
}
- const errorName = error.details.codes.name[0];
-
- expect(errorName).toEqual('uniqueness');
+ expect(error.message).toContain('already exists');
});
});
diff --git a/modules/client/back/methods/client/summary.js b/modules/client/back/methods/client/summary.js
index 8162096f0..9c1420b61 100644
--- a/modules/client/back/methods/client/summary.js
+++ b/modules/client/back/methods/client/summary.js
@@ -54,7 +54,10 @@ module.exports = Self => {
{
relation: 'country',
scope: {
- fields: ['name']
+ fields: ['id', 'name', 'code'],
+ include: {
+ relation: 'saySimpleCountry',
+ }
}
},
{
diff --git a/modules/client/back/methods/client/updateAddress.js b/modules/client/back/methods/client/updateAddress.js
index 7342b28f1..efef83d6b 100644
--- a/modules/client/back/methods/client/updateAddress.js
+++ b/modules/client/back/methods/client/updateAddress.js
@@ -72,6 +72,14 @@ module.exports = function(Self) {
{
arg: 'isLogifloraAllowed',
type: 'boolean'
+ },
+ {
+ arg: 'longitude',
+ type: 'any',
+ },
+ {
+ arg: 'latitude',
+ type: 'any',
}
],
returns: {
diff --git a/modules/client/back/methods/defaulter/filter.js b/modules/client/back/methods/defaulter/filter.js
index 9f19dee0a..5359ce4a7 100644
--- a/modules/client/back/methods/defaulter/filter.js
+++ b/modules/client/back/methods/defaulter/filter.js
@@ -74,7 +74,8 @@ module.exports = Self => {
pm.name payMethod,
r.finished IS NULL hasRecovery,
dp.id departmentFk,
- dp.name departmentName
+ dp.name departmentName,
+ dp.notificationEmail departmentEmail
FROM defaulter d
JOIN client c ON c.id = d.clientFk
JOIN country cn ON cn.id = c.countryFk
diff --git a/modules/client/back/methods/defaulter/observationEmail.js b/modules/client/back/methods/defaulter/observationEmail.js
index c06d1d3d0..797e88f74 100644
--- a/modules/client/back/methods/defaulter/observationEmail.js
+++ b/modules/client/back/methods/defaulter/observationEmail.js
@@ -47,7 +47,7 @@ module.exports = Self => {
await models.Mail.create({
subject: $t('Comment added to client', {clientFk: defaulter.clientFk}),
body: body,
- receiver: `${defaulter.salesPersonName}@verdnatura.es`,
+ receiver: `${defaulter.departmentEmail}`,
replyTo: `${user.name}@verdnatura.es`
}, myOptions);
}
diff --git a/modules/client/back/models/client-observation.js b/modules/client/back/models/client-observation.js
index e34eedca9..d022a440a 100644
--- a/modules/client/back/models/client-observation.js
+++ b/modules/client/back/models/client-observation.js
@@ -1,8 +1,11 @@
module.exports = function(Self) {
- Self.validate('text', isEnabled, {message: 'Description cannot be blank'});
- function isEnabled(err) {
+ Self.validate('text', function(err) {
if (!this.text) err();
- }
+ }, {message: 'Description cannot be blank'});
+
+ Self.validate('observationTypeFk', function(err) {
+ if (!this.observationTypeFk) err();
+ }, {message: 'type cannot be blank'});
Self.observe('before save', function(ctx, next) {
ctx.instance.created = Date();
diff --git a/modules/client/back/models/client-observation.json b/modules/client/back/models/client-observation.json
index b204ebeb4..1d906420a 100644
--- a/modules/client/back/models/client-observation.json
+++ b/modules/client/back/models/client-observation.json
@@ -1,10 +1,10 @@
{
- "name": "ClientObservation",
+ "name": "ClientObservation",
"description": "Client notes",
"base": "VnModel",
- "mixins": {
- "Loggable": true
- },
+ "mixins": {
+ "Loggable": true
+ },
"options": {
"mysql": {
"table": "clientObservation"
@@ -26,6 +26,10 @@
"created": {
"type": "date",
"description": "Creation date and time"
+ },
+ "observationTypeFk": {
+ "type": "number",
+ "description": "Type of observation"
}
},
"relations": {
@@ -44,14 +48,18 @@
"include": {
"relation": "worker",
"scope": {
- "fields": ["id"],
+ "fields": [
+ "id"
+ ],
"include": {
"relation": "user",
"scope": {
- "fields": ["nickname"]
+ "fields": [
+ "name"
+ ]
}
}
}
}
}
-}
+}
\ No newline at end of file
diff --git a/modules/client/front/defaulter/index.html b/modules/client/front/defaulter/index.html
index 33bb751f1..440f34d3d 100644
--- a/modules/client/front/defaulter/index.html
+++ b/modules/client/front/defaulter/index.html
@@ -54,7 +54,7 @@
Client
-
+
Es trabajador
diff --git a/modules/client/front/defaulter/index.js b/modules/client/front/defaulter/index.js
index bc8686c10..2ec53d380 100644
--- a/modules/client/front/defaulter/index.js
+++ b/modules/client/front/defaulter/index.js
@@ -57,6 +57,11 @@ export default class Controller extends Section {
field: 'observation',
searchable: false
},
+ {
+ field: 'isWorker',
+ checkbox: true,
+
+ },
{
field: 'created',
datepicker: true
@@ -73,9 +78,6 @@ export default class Controller extends Section {
set defaulters(value) {
if (!value || !value.length) return;
- for (let defaulter of value)
- defaulter.isWorker = defaulter.businessTypeFk === 'worker';
-
this._defaulters = value;
}
@@ -164,6 +166,8 @@ export default class Controller extends Section {
exprBuilder(param, value) {
switch (param) {
+ case 'isWorker':
+ return {isWorker: value};
case 'creditInsurance':
case 'amount':
case 'clientFk':
diff --git a/modules/client/front/descriptor/index.html b/modules/client/front/descriptor/index.html
index f2dbd64b6..cecd7ee62 100644
--- a/modules/client/front/descriptor/index.html
+++ b/modules/client/front/descriptor/index.html
@@ -99,7 +99,7 @@
diff --git a/modules/client/front/note/index/index.html b/modules/client/front/note/index/index.html
index 634a9c3ce..e69de29bb 100644
--- a/modules/client/front/note/index/index.html
+++ b/modules/client/front/note/index/index.html
@@ -1,31 +0,0 @@
-
-
-
-
-
-
- {{::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
index ed15db671..1610bdaab 100644
--- a/modules/client/front/note/index/index.js
+++ b/modules/client/front/note/index/index.js
@@ -5,9 +5,10 @@ import './style.scss';
export default class Controller extends Section {
constructor($element, $) {
super($element, $);
- this.filter = {
- order: 'created DESC',
- };
+ }
+ async $onInit() {
+ this.$state.go('home');
+ window.location.href = await this.vnApp.getUrl(`customer/${this.$params.id}/notes`);
}
}
diff --git a/modules/entry/back/methods/entry/buyLabel.js b/modules/entry/back/methods/entry/buyLabel.js
index 919f7c4d7..fb807fb5f 100644
--- a/modules/entry/back/methods/entry/buyLabel.js
+++ b/modules/entry/back/methods/entry/buyLabel.js
@@ -1,14 +1,28 @@
module.exports = Self => {
Self.remoteMethodCtx('buyLabel', {
- description: 'Returns the entry buy labels',
+ description: 'Returns the buy label',
accessType: 'READ',
accepts: [
{
arg: 'id',
type: 'number',
required: true,
- description: 'The entry id',
+ description: 'The buy id',
http: {source: 'path'}
+ }, {
+ arg: 'labelType',
+ type: 'string',
+ required: true,
+ description: 'The label type',
+ http: {source: 'path'}
+ }, {
+ arg: 'packing',
+ type: 'number',
+ required: false
+ }, {
+ arg: 'copies',
+ type: 'number',
+ required: false
}
],
returns: [
@@ -27,11 +41,16 @@ module.exports = Self => {
}
],
http: {
- path: '/:id/buy-label',
+ path: '/:id/:labelType/buy-label',
verb: 'GET'
},
accessScopes: ['DEFAULT', 'read:multimedia']
});
- Self.buyLabel = (ctx, id) => Self.printReport(ctx, id, 'buy-label');
+ Self.buyLabel = (ctx, id, labelType) => {
+ if (labelType == 'qr')
+ return Self.printReport(ctx, id, 'buy-label-qr');
+ else
+ return Self.printReport(ctx, id, 'buy-label-barcode');
+ };
};
diff --git a/modules/entry/back/methods/entry/buyLabelSupplier.js b/modules/entry/back/methods/entry/buyLabelSupplier.js
new file mode 100644
index 000000000..23806f561
--- /dev/null
+++ b/modules/entry/back/methods/entry/buyLabelSupplier.js
@@ -0,0 +1,41 @@
+module.exports = Self => {
+ Self.remoteMethodCtx('buyLabelSupplier', {
+ description: 'Returns the entry buy labels',
+ accessType: 'READ',
+ accepts: [
+ {
+ arg: 'id',
+ type: 'number',
+ required: true,
+ description: 'The entry id',
+ http: {source: 'path'}
+ }, {
+ arg: 'showEntryLines',
+ type: 'boolean',
+ required: false
+ }
+ ],
+ 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/buy-label-supplier',
+ verb: 'GET'
+ },
+ accessScopes: ['DEFAULT', 'read:multimedia']
+ });
+
+ Self.buyLabelSupplier = (ctx, id) => Self.printReport(ctx, id, 'buy-label-supplier');
+};
diff --git a/modules/entry/back/methods/entry/filter.js b/modules/entry/back/methods/entry/filter.js
index 776544bc6..d7740dd4e 100644
--- a/modules/entry/back/methods/entry/filter.js
+++ b/modules/entry/back/methods/entry/filter.js
@@ -106,10 +106,15 @@ module.exports = Self => {
description: `The to shipped date filter`
},
{
- arg: 'days',
+ arg: 'daysOnward',
type: 'number',
description: `N days interval`
},
+ {
+ arg: 'daysAgo',
+ type: 'number',
+ description: `N days ago interval`
+ },
{
arg: 'invoiceAmount',
type: 'number',
@@ -189,7 +194,8 @@ module.exports = Self => {
e.evaNotes observation,
e.isConfirmed,
e.isOrdered,
- e.isRaid,
+ t.isRaid,
+ t.daysInForward,
e.commission,
e.created,
e.travelFk,
@@ -216,16 +222,29 @@ module.exports = Self => {
JOIN vn.currency cu ON cu.id = e.currencyFk`
);
- if (ctx.args.days) {
- stmt.merge({
- sql: `
- AND t.shipped <= util.VN_CURDATE() + INTERVAL ? DAY
- AND t.shipped >= util.VN_CURDATE()
- `,
- params: [ctx.args.days]
- });
+ stmt.merge(conn.makeWhere(filter.where));
+
+ const {daysAgo, daysOnward} = ctx.args;
+ if (daysOnward || daysAgo) {
+ const params = [];
+ let today = 'util.VN_CURDATE()';
+ let from = today;
+ let to = today;
+
+ if (daysAgo) {
+ from += ' - INTERVAL ? DAY';
+ params.push(daysAgo);
+ }
+ if (daysOnward) {
+ to += ' + INTERVAL ? DAY';
+ params.push(daysOnward);
+ }
+
+ const whereDays = (filter.where ? 'AND' : 'WHERE') + ` t.shipped BETWEEN ${from} AND ${to}`;
+ stmt.merge({sql: whereDays, params});
}
- stmt.merge(conn.makeSuffix(filter));
+
+ stmt.merge(conn.makePagination(filter));
const itemsIndex = stmts.push(stmt) - 1;
const sql = ParameterizedSQL.join(stmts, ';');
diff --git a/modules/entry/back/methods/entry/getEntry.js b/modules/entry/back/methods/entry/getEntry.js
index cac3c65f8..92be9a9dd 100644
--- a/modules/entry/back/methods/entry/getEntry.js
+++ b/modules/entry/back/methods/entry/getEntry.js
@@ -48,7 +48,9 @@ module.exports = Self => {
'warehouseInFk',
'isReceived',
'isDelivered',
- 'ref'],
+ 'ref',
+ 'isRaid',
+ 'daysInForward'],
include: [
{
relation: 'agency',
@@ -85,7 +87,6 @@ module.exports = Self => {
}
],
};
-
return models.Entry.findOne(filter, myOptions);
};
};
diff --git a/modules/entry/back/methods/entry/print.js b/modules/entry/back/methods/entry/labelSupplier.js
similarity index 85%
rename from modules/entry/back/methods/entry/print.js
rename to modules/entry/back/methods/entry/labelSupplier.js
index 5b9de9a69..07107d032 100644
--- a/modules/entry/back/methods/entry/print.js
+++ b/modules/entry/back/methods/entry/labelSupplier.js
@@ -1,6 +1,6 @@
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
- Self.remoteMethodCtx('print', {
+ Self.remoteMethodCtx('labelSupplier', {
description: 'Print stickers of all entries',
accessType: 'READ',
accepts: [
@@ -28,13 +28,13 @@ module.exports = Self => {
}
],
http: {
- path: '/:id/print',
+ path: '/:id/labelSupplier',
verb: 'GET'
},
accessScopes: ['DEFAULT', 'read:multimedia']
});
- Self.print = async function(ctx, id, options) {
+ Self.labelSupplier = async function(ctx, id, options) {
const models = Self.app.models;
const myOptions = {};
if (typeof options == 'object')
@@ -47,8 +47,8 @@ module.exports = Self => {
for (const buy of buys) {
if (buy.stickers < 1) continue;
- ctx.args.id = buy.id;
- const pdfBuffer = await models.Entry.buyLabel(ctx, myOptions);
+ ctx.args = {...ctx.args, id: buy.id, showEntryLines: true};
+ const pdfBuffer = await models.Entry.buyLabelSupplier(ctx, myOptions);
await merger.add(new Uint8Array(pdfBuffer[0]));
}
diff --git a/modules/entry/back/methods/entry/specs/filter.spec.js b/modules/entry/back/methods/entry/specs/filter.spec.js
index c7156062a..b139b00b6 100644
--- a/modules/entry/back/methods/entry/specs/filter.spec.js
+++ b/modules/entry/back/methods/entry/specs/filter.spec.js
@@ -38,8 +38,9 @@ describe('Entry filter()', () => {
};
const result = await models.Entry.filter(ctx, options);
+ const resultWithCurrency = result.filter(entry => entry.currencyFk === 1);
- expect(result.length).toEqual(11);
+ expect(result.length).toEqual(resultWithCurrency.length);
await tx.rollback();
} catch (e) {
@@ -49,13 +50,13 @@ describe('Entry filter()', () => {
});
describe('should return the entry matching the supplier', () => {
- it('when userId is supplier ', async() => {
+ it('when userId is supplier and searching days onward', async() => {
const tx = await models.Entry.beginTransaction({});
const options = {transaction: tx};
try {
const ctx = {
- args: {days: 6},
+ args: {daysOnward: 6},
req: {accessToken: {userId: 1102}}
};
@@ -70,6 +71,27 @@ describe('Entry filter()', () => {
}
});
+ it('when userId is supplier and searching days ago', async() => {
+ const tx = await models.Entry.beginTransaction({});
+ const options = {transaction: tx};
+
+ try {
+ const ctx = {
+ args: {daysAgo: 31},
+ req: {accessToken: {userId: 1102}}
+ };
+
+ const result = await models.Entry.filter(ctx, options);
+
+ expect(result.length).toEqual(6);
+
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
+
it('when userId is supplier fetching other supplier', async() => {
const tx = await models.Entry.beginTransaction({});
const options = {transaction: tx};
@@ -120,18 +142,21 @@ describe('Entry filter()', () => {
it('should return the entry matching the company', async() => {
const tx = await models.Entry.beginTransaction({});
const options = {transaction: tx};
+ const companyFk = 442;
try {
const ctx = {
args: {
- companyFk: 442
+ companyFk
},
req: {accessToken: {userId: 9}}
};
const result = await models.Entry.filter(ctx, options);
- expect(result.length).toEqual(10);
+ const resultWithCurrency = result.filter(entry => entry.companyFk === companyFk);
+
+ expect(result.length).toEqual(resultWithCurrency.length);
await tx.rollback();
} catch (e) {
diff --git a/modules/entry/back/methods/stock-bought/getStockBought.js b/modules/entry/back/methods/stock-bought/getStockBought.js
index c1f99c496..9768b58e7 100644
--- a/modules/entry/back/methods/stock-bought/getStockBought.js
+++ b/modules/entry/back/methods/stock-bought/getStockBought.js
@@ -6,6 +6,9 @@ module.exports = Self => {
arg: 'workerFk',
type: 'number',
description: 'The id for a buyer',
+ }, {
+ arg: 'filter',
+ type: 'object',
},
{
arg: 'dated',
@@ -23,7 +26,7 @@ module.exports = Self => {
}
});
- Self.getStockBought = async(workerFk, dated = Date.vnNew()) => {
+ Self.getStockBought = async(workerFk, filter, dated = Date.vnNew()) => {
const models = Self.app.models;
const today = Date.vnNew();
dated.setHours(0, 0, 0, 0);
@@ -31,7 +34,7 @@ module.exports = Self => {
await models.StockBought.rawSql(`CALL vn.stockBought_calculate(?)`, [dated]);
- const filter = {
+ const defaultFilter = {
where: {dated},
include: [
{
@@ -53,6 +56,6 @@ module.exports = Self => {
if (workerFk) filter.where.workerFk = workerFk;
- return models.StockBought.find(filter);
+ return models.StockBought.find({...filter, ...defaultFilter});
};
};
diff --git a/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js b/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js
index 3e040d0d3..723e04cb9 100644
--- a/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js
+++ b/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js
@@ -1,3 +1,4 @@
+const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
module.exports = Self => {
Self.remoteMethod('getStockBoughtDetail', {
description: 'Returns the detail of stock bought for a given date and a worker',
@@ -12,6 +13,9 @@ module.exports = Self => {
type: 'string',
description: 'The date to filter',
required: true,
+ }, {
+ arg: 'filter',
+ type: 'object',
}
],
returns: {
@@ -24,11 +28,10 @@ module.exports = Self => {
}
});
- Self.getStockBoughtDetail = async(workerFk, dated) => {
- const models = Self.app.models;
+ Self.getStockBoughtDetail = async(workerFk, dated, filter, options) => {
+ const conn = Self.dataSource.connector;
const myOptions = {};
let tx;
- let result;
if (typeof options == 'object')
Object.assign(myOptions, options);
@@ -39,14 +42,19 @@ module.exports = Self => {
}
try {
- await models.StockBought.rawSql(`CALL vn.item_calculateStock(?)`, [dated], myOptions);
- result = await Self.rawSql(
+ const stmts = [];
+ stmts.push(new ParameterizedSQL(`CALL vn.item_calculateStock(?)`, [dated]));
+
+ const query = new ParameterizedSQL(
`SELECT b.entryFk entryFk,
i.id itemFk,
i.name itemName,
ti.quantity,
- (ac.conversionCoefficient * (ti.quantity / b.packing) * buy_getVolume(b.id))
- / (vc.trolleyM3 * 1000000) volume,
+ ROUND((ac.conversionCoefficient *
+ (ti.quantity / b.packing) *
+ buy_getVolume(b.id)
+ ) / (vc.trolleyM3 * 1000000),
+ 2) volume,
b.packagingFk packagingFk,
b.packing
FROM tmp.item ti
@@ -61,11 +69,17 @@ module.exports = Self => {
JOIN volumeConfig vc
WHERE ic.display
AND w.id = ?`,
- [workerFk], myOptions
+ [workerFk]
);
- await Self.rawSql(`DROP TEMPORARY TABLE tmp.item, tmp.buyUltimate;`, [], myOptions);
+
+ stmts.push(query.merge(conn.makeSuffix(filter)));
+
+ stmts.push(new ParameterizedSQL(`DROP TEMPORARY TABLE tmp.item, tmp.buyUltimate`));
+
+ const sql = ParameterizedSQL.join(stmts, ';');
+ const result = await conn.executeStmt(sql, myOptions);
if (tx) await tx.commit();
- return result;
+ return result[1];
} catch (e) {
await tx.rollback();
throw e;
diff --git a/modules/entry/back/model-config.json b/modules/entry/back/model-config.json
index 5c45b6e07..49c2df2db 100644
--- a/modules/entry/back/model-config.json
+++ b/modules/entry/back/model-config.json
@@ -28,5 +28,8 @@
},
"StockBought": {
"dataSource": "vn"
+ },
+ "InventoryConfig": {
+ "dataSource": "vn"
}
}
diff --git a/modules/entry/back/models/buy.js b/modules/entry/back/models/buy.js
index 34f19e765..a027a861e 100644
--- a/modules/entry/back/models/buy.js
+++ b/modules/entry/back/models/buy.js
@@ -2,4 +2,5 @@ module.exports = Self => {
require('../methods/entry/editLatestBuys')(Self);
require('../methods/entry/latestBuysFilter')(Self);
require('../methods/entry/deleteBuys')(Self);
+ require('../methods/entry/buyLabel')(Self);
};
diff --git a/modules/entry/back/models/entry.js b/modules/entry/back/models/entry.js
index 8ca79f531..55a23bb0a 100644
--- a/modules/entry/back/models/entry.js
+++ b/modules/entry/back/models/entry.js
@@ -1,3 +1,4 @@
+const UserError = require('vn-loopback/util/user-error');
const LoopBackContext = require('loopback-context');
module.exports = Self => {
require('../methods/entry/filter')(Self);
@@ -11,18 +12,28 @@ module.exports = Self => {
require('../methods/entry/addFromPackaging')(Self);
require('../methods/entry/addFromBuy')(Self);
require('../methods/entry/buyLabel')(Self);
- require('../methods/entry/print')(Self);
+ require('../methods/entry/labelSupplier')(Self);
+ require('../methods/entry/buyLabelSupplier')(Self);
Self.observe('before save', async function(ctx, options) {
if (ctx.isNewInstance) return;
const changes = ctx.data || ctx.instance;
const orgData = ctx.currentInstance;
+ const loopBackContext = LoopBackContext.getCurrentContext();
+ const accessToken = {req: loopBackContext.active};
+ const hasChanges = orgData && changes;
+
+ const isBookedChanged = changes.isBooked !== undefined && orgData.isBooked !== changes.isBooked;
+
+ if (isBookedChanged) {
+ const canEditIsBooked = await Self.app.models.ACL.checkAccessAcl(accessToken, 'Entry', 'isBooked', 'READ');
+ if (!canEditIsBooked)
+ throw new UserError('You do not have permission to modify the booked field');
+ }
const observation = changes.observation || orgData.observation;
- const hasChanges = orgData && changes;
- const observationChanged = hasChanges
- && orgData.observation != observation;
+ const observationChanged = hasChanges && orgData.observation != observation;
if (observationChanged) {
let tx;
@@ -37,8 +48,7 @@ module.exports = Self => {
}
try {
- const loopbackContext = LoopBackContext.getCurrentContext();
- const userId = loopbackContext.active.accessToken.userId;
+ const userId = loopBackContext.active.accessToken.userId;
const id = changes.id || orgData.id;
const entry = await Self.app.models.Entry.findById(id, null, myOptions);
await entry.updateAttribute('observationEditorFk', userId, myOptions);
diff --git a/modules/entry/back/models/entry.json b/modules/entry/back/models/entry.json
index 383585fce..4a09c7d6a 100644
--- a/modules/entry/back/models/entry.json
+++ b/modules/entry/back/models/entry.json
@@ -33,15 +33,6 @@
"isConfirmed": {
"type": "boolean"
},
- "isVirtual": {
- "type": "boolean",
- "mysql": {
- "columnName": "isRaid"
- }
- },
- "isRaid": {
- "type": "boolean"
- },
"commission": {
"type": "number"
},
@@ -88,7 +79,8 @@
"travel": {
"type": "belongsTo",
"model": "Travel",
- "foreignKey": "travelFk"
+ "foreignKey": "travelFk",
+ "daysInForward": "daysInForward"
},
"company": {
"type": "belongsTo",
diff --git a/modules/entry/back/models/inventory-config.json b/modules/entry/back/models/inventory-config.json
new file mode 100644
index 000000000..caa39db88
--- /dev/null
+++ b/modules/entry/back/models/inventory-config.json
@@ -0,0 +1,18 @@
+{
+ "name": "InventoryConfig",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "inventoryConfig"
+ }
+ },
+ "properties": {
+ "id": {
+ "type": "number",
+ "id": true
+ },
+ "supplierFk": {
+ "type": "number"
+ }
+ }
+}
diff --git a/modules/entry/back/models/specs/entry.spec.js b/modules/entry/back/models/specs/entry.spec.js
new file mode 100644
index 000000000..15a8202c4
--- /dev/null
+++ b/modules/entry/back/models/specs/entry.spec.js
@@ -0,0 +1,97 @@
+const {models} = require('vn-loopback/server/server');
+const LoopBackContext = require('loopback-context');
+
+describe('entry_isEditable trigger', () => {
+ const activeCtx = {
+ accessToken: {userId: 5},
+ http: {
+ req: {
+ headers: {origin: 'http://localhost'}
+ }
+ }
+ };
+ const ctx = {req: activeCtx};
+ const entryId = 1;
+ let tx;
+ let options;
+ let entry;
+
+ beforeEach(async() => {
+ spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({active: ctx.req});
+ tx = await models.Entry.beginTransaction({});
+ options = {transaction: tx};
+
+ entry = await models.Entry.findById(entryId, null, options);
+ });
+
+ afterEach(async() => {
+ await tx.rollback();
+ });
+
+ async function prepareEntry(isBooked, typeFk) {
+ let newCreated = Date.vnNew();
+ await entry.updateAttributes({isBooked, typeFk}, options);
+ await entry.updateAttributes({dated: newCreated}, options);
+ }
+
+ it('should throw an error when entry is booked and typeFk is null', async() => {
+ let error;
+ try {
+ await prepareEntry(true, null);
+ } catch (e) {
+ error = e;
+ }
+
+ expect(error.message).toContain(`Entry ${entryId} is not editable`);
+ });
+
+ it('should throw an error when entry is booked and typeFk is not informal', async() => {
+ let error;
+ try {
+ const type = await models.EntryType.findOne({where: {isInformal: false}}, options);
+ await prepareEntry(true, type.code);
+ } catch (e) {
+ error = e;
+ }
+
+ expect(error.message).toContain(`Entry ${entryId} is not editable`);
+ });
+
+ it('should not throw an error when entry is booked and typeFk is informal', async() => {
+ let error;
+ try {
+ const type = await models.EntryType.findOne({where: {isInformal: true}}, options);
+ await prepareEntry(true, type.code);
+ } catch (e) {
+ error = e;
+ }
+
+ expect(error).toBeUndefined();
+ });
+
+ it('should not throw an error when entry is not booked', async() => {
+ let error;
+ try {
+ const type = await models.EntryType.findOne({}, options);
+ await prepareEntry(false, type.code);
+ } catch (e) {
+ error = e;
+ }
+
+ expect(error).toBeUndefined();
+ });
+
+ it('should not throw an error when @isModeInventory is true', async() => {
+ let error;
+ try {
+ await models.Application.rawSql('SET @isModeInventory = TRUE;', null, options);
+ await prepareEntry(true, null);
+ } catch (e) {
+ error = e;
+ } finally {
+ await models.Application.rawSql('SET @isModeInventory = FALSE;', null, options);
+ }
+
+ expect(error).toBeUndefined();
+ });
+});
diff --git a/modules/entry/front/descriptor-popover/index.html b/modules/entry/front/descriptor-popover/index.html
new file mode 100644
index 000000000..23f641632
--- /dev/null
+++ b/modules/entry/front/descriptor-popover/index.html
@@ -0,0 +1,3 @@
+
+
+
\ No newline at end of file
diff --git a/modules/travel/front/descriptor-popover/index.js b/modules/entry/front/descriptor-popover/index.js
similarity index 81%
rename from modules/travel/front/descriptor-popover/index.js
rename to modules/entry/front/descriptor-popover/index.js
index 12c5908ca..d79aed03e 100644
--- a/modules/travel/front/descriptor-popover/index.js
+++ b/modules/entry/front/descriptor-popover/index.js
@@ -3,7 +3,7 @@ import DescriptorPopover from 'salix/components/descriptor-popover';
class Controller extends DescriptorPopover {}
-ngModule.vnComponent('vnTravelDescriptorPopover', {
+ngModule.vnComponent('vnEntryDescriptorPopover', {
slotTemplate: require('./index.html'),
controller: Controller
});
diff --git a/modules/entry/front/descriptor/index.html b/modules/entry/front/descriptor/index.html
new file mode 100644
index 000000000..957bcafb5
--- /dev/null
+++ b/modules/entry/front/descriptor/index.html
@@ -0,0 +1,65 @@
+
+
+
+ Show entry report
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/modules/entry/front/descriptor/index.js b/modules/entry/front/descriptor/index.js
new file mode 100644
index 000000000..3452a6d34
--- /dev/null
+++ b/modules/entry/front/descriptor/index.js
@@ -0,0 +1,99 @@
+import ngModule from '../module';
+import Descriptor from 'salix/components/descriptor';
+
+class Controller extends Descriptor {
+ get entry() {
+ return this.entity;
+ }
+
+ set entry(value) {
+ this.entity = value;
+ }
+
+ get travelFilter() {
+ let travelFilter;
+ const entryTravel = this.entry && this.entry.travel;
+
+ if (entryTravel && entryTravel.agencyModeFk) {
+ travelFilter = this.entry && JSON.stringify({
+ agencyModeFk: entryTravel.agencyModeFk
+ });
+ }
+ return travelFilter;
+ }
+
+ get entryFilter() {
+ let entryTravel = this.entry && this.entry.travel;
+
+ if (!entryTravel || !entryTravel.landed) return null;
+
+ const date = new Date(entryTravel.landed);
+ date.setHours(0, 0, 0, 0);
+
+ const from = new Date(date.getTime());
+ from.setDate(from.getDate() - 10);
+
+ const to = new Date(date.getTime());
+ to.setDate(to.getDate() + 10);
+
+ return JSON.stringify({
+ supplierFk: this.entry.supplierFk,
+ from,
+ to
+ });
+ }
+
+ loadData() {
+ const filter = {
+ include: [
+ {
+ relation: 'travel',
+ scope: {
+ fields: ['id', 'landed', 'agencyModeFk', 'warehouseOutFk'],
+ include: [
+ {
+ relation: 'agency',
+ scope: {
+ fields: ['name']
+ }
+ },
+ {
+ relation: 'warehouseOut',
+ scope: {
+ fields: ['name']
+ }
+ },
+ {
+ relation: 'warehouseIn',
+ scope: {
+ fields: ['name']
+ }
+ }
+ ]
+ }
+ },
+ {
+ relation: 'supplier',
+ scope: {
+ fields: ['id', 'nickname']
+ }
+ }
+ ]
+ };
+
+ return this.getData(`Entries/${this.id}`, {filter})
+ .then(res => this.entity = res.data);
+ }
+
+ showEntryReport() {
+ this.vnReport.show(`Entries/${this.id}/entry-order-pdf`);
+ }
+}
+
+ngModule.vnComponent('vnEntryDescriptor', {
+ template: require('./index.html'),
+ controller: Controller,
+ bindings: {
+ entry: '<'
+ }
+});
diff --git a/modules/entry/front/index.js b/modules/entry/front/index.js
index a7209a0bd..0f2208862 100644
--- a/modules/entry/front/index.js
+++ b/modules/entry/front/index.js
@@ -1,3 +1,6 @@
export * from './module';
import './main';
+import './descriptor';
+import './descriptor-popover';
+import './summary';
diff --git a/modules/entry/front/routes.json b/modules/entry/front/routes.json
index 53c599cf1..a2e70e37d 100644
--- a/modules/entry/front/routes.json
+++ b/modules/entry/front/routes.json
@@ -8,6 +8,12 @@
"main": [
{"state": "entry.index", "icon": "icon-entry"},
{"state": "entry.latestBuys", "icon": "contact_support"}
+ ],
+ "card": [
+ {"state": "entry.card.basicData", "icon": "settings"},
+ {"state": "entry.card.buy.index", "icon": "icon-lines"},
+ {"state": "entry.card.observation", "icon": "insert_drive_file"},
+ {"state": "entry.card.log", "icon": "history"}
]
},
"keybindings": [
@@ -27,6 +33,90 @@
"component": "vn-entry-index",
"description": "Entries",
"acl": ["buyer", "administrative"]
+ },
+ {
+ "url": "/latest-buys?q",
+ "state": "entry.latestBuys",
+ "component": "vn-entry-latest-buys",
+ "description": "Latest buys",
+ "acl": ["buyer", "administrative"]
+ },
+ {
+ "url": "/create?supplierFk&travelFk&companyFk",
+ "state": "entry.create",
+ "component": "vn-entry-create",
+ "description": "New entry",
+ "acl": ["buyer", "administrative"]
+ },
+ {
+ "url": "/:id",
+ "state": "entry.card",
+ "abstract": true,
+ "component": "vn-entry-card"
+ },
+ {
+ "url": "/summary",
+ "state": "entry.card.summary",
+ "component": "vn-entry-summary",
+ "description": "Summary",
+ "params": {
+ "entry": "$ctrl.entry"
+ },
+ "acl": ["buyer", "administrative"]
+ },
+ {
+ "url": "/basic-data",
+ "state": "entry.card.basicData",
+ "component": "vn-entry-basic-data",
+ "description": "Basic data",
+ "params": {
+ "entry": "$ctrl.entry"
+ },
+ "acl": ["buyer", "administrative"]
+ },
+ {
+ "url": "/observation",
+ "state": "entry.card.observation",
+ "component": "vn-entry-observation",
+ "description": "Notes",
+ "params": {
+ "entry": "$ctrl.entry"
+ },
+ "acl": ["buyer", "administrative"]
+ },
+ {
+ "url" : "/log",
+ "state": "entry.card.log",
+ "component": "vn-entry-log",
+ "description": "Log",
+ "acl": ["buyer", "administrative"]
+ },
+ {
+ "url": "/buy",
+ "state": "entry.card.buy",
+ "abstract": true,
+ "component": "ui-view",
+ "acl": ["buyer"]
+ },
+ {
+ "url" : "/index",
+ "state": "entry.card.buy.index",
+ "component": "vn-entry-buy-index",
+ "description": "Buys",
+ "params": {
+ "entry": "$ctrl.entry"
+ },
+ "acl": ["buyer", "administrative"]
+ },
+ {
+ "url" : "/import",
+ "state": "entry.card.buy.import",
+ "component": "vn-entry-buy-import",
+ "description": "Import buys",
+ "params": {
+ "entry": "$ctrl.entry"
+ },
+ "acl": ["buyer"]
}
]
}
diff --git a/modules/entry/front/summary/index.html b/modules/entry/front/summary/index.html
new file mode 100644
index 000000000..db4b034f7
--- /dev/null
+++ b/modules/entry/front/summary/index.html
@@ -0,0 +1,195 @@
+
+
+
+
+
+
+
+ #{{$ctrl.entryData.id}} - {{$ctrl.entryData.supplier.nickname}}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{$ctrl.entryData.travel.ref}}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Buys
+
+
+
+ Quantity
+ Stickers
+ Package
+ Weight
+ Packing
+ Grouping
+ Buying value
+ Import
+ PVP
+
+
+
+
+ {{::line.quantity}}
+ {{::line.stickers | dashIfEmpty}}
+ {{::line.packagingFk | dashIfEmpty}}
+ {{::line.weight}}
+
+
+ {{::line.packing | dashIfEmpty}}
+
+
+
+
+ {{::line.grouping | dashIfEmpty}}
+
+
+ {{::line.buyingValue | currency: 'EUR':2}}
+ {{::line.quantity * line.buyingValue | currency: 'EUR':2}}
+ {{::line.price2 | currency: 'EUR':2 | dashIfEmpty}} / {{::line.price3 | currency: 'EUR':2 | dashIfEmpty}}
+
+
+
+
+ {{::line.item.itemType.code}}
+
+
+
+
+ {{::line.item.id}}
+
+
+
+
+ {{::line.item.size}}
+
+
+
+
+ {{::line.item.minPrice | currency: 'EUR':2}}
+
+
+
+
+ {{::line.item.name}}
+
+ {{::line.item.subName}}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/modules/entry/front/summary/index.js b/modules/entry/front/summary/index.js
new file mode 100644
index 000000000..6e18bc959
--- /dev/null
+++ b/modules/entry/front/summary/index.js
@@ -0,0 +1,33 @@
+import ngModule from '../module';
+import './style.scss';
+import Summary from 'salix/components/summary';
+
+class Controller extends Summary {
+ get entry() {
+ if (!this._entry)
+ return this.$params;
+
+ return this._entry;
+ }
+
+ set entry(value) {
+ this._entry = value;
+
+ if (value && value.id)
+ this.getEntryData();
+ }
+
+ getEntryData() {
+ return this.$http.get(`Entries/${this.entry.id}/getEntry`).then(response => {
+ this.entryData = response.data;
+ });
+ }
+}
+
+ngModule.vnComponent('vnEntrySummary', {
+ template: require('./index.html'),
+ controller: Controller,
+ bindings: {
+ entry: '<'
+ }
+});
diff --git a/modules/entry/front/summary/style.scss b/modules/entry/front/summary/style.scss
new file mode 100644
index 000000000..1d5b22e30
--- /dev/null
+++ b/modules/entry/front/summary/style.scss
@@ -0,0 +1,30 @@
+@import "variables";
+
+
+vn-entry-summary .summary {
+ max-width: $width-lg;
+
+ .dark-row {
+ background-color: lighten($color-marginal, 10%);
+ }
+
+ tbody tr:nth-child(1) {
+ border-top: $border-thin;
+ }
+
+ tbody tr:nth-child(1),
+ tbody tr:nth-child(2) {
+ border-left: $border-thin;
+ border-right: $border-thin
+ }
+
+ tbody tr:nth-child(3) {
+ height: inherit
+ }
+
+ tr {
+ margin-bottom: 10px;
+ }
+}
+
+$color-font-link-medium: lighten($color-font-link, 20%)
\ No newline at end of file
diff --git a/modules/invoiceIn/back/locale/invoiceIn/en.yml b/modules/invoiceIn/back/locale/invoiceIn/en.yml
index 9e94eba0d..f590f9656 100644
--- a/modules/invoiceIn/back/locale/invoiceIn/en.yml
+++ b/modules/invoiceIn/back/locale/invoiceIn/en.yml
@@ -17,4 +17,6 @@ columns:
isVatDeductible: is VAT deductible
withholdingSageFk: withholding
expenseFkDeductible: expense deductible
- editorFk: editor
\ No newline at end of file
+ editorFk: editor
+ siiTrasCendencyInvoiceInFk: SII tax regime
+ siiTypeInvoiceInFk: SII Type
\ No newline at end of file
diff --git a/modules/invoiceIn/back/locale/invoiceIn/es.yml b/modules/invoiceIn/back/locale/invoiceIn/es.yml
index bd64c4327..64ded6aca 100644
--- a/modules/invoiceIn/back/locale/invoiceIn/es.yml
+++ b/modules/invoiceIn/back/locale/invoiceIn/es.yml
@@ -5,7 +5,7 @@ columns:
serial: serie
supplierFk: proveedor
issued: fecha emisión
- supplierRef: referéncia proveedor
+ supplierRef: referencia proveedor
isBooked: facturado
currencyFk: moneda
created: creado
@@ -17,4 +17,6 @@ columns:
isVatDeductible: impuesto deducible
withholdingSageFk: código de retención
expenseFkDeductible: gasto deducible
- editorFk: editor
\ No newline at end of file
+ editorFk: editor
+ siiTrasCendencyInvoiceInFk: régimen fiscal SII
+ siiTypeInvoiceInFk: tipo SII
\ No newline at end of file
diff --git a/modules/invoiceIn/back/methods/invoice-in/corrective.js b/modules/invoiceIn/back/methods/invoice-in/corrective.js
index 05f632bcd..e7088d201 100644
--- a/modules/invoiceIn/back/methods/invoice-in/corrective.js
+++ b/modules/invoiceIn/back/methods/invoice-in/corrective.js
@@ -44,7 +44,7 @@ module.exports = Self => {
correctingFk: clone.id,
correctedFk: id,
cplusRectificationTypeFk: invoiceType,
- siiTypeInvoiceOutFk: invoiceClass,
+ siiTypeInvoiceInFk: invoiceClass,
invoiceCorrectionTypeFk: invoiceReason
}, myOptions);
diff --git a/modules/invoiceIn/back/methods/invoice-in/filter.js b/modules/invoiceIn/back/methods/invoice-in/filter.js
index 936f7bb6c..f081368e4 100644
--- a/modules/invoiceIn/back/methods/invoice-in/filter.js
+++ b/modules/invoiceIn/back/methods/invoice-in/filter.js
@@ -91,6 +91,10 @@ module.exports = Self => {
{
arg: 'supplierActivityFk',
type: 'string',
+ },
+ {
+ arg: 'companyFk',
+ type: 'number',
}
],
returns: {
@@ -161,8 +165,8 @@ module.exports = Self => {
: {'ii.id': {nin: correcteds.map(x => x.correctingFk)}};
case 'correctedFk':
return {'ii.id': {inq: correctings.map(x => x.correctingFk)}};
- case 'supplierActivityFk':
- return {'s.supplierActivityFk': value};
+ case 'companyFk':
+ return {'ii.companyFk': value};
}
});
@@ -184,7 +188,9 @@ module.exports = Self => {
s.name supplierName,
s.account,
SUM(iid.amount) amount,
- sub.code awbCode
+ sub.code awbCode,
+ c.code,
+ MIN(iid.dueDated) dueDated
FROM invoiceIn ii
JOIN supplier s ON s.id = ii.supplierFk
LEFT JOIN invoiceInDueDay iid ON iid.invoiceInFk = ii.id
@@ -199,7 +205,8 @@ module.exports = Self => {
GROUP BY de.duaFk
) sub ON sub.duaFk = d.id
LEFT JOIN company co ON co.id = ii.companyFk
- LEFT JOIN dms dm ON dm.id = ii.docFk`
+ LEFT JOIN dms dm ON dm.id = ii.docFk
+ JOIN company c ON c.id = ii.companyFk`,
);
const sqlWhere = conn.makeWhere(filter.where);
diff --git a/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js b/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js
index c63f02439..aee8d3f2c 100644
--- a/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js
+++ b/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js
@@ -15,11 +15,11 @@ describe('invoiceIn corrective()', () => {
await tx.rollback();
});
- it('La función corrective debería devolver un id cuando se ejecuta correctamente', async() => {
+ it('should return an id when executed correctly', async() => {
const originalId = 1;
const invoiceReason = 3;
const invoiceType = 2;
- const invoiceClass = 1;
+ const invoiceClass = 8;
const cloneId = await models.InvoiceIn.corrective(ctx,
originalId, invoiceReason, invoiceType, invoiceClass, options);
@@ -30,7 +30,7 @@ describe('invoiceIn corrective()', () => {
}, options);
expect(correction.cplusRectificationTypeFk).toEqual(invoiceType);
- expect(correction.siiTypeInvoiceOutFk).toEqual(invoiceClass);
+ expect(correction.siiTypeInvoiceInFk).toEqual(invoiceClass);
expect(correction.invoiceCorrectionTypeFk).toEqual(invoiceReason);
});
});
diff --git a/modules/invoiceIn/back/methods/invoice-in/specs/filter.spec.js b/modules/invoiceIn/back/methods/invoice-in/specs/filter.spec.js
index 48310b32a..beaa608e6 100644
--- a/modules/invoiceIn/back/methods/invoice-in/specs/filter.spec.js
+++ b/modules/invoiceIn/back/methods/invoice-in/specs/filter.spec.js
@@ -166,4 +166,21 @@ describe('InvoiceIn filter()', () => {
throw e;
}
});
+
+ it('should return the invoice in matching companyFk', async() => {
+ const tx = await models.InvoiceIn.beginTransaction({});
+ const options = {transaction: tx};
+
+ try {
+ const company = await models.Company.findOne({}, options);
+ const invoicesByCompany = await models.InvoiceIn.find({where: {companyFk: company.id}}, options);
+ const filteredInvoices = await models.InvoiceIn.filter({args: {companyFk: company.id}}, {}, options);
+
+ expect(filteredInvoices.length).toEqual(invoicesByCompany.length);
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
});
diff --git a/modules/invoiceIn/back/methods/invoice-in/specs/invoiceIn.spec.js b/modules/invoiceIn/back/methods/invoice-in/specs/invoiceIn.spec.js
new file mode 100644
index 000000000..a83aad3b2
--- /dev/null
+++ b/modules/invoiceIn/back/methods/invoice-in/specs/invoiceIn.spec.js
@@ -0,0 +1,63 @@
+const models = require('vn-loopback/server/server').models;
+
+describe('invoiceIn', () => {
+ let options;
+ let tx;
+ const invoiceId = 1;
+ const supplierId = 791;
+ const currencyId = 1;
+ const companyId = 442;
+
+ beforeEach(async() => {
+ tx = await models.InvoiceIn.beginTransaction({});
+ options = {transaction: tx};
+ });
+
+ afterEach(async() => {
+ await tx.rollback();
+ });
+
+ it('should allow insert for new instance', async() => {
+ const newInvoice = {
+ supplierFk: supplierId,
+ issued: Date.vnNew(),
+ operated: Date.vnNew(),
+ currencyFk: currencyId,
+ companyFk: companyId,
+ isBooked: false
+ };
+
+ const createdInvoice = await models.InvoiceIn.create(newInvoice, options);
+
+ expect(createdInvoice).toBeDefined();
+ expect(createdInvoice.id).toBeDefined();
+ });
+
+ it('should throw an error if trying to update a booked invoice', async() => {
+ const invoice = await models.InvoiceIn.findById(invoiceId, null, options);
+ await invoice.updateAttribute('isBooked', true, options);
+
+ let error;
+ try {
+ await invoice.updateAttribute('supplierFk', supplierId, options);
+ } catch (err) {
+ error = err;
+ }
+
+ expect(error.message).toBe('InvoiceIn is already booked');
+ });
+
+ it('should throw an error if trying to delete a booked invoice', async() => {
+ const invoice = await models.InvoiceIn.findById(invoiceId, null, options);
+ await invoice.updateAttribute('isBooked', true, options);
+
+ let error;
+ try {
+ await models.InvoiceIn.deleteById(invoiceId, options);
+ } catch (err) {
+ error = err;
+ }
+
+ expect(error.message).toBe('InvoiceIn is already booked');
+ });
+});
diff --git a/modules/invoiceIn/back/methods/invoice-in/specs/invoiceInTax.spec.js b/modules/invoiceIn/back/methods/invoice-in/specs/invoiceInTax.spec.js
new file mode 100644
index 000000000..e822189bd
--- /dev/null
+++ b/modules/invoiceIn/back/methods/invoice-in/specs/invoiceInTax.spec.js
@@ -0,0 +1,74 @@
+const models = require('vn-loopback/server/server').models;
+
+describe('invoiceInTax', () => {
+ let options;
+ let tx;
+ const invoiceInId = 1;
+ const invoiceInTaxId = 1;
+ beforeEach(async() => {
+ tx = await models.InvoiceInTax.beginTransaction({});
+ options = {transaction: tx};
+ });
+
+ afterEach(async() => {
+ await tx.rollback();
+ });
+
+ it('should throw an error if trying to save a tax from a booked invoice', async() => {
+ const invoiceIn = await models.InvoiceIn.findById(invoiceInId, null, options);
+ await invoiceIn.updateAttributes({isBooked: true}, options);
+ const invoiceInTax = await models.InvoiceInTax.findById(invoiceInTaxId, null, options);
+ let error;
+ try {
+ await invoiceInTax.updateAttribute('taxableBase', 100, options);
+ } catch (err) {
+ error = err;
+ }
+
+ expect(error.message).toBe('InvoiceIn is already booked');
+ });
+
+ it('should allow save if the invoice is not booked', async() => {
+ const invoiceIn = await models.InvoiceIn.findById(invoiceInId, null, options);
+ await invoiceIn.updateAttribute('isBooked', false, options);
+
+ const invoiceInTax = await models.InvoiceInTax.findById(invoiceInTaxId, null, options);
+ await invoiceInTax.updateAttribute('taxableBase', 100, options);
+
+ const updatedInvoiceInTax = await models.InvoiceInTax.findById(invoiceInTaxId, null, options);
+
+ expect(updatedInvoiceInTax.taxableBase).toBe(100);
+ });
+
+ it('should throw an error if trying to delete a tax from a booked invoice', async() => {
+ const invoiceIn = await models.InvoiceIn.findById(invoiceInId, null, options);
+ await invoiceIn.updateAttribute('isBooked', true, options);
+
+ let error;
+ try {
+ await models.InvoiceInTax.destroyById(invoiceInTaxId, options);
+ } catch (err) {
+ error = err;
+ }
+
+ expect(error).toBeDefined();
+ expect(error.message).toBe('InvoiceIn is already booked');
+ });
+
+ it('should allow delete if the invoice is not booked', async() => {
+ const invoiceIn = await models.InvoiceIn.findById(invoiceInId, null, options);
+ await invoiceIn.updateAttribute('isBooked', false, options);
+
+ let error;
+ try {
+ await models.InvoiceInTax.destroyById(invoiceInTaxId, options);
+ } catch (err) {
+ error = err;
+ }
+
+ const deletedInvoiceInTax = await models.InvoiceInTax.findById(invoiceInTaxId, null, options);
+
+ expect(error).toBeUndefined();
+ expect(deletedInvoiceInTax).toBeNull();
+ });
+});
diff --git a/modules/invoiceIn/back/methods/invoice-in/specs/updateInvoiceIn.spec.js b/modules/invoiceIn/back/methods/invoice-in/specs/updateInvoiceIn.spec.js
new file mode 100644
index 000000000..773e2ac2f
--- /dev/null
+++ b/modules/invoiceIn/back/methods/invoice-in/specs/updateInvoiceIn.spec.js
@@ -0,0 +1,59 @@
+const models = require('vn-loopback/server/server').models;
+
+const invoiceInId = 1;
+const supplierId = 791;
+describe('invoiceIn updateInvoiceIn()', () => {
+ const ctx = beforeAll.getCtx();
+ let options;
+ let tx;
+
+ beforeEach(async() => {
+ options = {transaction: tx};
+ tx = await models.Sale.beginTransaction({});
+ options.transaction = tx;
+ });
+
+ afterEach(async() => {
+ await tx.rollback();
+ });
+
+ it('should update the invoice', async() => {
+ const invoiceBefore = await models.InvoiceIn.findById(invoiceInId, null, options);
+ await update(ctx, options);
+ const invoiceAfter = await models.InvoiceIn.findById(invoiceInId, null, options);
+
+ expect(invoiceAfter.supplierFk).not.toBe(invoiceBefore.supplierFk);
+ expect(invoiceAfter.supplierFk).toBe(supplierId);
+ });
+
+ it('should not update the invoice if is booked', async() => {
+ let error;
+ try {
+ await models.InvoiceIn.toBook(ctx, invoiceInId, options);
+ await update(ctx, options);
+ } catch (e) {
+ error = e;
+ }
+
+ expect(error.message).toBe('InvoiceIn is already booked');
+ });
+});
+
+async function update(ctx, opts) {
+ const supplierRef = 'mockRef';
+ const currencyId = 1;
+ await models.InvoiceIn.updateInvoiceIn(ctx,
+ invoiceInId,
+ supplierId,
+ supplierRef,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ currencyId,
+ undefined,
+ undefined,
+ opts);
+}
diff --git a/modules/invoiceIn/back/methods/invoice-in/summary.js b/modules/invoiceIn/back/methods/invoice-in/summary.js
index fe198b2b4..b3fd9ee97 100644
--- a/modules/invoiceIn/back/methods/invoice-in/summary.js
+++ b/modules/invoiceIn/back/methods/invoice-in/summary.js
@@ -37,7 +37,13 @@ module.exports = Self => {
{
relation: 'supplier',
scope: {
- fields: ['id', 'name']
+ fields: ['id', 'name', 'isVies', 'countryFk'],
+ include: [{
+ relation: 'country',
+ scope: {
+ fields: ['id', 'code']
+ }
+ }]
}
},
{
diff --git a/modules/invoiceIn/back/methods/invoice-in/toUnbook.js b/modules/invoiceIn/back/methods/invoice-in/toUnbook.js
index a697e9ddc..c27354d73 100644
--- a/modules/invoiceIn/back/methods/invoice-in/toUnbook.js
+++ b/modules/invoiceIn/back/methods/invoice-in/toUnbook.js
@@ -52,7 +52,8 @@ module.exports = Self => {
accountingEntries = await models.Xdiario.count({ASIEN: asien}, myOptions);
await models.Xdiario.destroyAll({ASIEN: asien}, myOptions);
- await Self.updateAll({id: invoiceInId}, {isBooked: false}, myOptions);
+ const invoiceIn = await Self.findById(invoiceInId, myOptions);
+ await invoiceIn.updateAttribute('isBooked', false, myOptions);
} else {
const linkedBookEntry = await models.Xdiario.findOne({
fields: ['ASIEN'],
diff --git a/modules/invoiceIn/back/methods/invoice-in/updateInvoiceIn.js b/modules/invoiceIn/back/methods/invoice-in/updateInvoiceIn.js
index 92a1ba8ee..2f1b4caca 100644
--- a/modules/invoiceIn/back/methods/invoice-in/updateInvoiceIn.js
+++ b/modules/invoiceIn/back/methods/invoice-in/updateInvoiceIn.js
@@ -82,7 +82,7 @@ module.exports = Self => {
try {
const invoiceIn = await Self.findById(id, null, myOptions);
- invoiceIn.updateAttributes({supplierFk,
+ await invoiceIn.updateAttributes({supplierFk,
supplierRef,
issued,
operated,
@@ -94,6 +94,7 @@ module.exports = Self => {
companyFk,
withholdingSageFk
}, myOptions);
+
if (tx) await tx.commit();
return invoiceIn;
} catch (e) {
diff --git a/modules/invoiceIn/back/models/invoice-in-correction.json b/modules/invoiceIn/back/models/invoice-in-correction.json
index 52e16d420..d353f9e98 100644
--- a/modules/invoiceIn/back/models/invoice-in-correction.json
+++ b/modules/invoiceIn/back/models/invoice-in-correction.json
@@ -28,11 +28,10 @@
"model": "InvoiceCorrectionType",
"foreignKey": "invoiceCorrectionTypeFk"
},
- "siiTypeInvoiceOut": {
+ "siiTypeInvoiceIn": {
"type": "belongsTo",
- "model": "SiiTypeInvoiceOut",
- "foreignKey": "siiTypeInvoiceOutFk"
+ "model": "SiiTypeInvoiceIn",
+ "foreignKey": "siiTypeInvoiceInFk"
}
-
}
}
\ No newline at end of file
diff --git a/modules/invoiceIn/back/models/invoice-in-tax.js b/modules/invoiceIn/back/models/invoice-in-tax.js
new file mode 100644
index 000000000..ce33fe18f
--- /dev/null
+++ b/modules/invoiceIn/back/models/invoice-in-tax.js
@@ -0,0 +1,18 @@
+const UserError = require('vn-loopback/util/user-error');
+
+module.exports = Self => {
+ Self.observe('before save', async function(ctx) {
+ if (ctx.isNewInstance) return;
+
+ const models = Self.app.models;
+ const invoiceIn = await models.InvoiceIn.findById(ctx.currentInstance.invoiceInFk, null, ctx.options);
+ if (invoiceIn.isBooked) throw new UserError('InvoiceIn is already booked');
+ });
+
+ Self.observe('before delete', async function(ctx) {
+ const models = Self.app.models;
+ const invoiceInTax = await Self.findById(ctx.where.id, null, ctx.options);
+ const invoiceIn = await models.InvoiceIn.findById(invoiceInTax.invoiceInFk, null, ctx.options);
+ if (invoiceIn.isBooked) throw new UserError('InvoiceIn is already booked');
+ });
+};
diff --git a/modules/invoiceIn/back/models/invoice-in-tax.json b/modules/invoiceIn/back/models/invoice-in-tax.json
index 53b5548b6..256ee0553 100644
--- a/modules/invoiceIn/back/models/invoice-in-tax.json
+++ b/modules/invoiceIn/back/models/invoice-in-tax.json
@@ -22,12 +22,11 @@
"type": "number"
},
"expenseFk": {
- "type": "number"
+ "type": "string"
},
"created": {
"type": "date"
}
-
},
"relations": {
"invoiceIn": {
@@ -51,4 +50,4 @@
"foreignKey": "transactionTypeSageFk"
}
}
-}
+}
\ No newline at end of file
diff --git a/modules/invoiceIn/back/models/invoice-in.js b/modules/invoiceIn/back/models/invoice-in.js
index 1e69c0ef8..ca506b54d 100644
--- a/modules/invoiceIn/back/models/invoice-in.js
+++ b/modules/invoiceIn/back/models/invoice-in.js
@@ -19,4 +19,25 @@ module.exports = Self => {
return new UserError(`This invoice has a linked vehicle.`);
return err;
});
+
+ Self.observe('before save', async function(ctx) {
+ if (ctx.isNewInstance) return;
+
+ const changes = ctx.data || ctx.instance;
+ const orgData = ctx.currentInstance;
+ let isNotEditable = orgData.isBooked || (!orgData.isBooked && changes.isBooked);
+
+ if (isNotEditable) {
+ for (const [key, value] of Object.entries(changes)) {
+ if (key !== 'isBooked' && value !== orgData[key])
+ throw new UserError('InvoiceIn is already booked');
+ }
+ }
+ });
+
+ Self.observe('before delete', async function(ctx) {
+ const invoiceIn = await Self.findById(ctx.where.id, null, ctx.options);
+ if (invoiceIn.isBooked) throw new UserError('InvoiceIn is already booked');
+ });
};
+
diff --git a/modules/invoiceOut/back/methods/invoiceOut/clientsToInvoice.js b/modules/invoiceOut/back/methods/invoiceOut/clientsToInvoice.js
index 5526d214a..7befdcbeb 100644
--- a/modules/invoiceOut/back/methods/invoiceOut/clientsToInvoice.js
+++ b/modules/invoiceOut/back/methods/invoiceOut/clientsToInvoice.js
@@ -1,3 +1,5 @@
+const UserError = require('vn-loopback/util/user-error');
+
module.exports = Self => {
Self.remoteMethodCtx('clientsToInvoice', {
description: 'Get the clients to make global invoicing',
@@ -47,7 +49,12 @@ module.exports = Self => {
}
try {
- // Packaging liquidation
+ const clientCanBeInvoiced =
+ await Self.app.models.Client.canBeInvoiced(clientId, companyFk, myOptions);
+
+ if (!clientCanBeInvoiced)
+ throw new UserError(`This client can't be invoiced`);
+
const vIsAllInvoiceable = false;
await Self.rawSql('CALL ticketPackaging_add(?, ?, ?, ?)', [
clientId,
@@ -71,9 +78,6 @@ module.exports = Self => {
AND t.shipped BETWEEN ? AND util.dayEnd(?)
AND (t.clientFk = ? OR ? IS NULL )
AND t.companyFk = ?
- AND c.hasToInvoice
- AND c.isTaxDataChecked
- AND c.isActive
AND NOT t.isDeleted
GROUP BY IF(c.hasToInvoiceByAddress, a.id, c.id)
HAVING SUM(t.totalWithVat) > 0;`;
diff --git a/modules/invoiceOut/back/methods/invoiceOut/createManualInvoice.js b/modules/invoiceOut/back/methods/invoiceOut/createManualInvoice.js
index c46da0ba5..a06128848 100644
--- a/modules/invoiceOut/back/methods/invoiceOut/createManualInvoice.js
+++ b/modules/invoiceOut/back/methods/invoiceOut/createManualInvoice.js
@@ -10,6 +10,11 @@ module.exports = Self => {
type: 'any',
description: 'The invoiceable client id'
},
+ {
+ arg: 'addressFk',
+ type: 'any',
+ description: 'The address id'
+ },
{
arg: 'ticketFk',
type: 'any',
@@ -23,7 +28,8 @@ module.exports = Self => {
{
arg: 'serial',
type: 'string',
- description: 'The invoice serial'
+ description: 'The invoice serial',
+ required: true
},
{
arg: 'taxArea',
@@ -46,108 +52,126 @@ module.exports = Self => {
}
});
- Self.createManualInvoice = async(ctx, clientFk, ticketFk, maxShipped, serial, taxArea, reference, options) => {
- if (!clientFk && !ticketFk) throw new UserError(`Select ticket or client`);
- const models = Self.app.models;
- const myOptions = {userId: ctx.req.accessToken.userId};
- let tx;
+ Self.createManualInvoice =
+ async(ctx, clientFk, addressFk, ticketFk, maxShipped, serial, taxArea, reference, options) => {
+ if (!clientFk && !ticketFk) throw new UserError(`Select ticket or client`);
+ const models = Self.app.models;
+ const myOptions = {userId: ctx.req.accessToken.userId};
+ let tx;
- if (typeof options == 'object')
- Object.assign(myOptions, options);
+ if (typeof options == 'object')
+ Object.assign(myOptions, options);
- if (!myOptions.transaction) {
- tx = await Self.beginTransaction({});
- myOptions.transaction = tx;
- }
+ if (!myOptions.transaction) {
+ tx = await Self.beginTransaction({});
+ myOptions.transaction = tx;
+ }
- let companyId;
- let newInvoice;
- let query;
- try {
- if (ticketFk) {
- const ticket = await models.Ticket.findById(ticketFk, null, myOptions);
- const company = await models.Company.findById(ticket.companyFk, null, myOptions);
+ let companyFk;
+ let newInvoice;
+ let query;
+ try {
+ if (ticketFk) {
+ const ticket = await models.Ticket.findById(ticketFk, {
+ fields: ['clientFk', 'companyFk', 'shipped', 'refFk', 'totalWithVat']
+ }, myOptions);
+ const company = await models.Company.findById(ticket.companyFk, {
+ fields: ['code']
+ }, myOptions);
- clientFk = ticket.clientFk;
- maxShipped = ticket.shipped;
- companyId = ticket.companyFk;
+ clientFk = ticket.clientFk;
+ maxShipped = ticket.shipped;
+ companyFk = ticket.companyFk;
- // Validates invoiced ticket
- if (ticket.refFk)
- throw new UserError('This ticket is already invoiced');
+ if (ticket.refFk)
+ throw new UserError('This ticket is already invoiced');
- // Validates ticket amount
- if (ticket.totalWithVat == 0)
- throw new UserError(`A ticket with an amount of zero can't be invoiced`);
+ if (ticket.totalWithVat == 0)
+ throw new UserError(`A ticket with an amount of zero can't be invoiced`);
- // Validates ticket nagative base
- const hasNegativeBase = await getNegativeBase(maxShipped, clientFk, companyId, myOptions);
- if (hasNegativeBase && company.code == 'VNL')
- throw new UserError(`A ticket with a negative base can't be invoiced`);
- } else {
- if (!maxShipped)
- throw new UserError(`Max shipped required`);
+ const hasNegativeBase = await getNegativeBase(maxShipped, clientFk, companyFk, myOptions);
+ if (hasNegativeBase && company.code == 'VNL')
+ throw new UserError(`A ticket with a negative base can't be invoiced`);
+ } else {
+ if (!maxShipped)
+ throw new UserError(`Max shipped required`);
- const company = await models.Ticket.findOne({
- fields: ['companyFk'],
- where: {
- clientFk: clientFk,
- shipped: {lte: maxShipped}
+ if (addressFk) {
+ const address = await models.Address.findById(addressFk, {
+ fields: ['clientFk']
+ }, myOptions);
+
+ if (clientFk && clientFk !== address.clientFk)
+ throw new UserError('The provided clientFk does not match');
}
- }, myOptions);
- companyId = company.companyFk;
+ const company = await models.Ticket.findOne({
+ fields: ['companyFk'],
+ where: {
+ clientFk: clientFk,
+ shipped: {lte: maxShipped}
+ }
+ }, myOptions);
+ companyFk = company.companyFk;
+ }
+
+ const isClientInvoiceable = await isInvoiceable(clientFk, myOptions);
+ if (!isClientInvoiceable)
+ throw new UserError(`This client is not invoiceable`);
+
+ const tomorrow = Date.vnNew();
+ tomorrow.setDate(tomorrow.getDate() + 1);
+
+ if (maxShipped >= tomorrow)
+ throw new UserError(`Can't invoice to future`);
+
+ const maxInvoiceDate = await getMaxIssued(serial, companyFk, myOptions);
+ if (Date.vnNew() < maxInvoiceDate)
+ throw new UserError(`Can't invoice to past`);
+
+ if (ticketFk) {
+ query = `CALL invoiceOut_newFromTicket(?, ?, ?, ?, @newInvoiceId)`;
+ await Self.rawSql(query, [
+ ticketFk,
+ serial,
+ taxArea,
+ reference
+ ], myOptions);
+ } else if (addressFk) {
+ query = `CALL invoiceOut_newFromAddress(?, ?, ?, ?, ?, ?, @newInvoiceId)`;
+ await Self.rawSql(query, [
+ addressFk,
+ serial,
+ maxShipped,
+ companyFk,
+ taxArea,
+ reference
+ ], myOptions);
+ } else {
+ query = `CALL invoiceOut_newFromClient(?, ?, ?, ?, ?, ?, @newInvoiceId)`;
+ await Self.rawSql(query, [
+ clientFk,
+ serial,
+ maxShipped,
+ companyFk,
+ taxArea,
+ reference
+ ], myOptions);
+ }
+
+ [newInvoice] = await Self.rawSql(`SELECT @newInvoiceId id`, null, myOptions);
+
+ if (tx) await tx.commit();
+ } catch (e) {
+ if (tx) await tx.rollback();
+ throw e;
}
- // Validate invoiceable client
- const isClientInvoiceable = await isInvoiceable(clientFk, myOptions);
- if (!isClientInvoiceable)
- throw new UserError(`This client is not invoiceable`);
+ if (!newInvoice.id) throw new UserError('It was not able to create the invoice');
- // Can't invoice tickets into future
- const tomorrow = Date.vnNew();
- tomorrow.setDate(tomorrow.getDate() + 1);
+ await Self.createPdf(ctx, newInvoice.id);
- if (maxShipped >= tomorrow)
- throw new UserError(`Can't invoice to future`);
-
- const maxInvoiceDate = await getMaxIssued(serial, companyId, myOptions);
- if (Date.vnNew() < maxInvoiceDate)
- throw new UserError(`Can't invoice to past`);
-
- if (ticketFk) {
- query = `CALL invoiceOut_newFromTicket(?, ?, ?, ?, @newInvoiceId)`;
- await Self.rawSql(query, [
- ticketFk,
- serial,
- taxArea,
- reference
- ], myOptions);
- } else {
- query = `CALL invoiceOut_newFromClient(?, ?, ?, ?, ?, ?, @newInvoiceId)`;
- await Self.rawSql(query, [
- clientFk,
- serial,
- maxShipped,
- companyId,
- taxArea,
- reference
- ], myOptions);
- }
-
- [newInvoice] = await Self.rawSql(`SELECT @newInvoiceId id`, null, myOptions);
-
- if (tx) await tx.commit();
- } catch (e) {
- if (tx) await tx.rollback();
- throw e;
- }
-
- if (!newInvoice.id) throw new UserError('It was not able to create the invoice');
-
- await Self.createPdf(ctx, newInvoice.id);
-
- return newInvoice;
- };
+ return newInvoice;
+ };
async function isInvoiceable(clientFk, options) {
const models = Self.app.models;
@@ -159,10 +183,10 @@ module.exports = Self => {
return result.invoiceable;
}
- async function getNegativeBase(maxShipped, clientFk, companyId, options) {
+ async function getNegativeBase(maxShipped, clientFk, companyFk, options) {
const models = Self.app.models;
await models.InvoiceOut.rawSql('CALL invoiceOut_exportationFromClient(?,?,?)',
- [maxShipped, clientFk, companyId], options
+ [maxShipped, clientFk, companyFk], options
);
const query = 'SELECT vn.hasAnyNegativeBase() AS base';
const [result] = await models.InvoiceOut.rawSql(query, [], options);
@@ -170,14 +194,14 @@ module.exports = Self => {
return result.base;
}
- async function getMaxIssued(serial, companyId, options) {
+ async function getMaxIssued(serial, companyFk, options) {
const models = Self.app.models;
const query = `SELECT MAX(issued) AS issued
FROM invoiceOut
WHERE serial = ? AND companyFk = ?`;
const [maxIssued] = await models.InvoiceOut.rawSql(query,
- [serial, companyId], options);
- const maxInvoiceDate = maxIssued && maxIssued.issued || Date.vnNew();
+ [serial, companyFk], options);
+ const maxInvoiceDate = maxIssued?.issued || Date.vnNew();
return maxInvoiceDate;
}
diff --git a/modules/invoiceOut/back/methods/invoiceOut/delete.js b/modules/invoiceOut/back/methods/invoiceOut/delete.js
index d6efd9961..1ab9a582b 100644
--- a/modules/invoiceOut/back/methods/invoiceOut/delete.js
+++ b/modules/invoiceOut/back/methods/invoiceOut/delete.js
@@ -37,7 +37,7 @@ module.exports = Self => {
const tickets = await models.Ticket.find({
where: {refFk: invoiceOut.ref}
}, myOptions);
-
+
const [bookEntry] = await models.Xdiario.find({
where: {
SERIE: invoiceOut.ref[0],
@@ -55,13 +55,13 @@ module.exports = Self => {
if (bookEntry) {
if (bookEntry.enlazadoSage) {
const params = {
- bookEntry: bookEntry.ASIEN,
+ bookEntry: bookEntry.ASIEN,
invoiceOutRef: invoiceOut.ref
- }
+ };
await Self.rawSql(`SELECT util.notification_send('book-entry-deleted', ?, NULL)`,
[JSON.stringify(params)],
myOptions);
- };
+ }
await models.Xdiario.destroyAll({
ASIEN: bookEntry.ASIEN
diff --git a/modules/invoiceOut/back/methods/invoiceOut/filter.js b/modules/invoiceOut/back/methods/invoiceOut/filter.js
index 3b6aa4d82..ab6782140 100644
--- a/modules/invoiceOut/back/methods/invoiceOut/filter.js
+++ b/modules/invoiceOut/back/methods/invoiceOut/filter.js
@@ -14,6 +14,12 @@ module.exports = Self => {
description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string',
http: {source: 'query'}
},
+ {
+ arg: 'id',
+ type: 'number',
+ description: 'The invoiceOut id',
+ http: {source: 'query'}
+ },
{
arg: 'search',
type: 'string',
@@ -112,6 +118,8 @@ module.exports = Self => {
return {'i.created': value};
case 'clientFk':
return {'i.clientFk': value};
+ case 'id':
+ return {'i.id': value};
case 'fi':
return {'c.fi': value};
case 'amount':
diff --git a/modules/invoiceOut/back/methods/invoiceOut/getInvoiceDate.js b/modules/invoiceOut/back/methods/invoiceOut/getInvoiceDate.js
index dcc1fa6e8..493f19aa7 100644
--- a/modules/invoiceOut/back/methods/invoiceOut/getInvoiceDate.js
+++ b/modules/invoiceOut/back/methods/invoiceOut/getInvoiceDate.js
@@ -7,7 +7,12 @@ module.exports = Self => {
arg: 'companyFk',
type: 'number',
required: true
- }
+ },
+ {
+ arg: 'serialType',
+ type: 'string',
+ required: true
+ },
],
returns: {
type: ['object'],
@@ -19,16 +24,16 @@ module.exports = Self => {
}
});
- Self.getInvoiceDate = async companyFk => {
+ Self.getInvoiceDate = async(companyFk, serialType) => {
const models = Self.app.models;
const [invoiceDate] = await models.InvoiceOut.rawSql(
`SELECT MAX(io.issued) issued
FROM invoiceOut io
JOIN invoiceOutSerial ios ON ios.code = io.serial
- WHERE ios.type = 'global'
- AND io.issued
+ WHERE ios.type = ?
+ AND io.issued
AND io.companyFk = ?`,
- [companyFk]
+ [serialType, companyFk]
);
return invoiceDate;
};
diff --git a/modules/invoiceOut/back/methods/invoiceOut/negativeBases.js b/modules/invoiceOut/back/methods/invoiceOut/negativeBases.js
index 76ef29604..9e491b35c 100644
--- a/modules/invoiceOut/back/methods/invoiceOut/negativeBases.js
+++ b/modules/invoiceOut/back/methods/invoiceOut/negativeBases.js
@@ -48,13 +48,13 @@ module.exports = Self => {
let stmt;
stmts.push(new ParameterizedSQL(
`CREATE OR REPLACE TEMPORARY TABLE tmp.ticket
- (KEY (ticketFk))
+ (INDEX (ticketFk))
ENGINE = MEMORY
SELECT id ticketFk
- FROM ticket t
+ FROM ticket
WHERE shipped BETWEEN ? AND util.dayEnd(?)
AND refFk IS NULL`, [args.from, args.to]));
- stmts.push(`CALL vn.ticket_getTax(NULL)`);
+ stmts.push(`CALL ticket_getTax(NULL)`);
stmts.push(new ParameterizedSQL(
`CREATE OR REPLACE TEMPORARY TABLE tmp.filter
ENGINE = MEMORY
@@ -71,12 +71,12 @@ module.exports = Self => {
c.isTaxDataChecked,
w.id comercialId,
u.name workerName
- FROM vn.ticket t
- JOIN vn.company co ON co.id = t.companyFk
- JOIN vn.sale s ON s.ticketFk = t.id
- JOIN vn.client c ON c.id = t.clientFk
- JOIN vn.country cou ON cou.id = c.countryFk
- LEFT JOIN vn.worker w ON w.id = c.salesPersonFk
+ FROM ticket t
+ JOIN company co ON co.id = t.companyFk
+ JOIN sale s ON s.ticketFk = t.id
+ JOIN client c ON c.id = t.clientFk
+ JOIN country cou ON cou.id = c.countryFk
+ LEFT JOIN worker w ON w.id = c.salesPersonFk
JOIN account.user u ON u.id = w.id
LEFT JOIN (
SELECT ticketFk, taxableBase
diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/clientsToInvoice.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/clientsToInvoice.spec.js
index 470690c5a..df0566c54 100644
--- a/modules/invoiceOut/back/methods/invoiceOut/specs/clientsToInvoice.spec.js
+++ b/modules/invoiceOut/back/methods/invoiceOut/specs/clientsToInvoice.spec.js
@@ -4,11 +4,11 @@ describe('InvoiceOut clientsToInvoice()', () => {
const userId = 1;
const clientId = 1101;
const companyFk = 442;
- const maxShipped = new Date();
+ const maxShipped = Date.vnNew();
maxShipped.setMonth(11);
maxShipped.setDate(31);
maxShipped.setHours(23, 59, 59, 999);
- const invoiceDate = new Date();
+ const invoiceDate = Date.vnNew();
const activeCtx = {
getLocale: () => {
return 'en';
diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/createManualInvoice.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/createManualInvoice.spec.js
index 55739e570..58c18b730 100644
--- a/modules/invoiceOut/back/methods/invoiceOut/specs/createManualInvoice.spec.js
+++ b/modules/invoiceOut/back/methods/invoiceOut/specs/createManualInvoice.spec.js
@@ -6,110 +6,90 @@ describe('InvoiceOut createManualInvoice()', () => {
const clientId = 1106;
const activeCtx = {accessToken: {userId: 1}};
const ctx = {req: activeCtx};
+ let tx; let options;
+
+ beforeEach(async() => {
+ spyOn(models.InvoiceOut, 'createPdf').and.returnValue(Promise.resolve(true));
+ spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
+ active: activeCtx
+ });
+
+ tx = await models.InvoiceOut.beginTransaction({});
+ options = {transaction: tx};
+ });
+
+ afterEach(async() => {
+ await tx.rollback();
+ });
it('should throw an error trying to invoice again', async() => {
- spyOn(models.InvoiceOut, 'createPdf').and.returnValue(new Promise(resolve => resolve(true)));
-
- const tx = await models.InvoiceOut.beginTransaction({});
- const options = {transaction: tx};
-
let error;
try {
- await createInvoice(ctx, options, undefined, ticketId);
- await createInvoice(ctx, options, undefined, ticketId);
-
- await tx.rollback();
+ await createInvoice(ctx, options, undefined, undefined, ticketId);
+ await createInvoice(ctx, options, undefined, undefined, ticketId);
} catch (e) {
error = e;
- await tx.rollback();
}
expect(error.message).toContain('This ticket is already invoiced');
});
it('should throw an error for a ticket with an amount of zero', async() => {
- spyOn(models.InvoiceOut, 'createPdf').and.returnValue(new Promise(resolve => resolve(true)));
- spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
- active: activeCtx
- });
-
- const tx = await models.InvoiceOut.beginTransaction({});
- const options = {transaction: tx};
-
let error;
try {
const ticket = await models.Ticket.findById(ticketId, null, options);
await ticket.updateAttributes({totalWithVat: 0}, options);
- await createInvoice(ctx, options, undefined, ticketId);
- await tx.rollback();
+ await createInvoice(ctx, options, undefined, undefined, ticketId);
} catch (e) {
error = e;
- await tx.rollback();
}
expect(error.message).toContain(`A ticket with an amount of zero can't be invoiced`);
});
it('should throw an error when the clientFk property is set without the max shipped date', async() => {
- spyOn(models.InvoiceOut, 'createPdf').and.returnValue(new Promise(resolve => resolve(true)));
-
- const tx = await models.InvoiceOut.beginTransaction({});
- const options = {transaction: tx};
-
let error;
try {
await createInvoice(ctx, options, clientId);
- await tx.rollback();
} catch (e) {
error = e;
- await tx.rollback();
}
expect(error.message).toContain(`Max shipped required`);
});
it('should throw an error for a non-invoiceable client', async() => {
- spyOn(models.InvoiceOut, 'createPdf').and.returnValue(new Promise(resolve => resolve(true)));
- spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
- active: activeCtx
- });
-
- const tx = await models.InvoiceOut.beginTransaction({});
- const options = {transaction: tx};
-
let error;
try {
const client = await models.Client.findById(clientId, null, options);
await client.updateAttributes({isTaxDataChecked: false}, options);
- await createInvoice(ctx, options, undefined, ticketId);
-
- await tx.rollback();
+ await createInvoice(ctx, options, undefined, undefined, ticketId);
} catch (e) {
error = e;
- await tx.rollback();
}
expect(error.message).toContain(`This client is not invoiceable`);
});
- it('should create a manual invoice', async() => {
- spyOn(models.InvoiceOut, 'createPdf').and.returnValue(new Promise(resolve => resolve(true)));
+ it('should create a manual invoice with ticket', async() => {
+ const result = await createInvoice(ctx, options, undefined, undefined, ticketId);
- const tx = await models.InvoiceOut.beginTransaction({});
- const options = {transaction: tx};
+ expect(result.id).toEqual(jasmine.any(Number));
+ });
- try {
- const result = await createInvoice(ctx, options, undefined, ticketId);
+ it('should create a manual invoice with client', async() => {
+ const result = await createInvoice(ctx, options, clientId, undefined, undefined, Date.vnNew());
- expect(result.id).toEqual(jasmine.any(Number));
+ expect(result.id).toEqual(jasmine.any(Number));
+ });
- await tx.rollback();
- } catch (e) {
- await tx.rollback();
- throw e;
- }
+ it('should create a manual invoice with address', async() => {
+ const addressFk = 126;
+ const result = await createInvoice(ctx, options, clientId, addressFk, undefined, Date.vnNew());
+
+ expect(result.id).toEqual(jasmine.any(Number));
});
});
@@ -117,6 +97,7 @@ function createInvoice(
ctx,
options,
clientFk = undefined,
+ addressFk = undefined,
ticketFk = undefined,
maxShipped = undefined,
serial = 'T',
@@ -124,6 +105,6 @@ function createInvoice(
reference = undefined
) {
return models.InvoiceOut.createManualInvoice(
- ctx, clientFk, ticketFk, maxShipped, serial, taxArea, reference, options
+ ctx, clientFk, addressFk, ticketFk, maxShipped, serial, taxArea, reference, options
);
}
diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/getInvoiceDate.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/getInvoiceDate.spec.js
new file mode 100644
index 000000000..830402250
--- /dev/null
+++ b/modules/invoiceOut/back/methods/invoiceOut/specs/getInvoiceDate.spec.js
@@ -0,0 +1,39 @@
+const models = require('vn-loopback/server/server').models;
+const moment = require('moment');
+
+describe('getInvoiceDate()', () => {
+ const companyFk = 442;
+ let tx;
+ let options;
+
+ beforeEach(async() => {
+ tx = await models.InvoiceOut.beginTransaction({});
+ options = {transaction: tx};
+ });
+
+ afterEach(async() => {
+ await tx.rollback();
+ });
+
+ it('should return a correct date for serialType "global"', async() => {
+ const serialType = 'global';
+ const result = await models.InvoiceOut.getInvoiceDate(companyFk, serialType, options);
+
+ expect(moment(result.issued).format('YYYY-MM-DD')).toEqual('2000-12-01');
+ });
+
+ it('should return null for serialType "multiple"', async() => {
+ const serialType = 'multiple';
+ const result = await models.InvoiceOut.getInvoiceDate(companyFk, serialType, options);
+
+ expect(result.issued).toBeNull();
+ });
+
+ it('should return correct date for serialType "quick"', async() => {
+ const serialType = 'quick';
+ const result = await models.InvoiceOut.getInvoiceDate(companyFk, serialType, options);
+
+ expect(moment(result.issued).format('YYYY-MM-DD')).toEqual('2001-01-01');
+ });
+});
+
diff --git a/modules/invoiceOut/back/model-config.json b/modules/invoiceOut/back/model-config.json
index 9c7512429..710d824c3 100644
--- a/modules/invoiceOut/back/model-config.json
+++ b/modules/invoiceOut/back/model-config.json
@@ -43,5 +43,8 @@
},
"SiiTypeInvoiceOut": {
"dataSource": "vn"
+ },
+ "SiiTypeInvoiceIn": {
+ "dataSource": "vn"
}
-}
+}
\ No newline at end of file
diff --git a/modules/invoiceOut/back/models/invoice-out.js b/modules/invoiceOut/back/models/invoice-out.js
index bab1fa375..f8fc8cdbf 100644
--- a/modules/invoiceOut/back/models/invoice-out.js
+++ b/modules/invoiceOut/back/models/invoice-out.js
@@ -79,6 +79,8 @@ module.exports = Self => {
type
],
myOptions);
+ if (!serial)
+ throw new UserError('No invoice series found for these parameters');
const invoiceOutSerial = await Self.app.models.InvoiceOutSerial.findById(serial);
if (invoiceOutSerial?.taxAreaFk == 'WORLD') {
diff --git a/modules/invoiceOut/back/models/sii-type-invoice-in.json b/modules/invoiceOut/back/models/sii-type-invoice-in.json
new file mode 100644
index 000000000..a191febb9
--- /dev/null
+++ b/modules/invoiceOut/back/models/sii-type-invoice-in.json
@@ -0,0 +1,22 @@
+{
+ "name": "SiiTypeInvoiceIn",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "siiTypeInvoiceIn"
+ }
+ },
+ "properties": {
+ "id": {
+ "id": true,
+ "type": "number",
+ "description": "Identifier"
+ },
+ "code": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ }
+ }
+}
\ No newline at end of file
diff --git a/modules/invoiceOut/back/models/sii-type-invoice-out.json b/modules/invoiceOut/back/models/sii-type-invoice-out.json
index 37fd39c38..89f01bd74 100644
--- a/modules/invoiceOut/back/models/sii-type-invoice-out.json
+++ b/modules/invoiceOut/back/models/sii-type-invoice-out.json
@@ -17,9 +17,6 @@
},
"description": {
"type": "string"
- },
- "code": {
- "type": "string"
}
}
-}
+}
\ No newline at end of file
diff --git a/modules/invoiceOut/front/index.js b/modules/invoiceOut/front/index.js
index a5e51d439..6d58a0a45 100644
--- a/modules/invoiceOut/front/index.js
+++ b/modules/invoiceOut/front/index.js
@@ -1,7 +1,7 @@
export * from './module';
import './main';
-import './summary';
import './descriptor';
import './descriptor-popover';
import './descriptor-menu';
+import './summary';
diff --git a/modules/invoiceOut/front/routes.json b/modules/invoiceOut/front/routes.json
index 7c7495cb9..908df3972 100644
--- a/modules/invoiceOut/front/routes.json
+++ b/modules/invoiceOut/front/routes.json
@@ -34,6 +34,12 @@
"params": {
"invoice-out": "$ctrl.invoiceOut"
}
+ },
+ {
+ "url": "/:id",
+ "state": "invoiceOut.card",
+ "abstract": true,
+ "component": "vn-invoice-out-card"
}
]
}
diff --git a/modules/item/back/locale/item-minimum-quantity/en.yml b/modules/item/back/locale/item-minimum-quantity/en.yml
new file mode 100644
index 000000000..206b1d96b
--- /dev/null
+++ b/modules/item/back/locale/item-minimum-quantity/en.yml
@@ -0,0 +1,5 @@
+name: Minimum Quantity
+columns:
+ ended: Ended
+ code: Code
+ started: Started
\ No newline at end of file
diff --git a/modules/item/back/locale/item-minimum-quantity/es.yml b/modules/item/back/locale/item-minimum-quantity/es.yml
new file mode 100644
index 000000000..68c67eeff
--- /dev/null
+++ b/modules/item/back/locale/item-minimum-quantity/es.yml
@@ -0,0 +1,5 @@
+name: Cantidad Mínima
+columns:
+ ended: Finaliza
+ quantity: Cantidad
+ started: Comienza
diff --git a/modules/item/back/locale/item/en.yml b/modules/item/back/locale/item/en.yml
index ea40fd34b..f5e6fcf9a 100644
--- a/modules/item/back/locale/item/en.yml
+++ b/modules/item/back/locale/item/en.yml
@@ -46,4 +46,4 @@ columns:
itemFk: item
density: density
compression: compression
-
+ minQuantity: min quantity
diff --git a/modules/item/back/locale/item/es.yml b/modules/item/back/locale/item/es.yml
index 973f5e94f..68020d452 100644
--- a/modules/item/back/locale/item/es.yml
+++ b/modules/item/back/locale/item/es.yml
@@ -46,4 +46,4 @@ columns:
itemFk: artículo
density: densidad
compression: compresión
-
+ minQuantity: Cantidad mínima
diff --git a/modules/item/back/methods/item-shelving-sale/filter.js b/modules/item/back/methods/item-shelving-sale/filter.js
index 01a9f1856..edd04b61f 100644
--- a/modules/item/back/methods/item-shelving-sale/filter.js
+++ b/modules/item/back/methods/item-shelving-sale/filter.js
@@ -41,7 +41,7 @@ module.exports = Self => {
u.name
FROM itemShelvingSale iss
LEFT JOIN itemShelving ish ON iss.itemShelvingFk = ish.id
- LEFT JOIN shelving s ON ish.shelvingFk = s.code
+ LEFT JOIN shelving s ON ish.shelvingFk = s.id
LEFT JOIN parking p ON s.parkingFk = p.id
LEFT JOIN account.user u ON u.id = iss.userFk`
);
diff --git a/modules/item/back/methods/item-shelving/deleteItemShelvings.js b/modules/item/back/methods/item-shelving/deleteItemShelvings.js
index f534b4e9a..fbc354cce 100644
--- a/modules/item/back/methods/item-shelving/deleteItemShelvings.js
+++ b/modules/item/back/methods/item-shelving/deleteItemShelvings.js
@@ -34,6 +34,11 @@ module.exports = Self => {
try {
const promises = [];
for (let itemShelvingId of itemShelvingIds) {
+ const itemShelvingSaleToDelete = models.ItemShelvingSale.destroyAll({
+ itemShelvingFk: itemShelvingId
+ }, myOptions);
+ promises.push(itemShelvingSaleToDelete);
+
const itemShelvingToDelete = models.ItemShelving.destroyById(itemShelvingId, myOptions);
promises.push(itemShelvingToDelete);
}
diff --git a/modules/item/back/methods/item-shelving/getAlternative.js b/modules/item/back/methods/item-shelving/getAlternative.js
index 8108bfa6e..de34739bc 100644
--- a/modules/item/back/methods/item-shelving/getAlternative.js
+++ b/modules/item/back/methods/item-shelving/getAlternative.js
@@ -3,7 +3,7 @@ module.exports = Self => {
description: 'Returns a list of items and possible alternative locations',
accessType: 'READ',
accepts: [{
- arg: 'shelvingFk',
+ arg: 'shelvingCode',
type: 'string',
required: true,
}],
@@ -17,13 +17,21 @@ module.exports = Self => {
}
});
- Self.getAlternative = async(shelvingFk, options) => {
+ Self.getAlternative = async(shelvingCode, options) => {
const models = Self.app.models;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
+ const shelving = await models.Shelving.findOne({
+ where: {
+ code: shelvingCode
+ }
+ });
+
+ if (!shelving) return [];
+ const {id: shelvingFk} = shelving;
const filterItemShelvings = {
fields: ['id', 'visible', 'itemFk', 'shelvingFk'],
where: {shelvingFk},
@@ -42,7 +50,7 @@ module.exports = Self => {
if (itemShelvings) {
const [alternatives] = await models.ItemShelving.rawSql('CALL vn.itemShelving_getAlternatives(?)',
- [shelvingFk], myOptions
+ [shelvingCode], myOptions
);
return itemShelvings.map(itemShelving => {
const item = itemShelving.item();
diff --git a/modules/item/back/methods/item-shelving/getItemsByReviewOrder.js b/modules/item/back/methods/item-shelving/getItemsByReviewOrder.js
new file mode 100644
index 000000000..7a960a8c8
--- /dev/null
+++ b/modules/item/back/methods/item-shelving/getItemsByReviewOrder.js
@@ -0,0 +1,89 @@
+module.exports = Self => {
+ const models = require('vn-loopback/server/server').models;
+ Self.remoteMethod('getItemsByReviewOrder', {
+ description:
+ 'Get list items if they are ordered by pickingOrder and their created regarding where they will be parked',
+ accessType: 'READ',
+ accepts: [{
+ arg: 'shelving',
+ type: 'string',
+ required: true,
+ description: 'Shelving code'
+ },
+ {
+ arg: 'parking',
+ type: 'string',
+ required: true,
+ description: 'Parking code'
+ },
+ {
+ arg: 'itemFk',
+ type: 'number',
+ description: 'Item id'
+ },
+ ],
+ returns: {
+ type: 'Array',
+ root: true
+ },
+ http: {
+ path: `/getItemsByReviewOrder`,
+ verb: 'GET'
+ }
+ });
+
+ Self.getItemsByReviewOrder = async(shelving, parking, itemFk, options) => {
+ const myOptions = {};
+ if (typeof options == 'object')
+ Object.assign(myOptions, options);
+
+ const config = await models.ProductionConfig.findOne();
+ const hoursToCompare = config['itemOrderReviewHours'];
+ if (!hoursToCompare) return [];
+
+ const parkingItem = await models.Parking.findOne({where: {code: parking}}, myOptions);
+ if (!parkingItem) return [];
+ const pickingOrderToCompare = parkingItem['pickingOrder'];
+
+ const result = await Self.rawSql(`
+ WITH currentItemShelving AS (
+ SELECT is2.created, is2.itemFk, sh.code
+ FROM vn.itemShelving is2
+ JOIN vn.shelving sh ON sh.id = is2.shelvingFk
+ LEFT JOIN vn.parking p ON p.id = sh.parkingFk
+ LEFT JOIN vn.sector s ON s.id = p.sectorFk
+ WHERE sh.code = ? AND (? IS NULL OR is2.itemFk = ?)
+ ),
+ itemShelvings AS (
+ SELECT is2.itemFk, is2.created, sh.code, p.pickingOrder, p.code AS parkingFk
+ FROM vn.itemShelving is2
+ JOIN currentItemShelving ai ON is2.itemFk = ai.itemFk
+ JOIN vn.shelving sh ON sh.id = is2.shelvingFk AND ai.code <> sh.code
+ JOIN vn.parking p ON p.id = sh.parkingFk
+ JOIN vn.sector s ON s.id = p.sectorFk
+ ),
+ parkingDestiny AS (
+ SELECT ? AS pickingOrder
+ )
+ SELECT ish.*,
+ CASE
+ WHEN ish.pickingOrder < d.pickingOrder AND aish.created < ish.created
+ AND ABS(TIMESTAMPDIFF(HOUR, aish.created, ish.created)) > ? THEN "old"
+ WHEN ish.pickingOrder > d.pickingOrder AND aish.created > ish.created
+ AND ABS(TIMESTAMPDIFF(HOUR, aish.created, ish.created)) > ? THEN "new"
+ END AS itemCreated
+ FROM itemShelvings ish
+ JOIN parkingDestiny d ON d.pickingOrder IS NOT NULL
+ JOIN currentItemShelving aish ON ish.itemFk = aish.itemFk
+ WHERE ABS(TIMESTAMPDIFF(HOUR, aish.created, ish.created)) > ?
+ AND (
+ (ish.pickingOrder < d.pickingOrder AND aish.created < ish.created)
+ OR
+ (ish.pickingOrder > d.pickingOrder AND aish.created > ish.created)
+ );
+ `,
+ [shelving, itemFk, itemFk, pickingOrderToCompare,
+ hoursToCompare, hoursToCompare, hoursToCompare, hoursToCompare], myOptions);
+ return result;
+ };
+};
diff --git a/modules/item/back/methods/item-shelving/getListItemNewer.js b/modules/item/back/methods/item-shelving/getListItemNewer.js
index 74c73532a..c806c0a7e 100644
--- a/modules/item/back/methods/item-shelving/getListItemNewer.js
+++ b/modules/item/back/methods/item-shelving/getListItemNewer.js
@@ -45,21 +45,21 @@ module.exports = Self => {
WITH tItemShelving AS(
SELECT is2.itemFk, is2.created, p.sectorFK, is2.id
FROM vn.itemShelving is2
- JOIN vn.shelving sh ON sh.code = is2.shelvingFk
+ JOIN vn.shelving sh ON sh.id = is2.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
JOIN vn.sector s ON s.id = p.sectorFk
JOIN vn.productionConfig pc
- WHERE is2.shelvingFk = ? AND s.code = pc.sectorFromCode
+ WHERE sh.code = ? AND s.code = pc.sectorFromCode
), tItemInSector AS (
- SELECT is2.itemFk, is2.created, is2.shelvingFk
+ SELECT is2.itemFk, is2.created, sh.code
FROM vn.itemShelving is2
- JOIN vn.shelving sh ON sh.code = is2.shelvingFk
+ JOIN vn.shelving sh ON sh.id = is2.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
JOIN vn.sector s ON s.id = p.sectorFk
JOIN vn.productionConfig pc
- WHERE is2.shelvingFk <> ?
+ WHERE sh.code <> ?
AND s.code = pc.sectorFromCode)
- SELECT ti.itemFK, tis.shelvingFk
+ SELECT ti.itemFK, tis.code shelvingFk
FROM tItemShelving ti
JOIN tItemInSector tis ON tis.itemFk = ti.itemFk
JOIN vn.productionConfig pc
diff --git a/modules/item/back/methods/item-shelving/specs/deleteItemShelvings.spec.js b/modules/item/back/methods/item-shelving/specs/deleteItemShelvings.spec.js
index b4113d7cf..541a529cb 100644
--- a/modules/item/back/methods/item-shelving/specs/deleteItemShelvings.spec.js
+++ b/modules/item/back/methods/item-shelving/specs/deleteItemShelvings.spec.js
@@ -10,7 +10,7 @@ describe('ItemShelving deleteItemShelvings()', () => {
const itemShelvingIds = [1, 2];
const result = await models.ItemShelving.deleteItemShelvings(itemShelvingIds, options);
- expect(result.length).toEqual(2);
+ expect(result.length).toEqual(4);
await tx.rollback();
} catch (e) {
diff --git a/modules/item/back/methods/item-shelving/specs/getItemsByReviewOrder.spec.js b/modules/item/back/methods/item-shelving/specs/getItemsByReviewOrder.spec.js
new file mode 100644
index 000000000..8f368b57c
--- /dev/null
+++ b/modules/item/back/methods/item-shelving/specs/getItemsByReviewOrder.spec.js
@@ -0,0 +1,123 @@
+
+const {models} = require('vn-loopback/server/server');
+
+describe('itemShelving getItemsByReviewOrder()', () => {
+ it('should return empty because hoursToReview = 0', async() => {
+ const shelving = 'NBB';
+ const parking = '700-01';
+
+ const tx = await models.Sector.beginTransaction({});
+ const myOptions = {transaction: tx};
+
+ try {
+ const config = await models.ProductionConfig.findOne();
+ await config.updateAttributes({
+ itemOrderReviewHours: null,
+ });
+
+ const result = await models.ItemShelving.getItemsByReviewOrder(shelving, parking, myOptions);
+
+ expect(result.length).toEqual(0);
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
+
+ it('should return an item because you are trying parking a shelving and there is an older item', async() => {
+ const shelving = 'NBB';
+ const parking = 'K-26-2';
+ const itemFk = 1000000;
+
+ const tx = await models.Sector.beginTransaction({});
+ const myOptions = {transaction: tx};
+
+ try {
+ const config = await models.ProductionConfig.findOne();
+ await config.updateAttributes({
+ itemOrderReviewHours: 24,
+ });
+
+ const result = await models.ItemShelving.getItemsByReviewOrder(shelving, parking, itemFk, myOptions);
+
+ expect(result.length).toEqual(1);
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
+
+ it('should return an item because you are trying parking a shelving and there is an newer item', async() => {
+ const shelving = 'NBB';
+ const parking = 'K-26-2';
+ const itemFk = 1000000;
+
+ const tx = await models.Sector.beginTransaction({});
+ const myOptions = {transaction: tx};
+
+ try {
+ const config = await models.ProductionConfig.findOne();
+ await config.updateAttributes({
+ itemOrderReviewHours: 24,
+ });
+
+ const result = await models.ItemShelving.getItemsByReviewOrder(shelving, parking, itemFk, myOptions);
+
+ expect(result.length).toEqual(1);
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
+
+ it('should return a item list because you are trying parking a shelving and there is an newer item', async() => {
+ const shelving = 'NCC';
+ const parking = 'K-26-2';
+ const itemFk = 1000000;
+
+ const tx = await models.Sector.beginTransaction({});
+ const myOptions = {transaction: tx};
+
+ try {
+ const config = await models.ProductionConfig.findOne();
+ await config.updateAttributes({
+ itemOrderReviewHours: 24,
+ });
+
+ const result = await models.ItemShelving.getItemsByReviewOrder(shelving, parking, itemFk, myOptions);
+
+ expect(result.length).toEqual(2);
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
+
+ it('should return empty list because all order is correct', async() => {
+ const shelving = 'NCC';
+ const parking = 'A-01-1';
+ const itemFk = 1000000;
+
+ const tx = await models.Sector.beginTransaction({});
+ const myOptions = {transaction: tx};
+
+ try {
+ const config = await models.ProductionConfig.findOne();
+ await config.updateAttributes({
+ itemOrderReviewHours: 24,
+ });
+
+ const result = await models.ItemShelving.getItemsByReviewOrder(shelving, parking, itemFk, myOptions);
+
+ expect(result.length).toEqual(0);
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
+});
diff --git a/modules/item/back/methods/item-shelving/specs/updateFromSale.spec.js b/modules/item/back/methods/item-shelving/specs/updateFromSale.spec.js
index dfa294000..2cdb5994b 100644
--- a/modules/item/back/methods/item-shelving/specs/updateFromSale.spec.js
+++ b/modules/item/back/methods/item-shelving/specs/updateFromSale.spec.js
@@ -5,7 +5,7 @@ describe('itemShelving updateFromSale()', () => {
const tx = await models.ItemBarcode.beginTransaction({});
const options = {transaction: tx};
const saleFk = 2;
- const filter = {where: {itemFk: 4, shelvingFk: 'HEJ'}
+ const filter = {where: {itemFk: 4, shelvingFk: 12}
};
try {
const {visible: visibleBefore} = await models.ItemShelving.findOne(filter, options);
diff --git a/modules/item/back/methods/item-shelving/specs/upsertItem.spec.js b/modules/item/back/methods/item-shelving/specs/upsertItem.spec.js
index f01cb985d..edc850211 100644
--- a/modules/item/back/methods/item-shelving/specs/upsertItem.spec.js
+++ b/modules/item/back/methods/item-shelving/specs/upsertItem.spec.js
@@ -18,22 +18,31 @@ describe('ItemShelving upsertItem()', () => {
});
it('should add two new records', async() => {
- const shelvingFk = 'GVC';
+ const shelvingCode = 'GVC';
const items = [1, 1, 1, 2];
-
- await models.ItemShelving.upsertItem(ctx, shelvingFk, items, warehouseFk, options);
+ const {id: shelvingFk} = await models.Shelving.findOne({
+ where: {
+ code: shelvingCode
+ }
+ });
+ await models.ItemShelving.upsertItem(ctx, shelvingCode, items, warehouseFk, options);
const itemShelvings = await models.ItemShelving.find({where: {shelvingFk}}, options);
expect(itemShelvings.length).toEqual(2);
});
it('should update the visible items', async() => {
- const shelvingFk = 'GVC';
+ const shelvingCode = 'GVC';
const items = [2, 2];
+ const {id: shelvingFk} = await models.Shelving.findOne({
+ where: {
+ code: shelvingCode
+ }
+ });
const {visible: visibleItemsBefore} = await models.ItemShelving.findOne({
where: {shelvingFk, itemFk: items[0]}
}, options);
- await models.ItemShelving.upsertItem(ctx, shelvingFk, items, warehouseFk, options);
+ await models.ItemShelving.upsertItem(ctx, shelvingCode, items, warehouseFk, options);
const {visible: visibleItemsAfter} = await models.ItemShelving.findOne({
where: {shelvingFk, itemFk: items[0]}
diff --git a/modules/item/back/methods/item/filter.js b/modules/item/back/methods/item/filter.js
index 909b3dff8..a7fde1e6c 100644
--- a/modules/item/back/methods/item/filter.js
+++ b/modules/item/back/methods/item/filter.js
@@ -38,13 +38,23 @@ module.exports = Self => {
type: 'integer',
description: 'Type id',
},
+ {
+ arg: 'producerFk',
+ type: 'integer',
+ description: 'Producer id',
+ },
+ {
+ arg: 'instrastatFk',
+ type: 'string',
+ description: 'intrastat id',
+ },
{
arg: 'isActive',
type: 'boolean',
description: 'Whether the item is or not active',
},
{
- arg: 'buyerFk',
+ arg: 'workerFk',
type: 'integer',
description: 'The buyer of the item',
},
@@ -126,14 +136,16 @@ module.exports = Self => {
return {'i.stemMultiplier': value};
case 'categoryFk':
return {'ic.id': value};
- case 'buyerFk':
+ case 'workerFk':
return {'it.workerFk': value};
+ case 'producerFk':
+ return {'pr.id': value};
case 'supplierFk':
return {'s.id': value};
case 'origin':
return {'ori.code': value};
- case 'intrastat':
- return {'intr.description': value};
+ case 'intrastatFk':
+ return {'i.intrastatFk': value};
case 'landed':
return {'lb.landed': value};
}
@@ -166,16 +178,18 @@ module.exports = Self => {
i.isFloramondo,
i.recycledPlastic,
i.nonRecycledPlastic,
- pr.name AS producer,
- it.name AS typeName,
- it.workerFk AS buyerFk,
- u.name AS userName,
- ori.code AS origin,
- ic.name AS category,
- intr.description AS intrastat,
+ pr.name producer,
+ it.name typeName,
+ it.workerFk buyerFk,
+ u.name userName,
+ ori.code origin,
+ ic.name category,
+ i.intrastatFk,
+ intr.description intrastat,
b.grouping,
b.packing,
- lb.landing AS landed
+ lb.landing landed,
+ it.name typeName
FROM item i
LEFT JOIN itemType it ON it.id = i.typeFk
LEFT JOIN itemCategory ic ON ic.id = it.categoryFk
diff --git a/modules/item/back/methods/item/labelPdf.js b/modules/item/back/methods/item/labelPdf.js
deleted file mode 100644
index d7a50397e..000000000
--- a/modules/item/back/methods/item/labelPdf.js
+++ /dev/null
@@ -1,59 +0,0 @@
-module.exports = Self => {
- Self.remoteMethodCtx('labelPdf', {
- description: 'Returns the item label pdf',
- accessType: 'READ',
- accepts: [
- {
- arg: 'id',
- type: 'number',
- required: true,
- description: 'The item id',
- http: {source: 'path'}
- },
- {
- arg: 'recipientId',
- type: 'number',
- description: 'The recipient id',
- required: false
- },
- {
- arg: 'warehouseId',
- type: 'number',
- description: 'The warehouse id',
- required: true
- },
- {
- arg: 'labelNumber',
- type: 'number',
- required: false
- },
- {
- arg: 'totalLabels',
- type: 'number',
- required: false
- }
- ],
- 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/label-pdf',
- verb: 'GET'
- },
- accessScopes: ['DEFAULT', 'read:multimedia']
- });
-
- Self.labelPdf = (ctx, id) => Self.printReport(ctx, id, 'item-label');
-};
diff --git a/modules/item/back/methods/item/lastEntriesFilter.js b/modules/item/back/methods/item/lastEntriesFilter.js
index 5aafbb4f6..06c60162f 100644
--- a/modules/item/back/methods/item/lastEntriesFilter.js
+++ b/modules/item/back/methods/item/lastEntriesFilter.js
@@ -54,7 +54,8 @@ module.exports = Self => {
b.packageValue,
b.packagingFk ,
s.id AS supplierFk,
- s.name AS supplier
+ s.name AS supplier,
+ b.printedStickers
FROM itemType it
RIGHT JOIN (entry e
LEFT JOIN supplier s ON s.id = e.supplierFk
diff --git a/modules/item/back/methods/item/specs/filter.spec.js b/modules/item/back/methods/item/specs/filter.spec.js
index 14467d1d8..a8aaca786 100644
--- a/modules/item/back/methods/item/specs/filter.spec.js
+++ b/modules/item/back/methods/item/specs/filter.spec.js
@@ -86,7 +86,7 @@ describe('item filter()', () => {
try {
const filter = {};
- const ctx = {args: {filter: filter, buyerFk: 16}, req: {accessToken: {userId: 1}}};
+ const ctx = {args: {filter: filter, workerFk: 16}, req: {accessToken: {userId: 1}}};
const result = await models.Item.filter(ctx, filter, options);
expect(result.length).toEqual(2);
diff --git a/modules/item/back/methods/item/specs/lastEntriesFilter.spec.js b/modules/item/back/methods/item/specs/lastEntriesFilter.spec.js
index 2fd30c2ca..d4429e158 100644
--- a/modules/item/back/methods/item/specs/lastEntriesFilter.spec.js
+++ b/modules/item/back/methods/item/specs/lastEntriesFilter.spec.js
@@ -34,10 +34,31 @@ describe('item lastEntriesFilter()', () => {
const options = {transaction: tx};
try {
- const filter = {where: {itemFk: 1, landed: {between: [minDate, maxDate]}}};
+ const itemFk = 1;
+ const filter = {where: {itemFk, landed: {between: [minDate, maxDate]}}};
const result = await models.Item.lastEntriesFilter(filter, options);
+ const minDateUtc = new Date(minDate).getTime();
+ const maxDateUtc = new Date(maxDate).getTime();
- expect(result.length).toEqual(6);
+ const resultMatch = (
+ await Promise.all(
+ result.map(async item => {
+ const itemRecord = await models.Buy.findOne({
+ fields: ['id'],
+ where: {id: item.id},
+ options,
+ });
+
+ const isItemFkValid = itemRecord?.id === itemFk;
+ const landedDate = new Date(item.landed).getTime();
+ const isLandedValid = landedDate >= minDateUtc && landedDate <= maxDateUtc;
+
+ return isItemFkValid && isLandedValid;
+ })
+ )
+ ).filter(Boolean).length;
+
+ expect(result.length).toEqual(resultMatch);
await tx.rollback();
} catch (e) {
diff --git a/modules/item/back/model-config.json b/modules/item/back/model-config.json
index 5dbe4d62a..c386a8eaa 100644
--- a/modules/item/back/model-config.json
+++ b/modules/item/back/model-config.json
@@ -47,15 +47,15 @@
"ItemType": {
"dataSource": "vn"
},
+ "ItemTypeLog": {
+ "dataSource": "vn"
+ },
"ItemTypeTag": {
"dataSource": "vn"
},
"ItemShelving": {
"dataSource": "vn"
},
- "ItemShelvingLog": {
- "dataSource": "vn"
- },
"ItemShelvingSale": {
"dataSource": "vn"
},
diff --git a/modules/item/back/models/item-shelving-log.json b/modules/item/back/models/item-shelving-log.json
deleted file mode 100644
index f976008f1..000000000
--- a/modules/item/back/models/item-shelving-log.json
+++ /dev/null
@@ -1,52 +0,0 @@
-{
- "name": "ItemShelvingLog",
- "base": "VnModel",
- "mixins": {
- "Loggable": true
- },
- "options": {
- "mysql": {
- "table": "itemShelvingLog"
- }
- },
- "properties": {
- "id": {
- "type": "number",
- "id": true,
- "description": "Identifier"
- },
- "created": {
- "type": "date"
- },
- "shelvingFk": {
- "type": "string"
- },
- "itemFk": {
- "type": "number"
- },
- "visible": {
- "type": "number"
- },
- "accion": {
- "type": "string"
- }
- },
- "relations": {
- "item": {
- "type": "belongsTo",
- "model": "Item",
- "foreignKey": "itemFk"
- },
- "worker": {
- "type": "belongsTo",
- "model": "Worker",
- "foreignKey": "workerFk"
- },
- "shelving": {
- "type": "belongsTo",
- "model": "Shelving",
- "foreignKey": "shelvingFk",
- "primaryKey": "code"
- }
- }
-}
\ No newline at end of file
diff --git a/modules/item/back/models/item-shelving.js b/modules/item/back/models/item-shelving.js
index be72dac37..34e18f23f 100644
--- a/modules/item/back/models/item-shelving.js
+++ b/modules/item/back/models/item-shelving.js
@@ -5,4 +5,5 @@ module.exports = Self => {
require('../methods/item-shelving/getAlternative')(Self);
require('../methods/item-shelving/updateFromSale')(Self);
require('../methods/item-shelving/getListItemNewer')(Self);
+ require('../methods/item-shelving/getItemsByReviewOrder')(Self);
};
diff --git a/modules/item/back/models/item-shelving.json b/modules/item/back/models/item-shelving.json
index 5df3b0703..483d6bf3d 100644
--- a/modules/item/back/models/item-shelving.json
+++ b/modules/item/back/models/item-shelving.json
@@ -41,6 +41,9 @@
},
"available": {
"type": "number"
+ },
+ "buyFk": {
+ "type": "number"
}
},
"relations": {
@@ -57,8 +60,7 @@
"shelving": {
"type": "belongsTo",
"model": "Shelving",
- "foreignKey": "shelvingFk",
- "primaryKey": "code"
+ "foreignKey": "shelvingFk"
}
}
}
\ No newline at end of file
diff --git a/modules/item/back/models/item-type-log.json b/modules/item/back/models/item-type-log.json
new file mode 100644
index 000000000..82a218aa6
--- /dev/null
+++ b/modules/item/back/models/item-type-log.json
@@ -0,0 +1,9 @@
+{
+ "name": "ItemTypeLog",
+ "base": "Log",
+ "options": {
+ "mysql": {
+ "table": "itemTypeLog"
+ }
+ }
+}
diff --git a/modules/item/back/models/item-type.js b/modules/item/back/models/item-type.js
new file mode 100644
index 000000000..4dc8adfc9
--- /dev/null
+++ b/modules/item/back/models/item-type.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(`An item type with the same code already exists`);
+ return err;
+ });
+};
diff --git a/modules/item/back/models/item-type.json b/modules/item/back/models/item-type.json
index c5c920b2f..88f66899e 100644
--- a/modules/item/back/models/item-type.json
+++ b/modules/item/back/models/item-type.json
@@ -29,6 +29,12 @@
},
"isLaid": {
"type": "boolean"
+ },
+ "maxRefs": {
+ "type": "string"
+ },
+ "isFragile": {
+ "type": "boolean"
}
},
"relations": {
diff --git a/modules/item/back/models/item.js b/modules/item/back/models/item.js
index e715ab431..44a51594c 100644
--- a/modules/item/back/models/item.js
+++ b/modules/item/back/models/item.js
@@ -15,7 +15,6 @@ module.exports = Self => {
require('../methods/item/getWasteByItem')(Self);
require('../methods/item/createIntrastat')(Self);
require('../methods/item/buyerWasteEmail')(Self);
- require('../methods/item/labelPdf')(Self);
require('../methods/item/setVisibleDiscard')(Self);
require('../methods/item/get')(Self);
diff --git a/modules/item/back/models/item.json b/modules/item/back/models/item.json
index eda56e938..159883455 100644
--- a/modules/item/back/models/item.json
+++ b/modules/item/back/models/item.json
@@ -154,6 +154,9 @@
},
"photoMotivation": {
"type": "string"
+ },
+ "isCustomInspectionRequired": {
+ "type": "boolean"
}
},
"relations": {
@@ -222,4 +225,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/modules/item/front/item-type/basic-data/index.html b/modules/item/front/item-type/basic-data/index.html
index 1417a05ab..c3f7a57f1 100644
--- a/modules/item/front/item-type/basic-data/index.html
+++ b/modules/item/front/item-type/basic-data/index.html
@@ -11,26 +11,26 @@
-
\ No newline at end of file
+
diff --git a/modules/item/front/item-type/create/index.html b/modules/item/front/item-type/create/index.html
index 44cb5183d..4a199a1b1 100644
--- a/modules/item/front/item-type/create/index.html
+++ b/modules/item/front/item-type/create/index.html
@@ -12,26 +12,26 @@
{
arg: 'alertLevel',
type: 'number',
description: `The alert level of the tickets`
+ },
+ {
+ arg: 'packing',
+ type: 'string',
+ description: `The packing of the items`
+ },
+ {
+ arg: 'countryFk',
+ type: 'number',
+ description: 'The country id filter'
+ },
+ {
+ arg: 'payMethod',
+ type: 'string',
+ description: 'The payment method filter'
}
],
returns: {
@@ -155,6 +170,8 @@ module.exports = Self => {
case 'clientFk':
param = `t.${param}`;
return {[param]: value};
+ case 'payMethod':
+ return {'c.payMethodFk': value};
}
});
@@ -169,7 +186,7 @@ module.exports = Self => {
stmt = new ParameterizedSQL(`
CREATE OR REPLACE TEMPORARY TABLE tmp.filter
(PRIMARY KEY (id))
- ENGINE = MEMORY
+ ENGINE = InnoDB
SELECT t.id,
t.shipped,
CAST(DATE(t.shipped) AS CHAR) shippedDate,
@@ -182,6 +199,7 @@ module.exports = Self => {
t.totalWithVat,
io.id invoiceOutId,
a.provinceFk,
+ p.countryFk,
p.name province,
w.name warehouse,
am.name agencyMode,
@@ -194,10 +212,20 @@ module.exports = Self => {
u.name userName,
c.salesPersonFk,
c.credit,
+ c.payMethodFk payMethodFk,
+ pm.id payMethodId,
+ pm.name payMethod,
z.hour zoneLanding,
z.name zoneName,
z.id zoneFk,
st.classColor,
+ d.id departmentFk,
+ d.name department,
+ (SELECT GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk SEPARATOR ',')
+ FROM sale s
+ JOIN item i ON i.id = s.itemFk
+ WHERE s.ticketFk = t.id
+ ) AS packing,
TIME_FORMAT(t.shipped, '%H:%i') preparationHour,
TIME_FORMAT(z.hour, '%H:%i') theoreticalhour,
TIME_FORMAT(zed.etc, '%H:%i') practicalHour
@@ -211,7 +239,10 @@ module.exports = Self => {
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 payMethod pm ON pm.id = c.payMethodFk
LEFT JOIN worker wk ON wk.id = c.salesPersonFk
+ LEFT JOIN workerDepartment wd ON wd.workerFk = wk.id
+ LEFT JOIN department d ON d.id = wd.departmentFk
LEFT JOIN account.user u ON u.id = wk.id
LEFT JOIN (
SELECT zoneFk,
@@ -342,7 +373,6 @@ module.exports = Self => {
'CHECKED',
'PACKING',
'PACKED',
- 'INVOICED',
'ON_DELIVERY',
'PREPARED',
'WAITING_FOR_PICKUP',
@@ -350,16 +380,15 @@ module.exports = Self => {
'PRINTED_BACK',
'LAST_CALL',
'PREVIOUS_PREPARATION',
- 'ASSISTED_PREPARATION',
- 'BOARD',
'PRINTED STOWAWAY',
- 'OK STOWAWAY',
'HALF_PACKED',
'COOLER_PREPARATION'
]}};
}
case 'agencyModeFk':
case 'warehouseFk':
+ case 'packing':
+ case 'countryFk':
param = `f.${param}`;
return {[param]: value};
}
diff --git a/modules/monitor/front/index.js b/modules/monitor/front/index.js
index 19ea06b5a..a7209a0bd 100644
--- a/modules/monitor/front/index.js
+++ b/modules/monitor/front/index.js
@@ -1,8 +1,3 @@
export * from './module';
import './main';
-import './index/';
-import './index/tickets';
-import './index/clients';
-import './index/orders';
-import './index/search-panel';
diff --git a/modules/monitor/front/index/clients/index.html b/modules/monitor/front/index/clients/index.html
deleted file mode 100644
index c0e3d1b14..000000000
--- a/modules/monitor/front/index/clients/index.html
+++ /dev/null
@@ -1,110 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Date
-
-
- Hour
-
-
- Salesperson
-
-
- Client
-
-
-
-
-
-
-
- {{::visit.dated | date:'dd/MM/yy'}}
-
-
-
-
- {{::visit.hour | date: 'HH:mm'}}
-
-
-
-
- {{::visit.salesPerson | dashIfEmpty}}
-
-
-
-
- {{::visit.clientName}}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/modules/monitor/front/index/clients/index.js b/modules/monitor/front/index/clients/index.js
deleted file mode 100644
index ac3ce9140..000000000
--- a/modules/monitor/front/index/clients/index.js
+++ /dev/null
@@ -1,96 +0,0 @@
-import ngModule from '../../module';
-import Section from 'salix/components/section';
-
-export default class Controller extends Section {
- constructor($element, $) {
- super($element, $);
-
- const date = Date.vnNew();
- this.dateFrom = date;
- this.dateTo = date;
- this.filter = {
- where: {
- 'v.stamp': {
- between: this.dateRange()
- }
- }
- };
-
- this.smartTableOptions = {
- activeButtons: {
- search: true
- },
- columns: [
- {
- field: 'clientFk',
- autocomplete: {
- url: 'Clients',
- showField: 'name',
- valueField: 'id'
- }
- },
- {
- field: 'salesPersonFk',
- autocomplete: {
- url: 'Workers/activeWithInheritedRole',
- where: `{role: 'salesPerson'}`,
- searchFunction: '{firstName: $search}',
- showField: 'nickname',
- valueField: 'id',
- }
- },
- {
- field: 'dated',
- searchable: false
- },
- {
- field: 'hour',
- searchable: false
- }
- ]
- };
- }
-
- exprBuilder(param, value) {
- switch (param) {
- case 'clientFk':
- return {[`c.id`]: value};
- case 'salesPersonFk':
- return {[`c.${param}`]: value};
- }
- }
-
- dateRange() {
- let from = this.dateFrom;
- let to = this.dateTo;
- if (!from)
- from = Date.vnNew();
- if (!to)
- to = Date.vnNew();
- const minHour = new Date(from);
- minHour.setHours(0, 0, 0, 0);
- const maxHour = new Date(to);
- maxHour.setHours(23, 59, 59, 59);
-
- return [minHour, maxHour];
- }
-
- addFilterDate() {
- this.$.model.filter = {
- where: {
- 'v.stamp': {
- between: this.dateRange()
- }
- }
- };
- this.$.model.refresh();
- }
-}
-
-ngModule.vnComponent('vnMonitorSalesClients', {
- template: require('./index.html'),
- controller: Controller,
- require: {
- main: '^vnMonitorIndex'
- }
-});
diff --git a/modules/monitor/front/index/index.html b/modules/monitor/front/index/index.html
deleted file mode 100644
index 85987ac20..000000000
--- a/modules/monitor/front/index/index.html
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
\ No newline at end of file
diff --git a/modules/monitor/front/index/index.js b/modules/monitor/front/index/index.js
deleted file mode 100644
index 72ca9dae9..000000000
--- a/modules/monitor/front/index/index.js
+++ /dev/null
@@ -1,34 +0,0 @@
-import ngModule from '../module';
-import Section from 'salix/components/section';
-import './style.scss';
-
-export default class Controller extends Section {
- constructor($element, $) {
- super($element, $);
-
- const isTopPanelHidden = localStorage.getItem('ticketTopPanelHidden');
- if (isTopPanelHidden === 'true')
- this.isTopPanelHidden = true;
- }
-
- toggle() {
- const monitor = this.element.querySelector('vn-horizontal');
- const isHidden = monitor.classList.contains('hidden');
-
- if (!isHidden) {
- monitor.classList.add('hidden');
- localStorage.setItem('ticketTopPanelHidden', true);
- } else {
- monitor.classList.remove('hidden');
- localStorage.setItem('ticketTopPanelHidden', false);
- }
- }
-}
-
-ngModule.vnComponent('vnMonitorIndex', {
- template: require('./index.html'),
- controller: Controller,
- require: {
- main: '^vnMonitorIndex'
- }
-});
diff --git a/modules/monitor/front/index/index.spec.js b/modules/monitor/front/index/index.spec.js
deleted file mode 100644
index 506e75720..000000000
--- a/modules/monitor/front/index/index.spec.js
+++ /dev/null
@@ -1,38 +0,0 @@
-import './index.js';
-describe('Component vnMonitorIndex', () => {
- let controller;
- let $element;
-
- beforeEach(ngModule('monitor'));
-
- beforeEach(inject(($compile, $rootScope) => {
- $element = $compile(' ')($rootScope);
- controller = $element.controller('vnMonitorIndex');
- }));
-
- describe('toggle()', () => {
- it('should add the hidden class to the horizontal contaning the panel to hide', () => {
- controller.toggle();
-
- const targetElement = $element[0].querySelector('vn-horizontal');
- const firstClass = targetElement.classList[0];
-
- const isTopPanelHidden = localStorage.getItem('ticketTopPanelHidden');
-
- expect(firstClass).toEqual('hidden');
- expect(isTopPanelHidden).toEqual('true');
- });
-
- it('should remove the hidden class to the horizontal contaning the panel to hide', () => {
- const targetElement = $element[0].querySelector('vn-horizontal');
- targetElement.classList.add('hidden');
- controller.toggle();
- const firstClass = targetElement.classList[0];
-
- const isTopPanelHidden = localStorage.getItem('ticketTopPanelHidden');
-
- expect(firstClass).toBeUndefined();
- expect(isTopPanelHidden).toEqual('false');
- });
- });
-});
diff --git a/modules/monitor/front/index/locale/es.yml b/modules/monitor/front/index/locale/es.yml
deleted file mode 100644
index f114a2259..000000000
--- a/modules/monitor/front/index/locale/es.yml
+++ /dev/null
@@ -1,16 +0,0 @@
-Tickets monitor: Monitor de tickets
-Clients on website: Clientes activos en la web
-Recent order actions: Acciones recientes en pedidos
-Search tickets: Buscar tickets
-Delete selected elements: Eliminar los elementos seleccionados
-All the selected elements will be deleted. Are you sure you want to continue?: Todos los elementos seleccionados serán eliminados. ¿Seguro que quieres continuar?
-Component lack: Faltan componentes
-Ticket too little: Ticket demasiado pequeño
-Minimize/Maximize: Minimizar/Maximizar
-Problems: Problemas
-Theoretical: Teórica
-Practical: Práctica
-Preparation: Preparación
-Auto-refresh: Auto-refresco
-Toggle auto-refresh every 2 minutes: Conmuta el refresco automático cada 2 minutos
-Is fragile: Es frágil
diff --git a/modules/monitor/front/index/orders/index.html b/modules/monitor/front/index/orders/index.html
deleted file mode 100644
index 4d1171185..000000000
--- a/modules/monitor/front/index/orders/index.html
+++ /dev/null
@@ -1,141 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
- Date
- Client
- SalesPerson
-
-
-
-
-
-
-
-
-
-
- {{::order.date_send | date: 'dd/MM/yyyy'}}
-
-
-
-
- {{::order.clientName}}
-
-
-
-
- {{::order.salesPerson | dashIfEmpty}}
-
-
-
-
-
-
-
- {{::order.date_make | date: 'dd/MM/yyyy HH:mm'}}
-
-
-
-
- {{::order.agencyName | dashIfEmpty}}
-
-
-
- {{::order.import | currency: 'EUR':2}}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Filter by selection
-
-
- Exclude selection
-
-
- Remove filter
-
-
- Remove all filters
-
-
- Copy value
-
-
-
-
-
diff --git a/modules/monitor/front/index/orders/index.js b/modules/monitor/front/index/orders/index.js
deleted file mode 100644
index 40100b79f..000000000
--- a/modules/monitor/front/index/orders/index.js
+++ /dev/null
@@ -1,74 +0,0 @@
-import ngModule from '../../module';
-import Section from 'salix/components/section';
-import './style.scss';
-
-export default class Controller extends Section {
- get checked() {
- const rows = this.$.model.data || [];
- const checkedRows = [];
- for (let row of rows) {
- if (row.checked)
- checkedRows.push(row.id);
- }
-
- return checkedRows;
- }
-
- get totalChecked() {
- return this.checked.length;
- }
-
- onDelete() {
- const params = {deletes: this.checked};
- const query = `SalesMonitors/deleteOrders`;
- this.$http.post(query, params).then(
- () => this.$.model.refresh());
- }
-
- chipColor(date) {
- const today = Date.vnNew();
- today.setHours(0, 0, 0, 0);
-
- const orderLanded = new Date(date);
- orderLanded.setHours(0, 0, 0, 0);
-
- const difference = today - orderLanded;
-
- if (difference == 0)
- return 'warning';
- if (difference < 0)
- return 'success';
- if (difference > 0)
- return 'alert';
- }
-
- exprBuilder(param, value) {
- switch (param) {
- case 'date_send':
- return {[`o.date_send`]: {
- between: this.dateRange(value)}
- };
- case 'clientFk':
- return {[`c.id`]: value};
- case 'salesPersonFk':
- return {[`c.${param}`]: value};
- }
- }
-
- dateRange(value) {
- const minHour = new Date(value);
- minHour.setHours(0, 0, 0, 0);
- const maxHour = new Date(value);
- maxHour.setHours(23, 59, 59, 59);
-
- return [minHour, maxHour];
- }
-}
-
-ngModule.vnComponent('vnMonitorSalesOrders', {
- template: require('./index.html'),
- controller: Controller,
- require: {
- main: '^vnMonitorIndex'
- }
-});
diff --git a/modules/monitor/front/index/orders/index.spec.js b/modules/monitor/front/index/orders/index.spec.js
deleted file mode 100644
index 109925358..000000000
--- a/modules/monitor/front/index/orders/index.spec.js
+++ /dev/null
@@ -1,50 +0,0 @@
-import './index.js';
-import crudModel from 'core/mocks/crud-model';
-
-describe('Component vnMonitorSalesOrders', () => {
- let controller;
- let $httpBackend;
-
- beforeEach(ngModule('monitor'));
-
- beforeEach(inject(($componentController, _$httpBackend_) => {
- $httpBackend = _$httpBackend_;
- const $element = angular.element(' ');
- controller = $componentController('vnMonitorSalesOrders', {$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() getter', () => {
- it('should return a the selected rows', () => {
- const modelData = controller.$.model.data;
- modelData[0].checked = true;
- modelData[1].checked = true;
-
- const result = controller.checked;
-
- expect(result).toEqual(expect.arrayContaining([1, 2]));
- });
- });
-
- describe('onDelete()', () => {
- it('should make a query and then call to the model refresh() method', () => {
- jest.spyOn(controller.$.model, 'refresh');
-
- const modelData = controller.$.model.data;
- modelData[0].checked = true;
- modelData[1].checked = true;
-
- const expectedParams = {deletes: [1, 2]};
- $httpBackend.expect('POST', 'SalesMonitors/deleteOrders', expectedParams).respond(200);
- controller.onDelete();
- $httpBackend.flush();
-
- expect(controller.$.model.refresh).toHaveBeenCalledWith();
- });
- });
-});
diff --git a/modules/monitor/front/index/orders/style.scss b/modules/monitor/front/index/orders/style.scss
deleted file mode 100644
index 64d6497c9..000000000
--- a/modules/monitor/front/index/orders/style.scss
+++ /dev/null
@@ -1,19 +0,0 @@
-@import "variables";
-
-vn-monitor-sales-orders {
- vn-table.scrollable {
- max-height: 350px;
- overflow-x: hidden
- }
-
- vn-table a.vn-tbody {
- & > vn-tr:nth-child(2) {
- color: gray;
-
- & > vn-td {
- border-bottom: $border;
- font-size: 13px;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/modules/monitor/front/index/search-panel/index.html b/modules/monitor/front/index/search-panel/index.html
deleted file mode 100644
index 25a3510ab..000000000
--- a/modules/monitor/front/index/search-panel/index.html
+++ /dev/null
@@ -1,120 +0,0 @@
-
-
-
-
-
diff --git a/modules/monitor/front/index/search-panel/index.js b/modules/monitor/front/index/search-panel/index.js
deleted file mode 100644
index ef6625e8a..000000000
--- a/modules/monitor/front/index/search-panel/index.js
+++ /dev/null
@@ -1,59 +0,0 @@
-import ngModule from '../../module';
-import SearchPanel from 'core/components/searchbar/search-panel';
-
-class Controller extends SearchPanel {
- constructor($, $element) {
- super($, $element);
- this.filter = this.$.filter;
-
- this.getGroupedStates();
- }
-
- getGroupedStates() {
- let groupedStates = [];
- this.$http.get('AlertLevels').then(res => {
- for (let state of res.data) {
- groupedStates.push({
- id: state.id,
- code: state.code,
- name: this.$t(state.code)
- });
- }
- this.groupedStates = groupedStates;
- });
- }
-
- get from() {
- return this._from;
- }
-
- set from(value) {
- this._from = value;
- this.filter.scopeDays = null;
- }
-
- get to() {
- return this._to;
- }
-
- set to(value) {
- this._to = value;
- this.filter.scopeDays = null;
- }
-
- get scopeDays() {
- return this._scopeDays;
- }
-
- set scopeDays(value) {
- this._scopeDays = value;
-
- this.filter.from = null;
- this.filter.to = null;
- }
-}
-
-ngModule.vnComponent('vnMonitorSalesSearchPanel', {
- template: require('./index.html'),
- controller: Controller
-});
diff --git a/modules/monitor/front/index/search-panel/index.spec.js b/modules/monitor/front/index/search-panel/index.spec.js
deleted file mode 100644
index 18cf1abfc..000000000
--- a/modules/monitor/front/index/search-panel/index.spec.js
+++ /dev/null
@@ -1,71 +0,0 @@
-import './index';
-
-describe('Monitor Component vnMonitorSalesSearchPanel', () => {
- let $httpBackend;
- let controller;
-
- beforeEach(ngModule('monitor'));
-
- beforeEach(inject(($componentController, _$httpBackend_) => {
- $httpBackend = _$httpBackend_;
- controller = $componentController('vnMonitorSalesSearchPanel', {$element: null});
- controller.$t = () => {};
- controller.filter = {};
- }));
-
- describe('getGroupedStates()', () => {
- it('should set an array of groupedStates with the adition of a name translation', () => {
- jest.spyOn(controller, '$t').mockReturnValue('miCodigo');
- const data = [
- {
- id: 9999,
- code: 'myCode'
- }
- ];
- $httpBackend.whenGET('AlertLevels').respond(data);
- controller.getGroupedStates();
- $httpBackend.flush();
-
- expect(controller.groupedStates).toEqual([{
- id: 9999,
- code: 'myCode',
- name: 'miCodigo'
- }]);
- });
- });
-
- describe('from() setter', () => {
- it('should clear the scope days when setting the from property', () => {
- controller.filter.scopeDays = 1;
-
- controller.from = Date.vnNew();
-
- expect(controller.filter.scopeDays).toBeNull();
- expect(controller.from).toBeDefined();
- });
- });
-
- describe('to() setter', () => {
- it('should clear the scope days when setting the to property', () => {
- controller.filter.scopeDays = 1;
-
- controller.to = Date.vnNew();
-
- expect(controller.filter.scopeDays).toBeNull();
- expect(controller.to).toBeDefined();
- });
- });
-
- describe('scopeDays() setter', () => {
- it('should clear the date range when setting the scopeDays property', () => {
- controller.filter.from = Date.vnNew();
- controller.filter.to = Date.vnNew();
-
- controller.scopeDays = 1;
-
- expect(controller.filter.from).toBeNull();
- expect(controller.filter.to).toBeNull();
- expect(controller.scopeDays).toBeDefined();
- });
- });
-});
diff --git a/modules/monitor/front/index/style.scss b/modules/monitor/front/index/style.scss
deleted file mode 100644
index 2b193ac88..000000000
--- a/modules/monitor/front/index/style.scss
+++ /dev/null
@@ -1,85 +0,0 @@
-@import "variables";
-@import "effects";
-
-vn-monitor-index {
- .header {
- padding: 12px 0 5px 0;
- color: gray;
- font-size: 1.2rem;
- border-bottom: $border;
- margin-bottom: 10px;
-
- & > vn-none > vn-icon {
- @extend %clickable-light;
- color: $color-button;
- font-size: 1.4rem;
- }
-
- vn-none > .arrow {
- transition: transform 200ms;
- }
- }
-
- vn-monitor-sales-clients {
- vn-card {
- margin-right: 15px;
- }
-
- .header {
- padding-right: 15px;
-
- & > vn-none > .arrow {
- display: none
- }
- }
- }
-
- vn-table.scrollable {
- height: 300px
- }
-
- vn-horizontal {
- flex-wrap: wrap
- }
-
- .hidden {
- vn-card {
- display: none
- }
-
- .header > vn-none > .arrow {
- transform: rotate(180deg);
- }
- }
-}
-
-@media (max-width:1150px) {
- vn-monitor-index {
- & > vn-horizontal {
- flex-direction: column;
-
- vn-monitor-sales-clients,
- vn-monitor-sales-orders {
- width: 100%
- }
-
- vn-monitor-sales-clients {
- margin-bottom: 15px
- }
- }
-
- vn-monitor-sales-clients {
- vn-card {
- margin-right: 0
- }
-
- .header {
- padding-right: 0;
-
- & > vn-none > .arrow {
- display: inline-block
- }
- }
- }
- }
-}
\ No newline at end of file
diff --git a/modules/monitor/front/index/tickets/index.html b/modules/monitor/front/index/tickets/index.html
deleted file mode 100644
index 94a950baf..000000000
--- a/modules/monitor/front/index/tickets/index.html
+++ /dev/null
@@ -1,270 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Problems
-
-
- Identifier
-
-
- Client
-
-
- Salesperson
-
-
- Date
-
-
- Theoretical
-
-
- Practical
-
-
- Preparation
-
-
- Province
-
-
- State
-
-
- Fragile
-
-
- Zone
-
-
- Total
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {{ticket.id}}
-
-
-
-
- {{ticket.nickname}}
-
-
-
-
- {{ticket.userName | dashIfEmpty}}
-
-
-
-
- {{ticket.shippedDate | date: 'dd/MM/yyyy'}}
-
-
- {{ticket.zoneLanding | date: 'HH:mm'}}
- {{ticket.practicalHour | date: 'HH:mm'}}
- {{ticket.shipped | date: 'HH:mm'}}
- {{ticket.province}}
-
-
- {{ticket.refFk}}
-
-
- {{ticket.state}}
-
-
-
-
-
-
-
-
- {{ticket.zoneName | dashIfEmpty}}
-
-
-
-
- {{(ticket.totalWithVat ? ticket.totalWithVat : 0) | currency: 'EUR': 2}}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Filter by selection
-
-
- Exclude selection
-
-
- Remove filter
-
-
- Remove all filters
-
-
- Copy value
-
-
-
diff --git a/modules/monitor/front/index/tickets/index.js b/modules/monitor/front/index/tickets/index.js
deleted file mode 100644
index 2f2dead05..000000000
--- a/modules/monitor/front/index/tickets/index.js
+++ /dev/null
@@ -1,178 +0,0 @@
-import ngModule from '../../module';
-import Section from 'salix/components/section';
-import './style.scss';
-
-export default class Controller extends Section {
- constructor($element, $) {
- super($element, $);
-
- this.filterParams = this.fetchParams();
- this.smartTableOptions = {
- activeButtons: {
- search: true,
- shownColumns: true,
- },
- columns: [
- {
- field: 'totalProblems',
- searchable: false
- },
- {
- field: 'salesPersonFk',
- autocomplete: {
- url: 'Workers/activeWithInheritedRole',
- where: `{role: 'salesPerson'}`,
- searchFunction: '{firstName: $search}',
- showField: 'nickname',
- valueField: 'id',
- }
- },
- {
- field: 'provinceFk',
- autocomplete: {
- url: 'Provinces',
- }
- },
- {
- field: 'stateFk',
- autocomplete: {
- url: 'States',
- }
- },
- {
- field: 'zoneFk',
- autocomplete: {
- url: 'Zones',
- }
- },
- {
- field: 'warehouseFk',
- autocomplete: {
- url: 'Warehouses',
- }
- },
- {
- field: 'shippedDate',
- datepicker: true
- },
- {
- field: 'theoreticalHour',
- searchable: false
- },
- {
- field: 'preparationHour',
- searchable: false
- }
- ]
- };
- }
-
- $onInit() {
- if (!this.$params.q) {
- this.$.$applyAsync(
- () => this.$.model.applyFilter(null, this.filterParams));
- }
- }
-
- fetchParams($params = {}) {
- const excludedParams = [
- 'search',
- 'clientFk',
- 'orderFk',
- 'refFk',
- 'scopeDays'
- ];
-
- const hasExcludedParams = excludedParams.some(param => {
- return $params && $params[param] != undefined;
- });
- const hasParams = Object.entries($params).length;
- if (!hasParams || !hasExcludedParams)
- $params.scopeDays = 1;
-
- if (typeof $params.scopeDays === 'number') {
- const from = Date.vnNew();
- from.setHours(0, 0, 0, 0);
-
- const to = new Date(from.getTime());
- to.setDate(to.getDate() + $params.scopeDays);
- to.setHours(23, 59, 59, 999);
-
- Object.assign($params, {from, to});
- }
-
- return $params;
- }
-
- compareDate(date) {
- let today = Date.vnNew();
- 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';
- }
-
- totalPriceColor(ticket) {
- const total = parseInt(ticket.totalWithVat);
- if (total > 0 && total < 50)
- return 'warning';
- }
-
- exprBuilder(param, value) {
- switch (param) {
- case 'stateFk':
- return {'ts.stateFk': value};
- case 'salesPersonFk':
- return {'c.salesPersonFk': value};
- case 'provinceFk':
- return {'a.provinceFk': value};
- case 'theoreticalHour':
- return {'z.hour': value};
- case 'practicalHour':
- return {'zed.etc': value};
- case 'shippedDate':
- return {'t.shipped': {
- between: this.dateRange(value)}
- };
- case 'nickname':
- return {[`t.nickname`]: {like: `%${value}%`}};
- case 'zoneFk':
- case 'totalWithVat':
- return {[`t.${param}`]: value};
- }
- }
-
- dateRange(value) {
- const minHour = new Date(value);
- minHour.setHours(0, 0, 0, 0);
- const maxHour = new Date(value);
- maxHour.setHours(23, 59, 59, 59);
-
- return [minHour, maxHour];
- }
-
- preview(ticket) {
- this.selectedTicket = ticket;
- this.$.summary.show();
- }
-
- autoRefresh(value) {
- if (value)
- this.refreshTimer = setInterval(() => this.$.model.refresh(), 120000);
- else {
- clearInterval(this.refreshTimer);
- this.refreshTimer = null;
- }
- }
-}
-
-ngModule.vnComponent('vnMonitorSalesTickets', {
- template: require('./index.html'),
- controller: Controller
-});
diff --git a/modules/monitor/front/index/tickets/index.spec.js b/modules/monitor/front/index/tickets/index.spec.js
deleted file mode 100644
index c12ea6844..000000000
--- a/modules/monitor/front/index/tickets/index.spec.js
+++ /dev/null
@@ -1,133 +0,0 @@
-import './index.js';
-describe('Component vnMonitorSalesTickets', () => {
- let controller;
- let $window;
- let tickets = [{
- id: 1,
- clientFk: 1,
- checked: false,
- totalWithVat: 10.5
- }, {
- id: 2,
- clientFk: 1,
- checked: true,
- totalWithVat: 20.5
- }, {
- id: 3,
- clientFk: 1,
- checked: true,
- totalWithVat: 30
- }];
-
- beforeEach(ngModule('monitor'));
-
- beforeEach(inject(($componentController, _$window_) => {
- $window = _$window_;
- const $element = angular.element(' ');
- controller = $componentController('vnMonitorSalesTickets', {$element});
- }));
-
- describe('fetchParams()', () => {
- it('should return a range of dates with passed scope days', () => {
- let params = controller.fetchParams({
- scopeDays: 2
- });
- const from = Date.vnNew();
- from.setHours(0, 0, 0, 0);
- const to = new Date(from.getTime());
- to.setDate(to.getDate() + params.scopeDays);
- to.setHours(23, 59, 59, 999);
-
- const expectedParams = {
- from,
- scopeDays: params.scopeDays,
- to
- };
-
- expect(params).toEqual(expectedParams);
- });
-
- it('should return default value for scope days', () => {
- let params = controller.fetchParams({
- scopeDays: 1
- });
-
- expect(params.scopeDays).toEqual(1);
- });
-
- it('should return the given scope days', () => {
- let params = controller.fetchParams({
- scopeDays: 2
- });
-
- expect(params.scopeDays).toEqual(2);
- });
- });
-
- describe('compareDate()', () => {
- it('should return warning when the date is the present', () => {
- let today = Date.vnNew();
- let result = controller.compareDate(today);
-
- expect(result).toEqual('warning');
- });
-
- it('should return sucess when the date is in the future', () => {
- let futureDate = Date.vnNew();
- 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 = Date.vnNew();
- pastDate = pastDate.setDate(pastDate.getDate() - 10);
- let result = controller.compareDate(pastDate);
-
- expect(result).toEqual(undefined);
- });
- });
-
- describe('totalPriceColor()', () => {
- it('should return "warning" when the ticket amount is less than 50€', () => {
- const result = controller.totalPriceColor({totalWithVat: '8.50'});
-
- expect(result).toEqual('warning');
- });
- });
-
- describe('dateRange()', () => {
- it('should return two dates with the hours at the start and end of the given date', () => {
- const now = Date.vnNew();
-
- const today = now.getDate();
-
- const dateRange = controller.dateRange(now);
- const start = dateRange[0].toString();
- const end = dateRange[1].toString();
-
- expect(start).toContain(today);
- expect(start).toContain('00:00:00');
-
- expect(end).toContain(today);
- expect(end).toContain('23:59:59');
- });
- });
-
- describe('preview()', () => {
- it('should show the dialog summary', () => {
- controller.$.summary = {show: () => {}};
- jest.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();
- });
- });
-});
diff --git a/modules/monitor/front/index/tickets/style.scss b/modules/monitor/front/index/tickets/style.scss
deleted file mode 100644
index 102c92a8a..000000000
--- a/modules/monitor/front/index/tickets/style.scss
+++ /dev/null
@@ -1,47 +0,0 @@
-@import "variables";
-
-vn-monitor-sales-tickets {
- @media screen and (max-width: 1440px) {
- .expendable {
- display: none;
- }
- }
-
- vn-th.icon-field,
- vn-th.icon-field *,
- vn-td.icon-field,
- vn-td.icon-field * {
- padding: 0;
- max-width: 50px
- }
-
- vn-th[field="nickname"],
- vn-td[name="nickname"] {
- min-width: 250px
- }
-
- vn-td.icon-field > vn-icon {
- margin-left: 3px;
- margin-right: 3px;
- }
-
- vn-table.scrollable.lg {
- height: 736px
- }
-
- tbody tr[ng-repeat]:focus {
- background-color: $color-primary-light
- }
-
- .highRisk i {
- color: $color-alert
- }
-
- td[name="nickname"] {
- max-width: 200px
- }
-
- td[name="zone"] {
- max-width: 150px
- }
-}
\ No newline at end of file
diff --git a/modules/monitor/front/locale/es.yml b/modules/monitor/front/locale/es.yml
index 7d7e72f6b..01b26b70c 100644
--- a/modules/monitor/front/locale/es.yml
+++ b/modules/monitor/front/locale/es.yml
@@ -1 +1,16 @@
-Sales monitor: Monitor de ventas
\ No newline at end of file
+Tickets monitor: Monitor de tickets
+Clients on website: Clientes activos en la web
+Recent order actions: Acciones recientes en pedidos
+Search tickets: Buscar tickets
+Delete selected elements: Eliminar los elementos seleccionados
+All the selected elements will be deleted. Are you sure you want to continue?: Todos los elementos seleccionados serán eliminados. ¿Seguro que quieres continuar?
+Component lack: Faltan componentes
+Ticket too little: Ticket demasiado pequeño
+Minimize/Maximize: Minimizar/Maximizar
+Problems: Problemas
+Theoretical: Teórica
+Practical: Práctica
+Preparation: Preparación
+Auto-refresh: Auto-refresco
+Toggle auto-refresh every 2 minutes: Conmuta el refresco automático cada 2 minutos
+Is fragile: Es frágil
\ No newline at end of file
diff --git a/modules/monitor/front/main/index.html b/modules/monitor/front/main/index.html
index 6e04f06d0..e69de29bb 100644
--- a/modules/monitor/front/main/index.html
+++ b/modules/monitor/front/main/index.html
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/modules/monitor/front/main/index.js b/modules/monitor/front/main/index.js
index 42fc159d5..3af5292cb 100644
--- a/modules/monitor/front/main/index.js
+++ b/modules/monitor/front/main/index.js
@@ -1,7 +1,16 @@
import ngModule from '../module';
import ModuleMain from 'salix/components/module-main';
-export default class Monitor extends ModuleMain {}
+export default class Monitor extends ModuleMain {
+ constructor($element, $) {
+ super($element, $);
+ }
+
+ async $onInit() {
+ this.$state.go('home');
+ window.location.href = await this.vnApp.getUrl(`monitor/`);
+ }
+}
ngModule.vnComponent('vnMonitor', {
controller: Monitor,
diff --git a/modules/monitor/front/routes.json b/modules/monitor/front/routes.json
index acad3ecbc..30da8bcac 100644
--- a/modules/monitor/front/routes.json
+++ b/modules/monitor/front/routes.json
@@ -1,13 +1,9 @@
{
"module": "monitor",
"name": "Monitors",
- "icon" : "grid_view",
- "dependencies": ["ticket", "worker", "client"],
- "validations" : true,
+ "icon": "grid_view",
"menus": {
- "main": [
- {"state": "monitor.index", "icon": "grid_view"}
- ],
+ "main": [],
"card": []
},
"keybindings": [
@@ -23,7 +19,7 @@
"abstract": true,
"component": "vn-monitor",
"description": "Monitors"
- },
+ },
{
"url": "/index?q",
"state": "monitor.index",
diff --git a/modules/order/back/methods/order/filter.js b/modules/order/back/methods/order/filter.js
index 758e8065c..2aeb1aac5 100644
--- a/modules/order/back/methods/order/filter.js
+++ b/modules/order/back/methods/order/filter.js
@@ -22,7 +22,7 @@ module.exports = Self => {
}, {
arg: 'from',
type: 'date',
- description: 'The from date'
+ description: 'The from date',
}, {
arg: 'to',
type: 'date',
@@ -76,14 +76,15 @@ module.exports = Self => {
});
Self.filter = async(ctx, filter, options) => {
+ const models = Self.app.models;
const conn = Self.dataSource.connector;
const myOptions = {};
+ const userId = ctx.req.accessToken.userId;
if (typeof options == 'object')
Object.assign(myOptions, options);
const args = ctx.args;
-
// Apply filter by team
const teamMembersId = [];
if (args.myTeam != null) {
@@ -100,9 +101,12 @@ module.exports = Self => {
teamMembersId.push(userId);
}
- if (args && args.myTeam)
+ if (args?.myTeam)
args.teamIds = teamIds;
+ if (args?.to)
+ args.to.setHours(23, 59, 0, 0);
+
const where = buildFilter(args, (param, value) => {
switch (param) {
case 'search':
@@ -150,7 +154,12 @@ module.exports = Self => {
CREATE OR REPLACE TEMPORARY TABLE tmp.filter
(INDEX (id))
ENGINE = MEMORY
- SELECT o.id,
+ WITH wOrderTicket AS(
+ SELECT orderFk,
+ ticketFk
+ FROM orderTicket
+ GROUP BY orderFk
+ )SELECT o.id,
o.total,
o.date_send landed,
o.date_make created,
@@ -198,7 +207,6 @@ module.exports = Self => {
`);
stmt.merge(conn.makeWhere(filter.where));
- stmt.merge(`GROUP BY id`);
stmt.merge(conn.makePagination(filter));
stmts.push(stmt);
stmts.push(`SET SESSION optimizer_search_depth = @_optimizer_search_depth`);
@@ -211,7 +219,6 @@ module.exports = Self => {
const sql = ParameterizedSQL.join(stmts, ';');
const result = await conn.executeStmt(sql, myOptions);
-
return result[ordersIndex];
};
};
diff --git a/modules/order/front/basic-data/index.html b/modules/order/front/basic-data/index.html
deleted file mode 100644
index 019153b0d..000000000
--- a/modules/order/front/basic-data/index.html
+++ /dev/null
@@ -1,88 +0,0 @@
-
-
-
-
-
-
diff --git a/modules/order/front/basic-data/index.js b/modules/order/front/basic-data/index.js
deleted file mode 100644
index 16a3cea5e..000000000
--- a/modules/order/front/basic-data/index.js
+++ /dev/null
@@ -1,57 +0,0 @@
-import ngModule from '../module';
-import Section from 'salix/components/section';
-import './style.scss';
-
-class Controller extends Section {
- constructor($element, $) {
- super($element, $);
- let isDirty = false;
- this.$.$watch('$ctrl.selection', newValue => {
- if (newValue) {
- this.$.addressModel.where = {clientFk: newValue.id};
- this.$.addressModel.refresh();
- if (isDirty)
- this.order.addressFk = newValue.defaultAddressFk;
- isDirty = true;
- } else {
- this.$.addressModel.clear();
- if (isDirty)
- this.order.addressFk = null;
- }
- });
- }
-
- set order(value = {}) {
- this._order = value;
-
- const agencyModeFk = value.agencyModeFk;
- this.getAvailableAgencies();
- this._order.agencyModeFk = agencyModeFk;
- }
-
- get order() {
- return this._order;
- }
-
- getAvailableAgencies() {
- const order = this.order;
- order.agencyModeFk = null;
-
- const params = {
- addressFk: order.addressFk,
- landed: order.landed
- };
- if (params.landed && params.addressFk) {
- this.$http.get(`Agencies/landsThatDay`, {params})
- .then(res => this._availableAgencies = res.data);
- }
- }
-}
-
-ngModule.vnComponent('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
deleted file mode 100644
index 21dee0765..000000000
--- a/modules/order/front/basic-data/index.spec.js
+++ /dev/null
@@ -1,67 +0,0 @@
-import './index.js';
-
-describe('Order', () => {
- describe('Component vnOrderBasicData', () => {
- let $httpBackend;
- let $httpParamSerializer;
- let controller;
- let $scope;
-
- beforeEach(ngModule('order'));
-
- beforeEach(inject(($compile, _$httpBackend_, $rootScope, _$httpParamSerializer_) => {
- $httpBackend = _$httpBackend_;
- $httpParamSerializer = _$httpParamSerializer_;
- $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() => {
- const addressId = 999;
- const id = 444;
-
- controller.selection = {id: id, defaultAddressFk: addressId};
- $scope.$digest();
-
- expect(controller.order.addressFk).toEqual(addressId);
- });
- });
-
- describe('getAvailableAgencies()', () => {
- it('should set agencyModeFk to null and get the available agencies if the order has landed and client', async() => {
- controller.order.agencyModeFk = 999;
- controller.order.addressFk = 999;
- controller.order.landed = Date.vnNew();
-
- const expectedAgencies = [{id: 1}, {id: 2}];
-
- const paramsObj = {
- addressFk: controller.order.addressFk,
- landed: controller.order.landed
- };
- const serializedParams = $httpParamSerializer(paramsObj);
- $httpBackend.expect('GET', `Agencies/landsThatDay?${serializedParams}`).respond(expectedAgencies);
- controller.getAvailableAgencies();
- $httpBackend.flush();
-
- expect(controller.order.agencyModeFk).toBeDefined();
- expect(controller._availableAgencies).toEqual(expectedAgencies);
- });
- });
- });
-});
diff --git a/modules/order/front/basic-data/locale/es.yml b/modules/order/front/basic-data/locale/es.yml
deleted file mode 100644
index 5c6014c9c..000000000
--- a/modules/order/front/basic-data/locale/es.yml
+++ /dev/null
@@ -1 +0,0 @@
-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
deleted file mode 100644
index 34d6c2931..000000000
--- a/modules/order/front/basic-data/style.scss
+++ /dev/null
@@ -1,9 +0,0 @@
-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
deleted file mode 100644
index 4f10c1728..000000000
--- a/modules/order/front/card/index.html
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
diff --git a/modules/order/front/card/index.js b/modules/order/front/card/index.js
deleted file mode 100644
index a7e5eeb5d..000000000
--- a/modules/order/front/card/index.js
+++ /dev/null
@@ -1,58 +0,0 @@
-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: 'salesPersonUser',
- scope: {
- fields: ['id', 'name']
- }
- }
- }
- }
- ]
- };
-
- return 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.vnComponent('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
deleted file mode 100644
index f0de26b72..000000000
--- a/modules/order/front/card/index.spec.js
+++ /dev/null
@@ -1,31 +0,0 @@
-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(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
deleted file mode 100644
index 42f2e0f50..000000000
--- a/modules/order/front/catalog-search-panel/index.html
+++ /dev/null
@@ -1,54 +0,0 @@
-
-
-
diff --git a/modules/order/front/catalog-search-panel/index.js b/modules/order/front/catalog-search-panel/index.js
deleted file mode 100644
index b84243ca7..000000000
--- a/modules/order/front/catalog-search-panel/index.js
+++ /dev/null
@@ -1,38 +0,0 @@
-import ngModule from '../module';
-import SearchPanel from 'core/components/searchbar/search-panel';
-
-class Controller extends SearchPanel {
- constructor($element, $) {
- super($element, $);
-
- this.filter = {};
- }
-
- get filter() {
- return this.$.filter;
- }
-
- set filter(value) {
- if (!value)
- value = {};
- if (!value.values)
- value.values = [{}];
-
- this.$.filter = value;
- }
-
- addValue() {
- this.filter.values.push({});
- setTimeout(() => this.parentPopover.relocate());
- }
-}
-
-ngModule.vnComponent('vnOrderCatalogSearchPanel', {
- template: require('./index.html'),
- controller: Controller,
- bindings: {
- onSubmit: '&?',
- parentPopover: '',
- resultTags: ''
- }
-});
diff --git a/modules/order/front/catalog-view/index.html b/modules/order/front/catalog-view/index.html
deleted file mode 100644
index b047e1e6a..000000000
--- a/modules/order/front/catalog-view/index.html
+++ /dev/null
@@ -1,81 +0,0 @@
-
-
-
-
-
-
-
-
-
-
- {{::item.name}}
-
-
- {{::item.subName}}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {{::item.minQuantity}}
-
-
-
-
-
-
-
-
-
-
-
diff --git a/modules/order/front/catalog-view/index.js b/modules/order/front/catalog-view/index.js
deleted file mode 100644
index 6f2cead8f..000000000
--- a/modules/order/front/catalog-view/index.js
+++ /dev/null
@@ -1,12 +0,0 @@
-import ngModule from '../module';
-import Component from 'core/lib/component';
-import './style.scss';
-
-ngModule.vnComponent('vnOrderCatalogView', {
- template: require('./index.html'),
- controller: Component,
- bindings: {
- order: '<',
- model: '<'
- }
-});
diff --git a/modules/order/front/catalog-view/locale/es.yml b/modules/order/front/catalog-view/locale/es.yml
deleted file mode 100644
index 187dbbc83..000000000
--- a/modules/order/front/catalog-view/locale/es.yml
+++ /dev/null
@@ -1 +0,0 @@
-Order created: Orden creada
\ No newline at end of file
diff --git a/modules/order/front/catalog-view/style.scss b/modules/order/front/catalog-view/style.scss
deleted file mode 100644
index 1e48745ca..000000000
--- a/modules/order/front/catalog-view/style.scss
+++ /dev/null
@@ -1,50 +0,0 @@
-@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: 448px;
- display: flex;
- overflow: hidden;
-
- & > * {
- padding-left: $spacing-md;
- }
- }
- }
- .catalog-list {
- padding-top: $spacing-sm;
- }
- .item-color-background {
- background: linear-gradient($color-bg-panel, $color-main);
- border-radius: 50%;
- margin-left: 140px;
- margin-top: 140px;
- width: 40px;
- height: 40px;
- position: absolute;
- }
- .item-color {
- margin: auto;
- margin-top: 5px;
- border-radius: 50%;
- width: 30px;
- height: 30px;
- position: relative;
- }
- .alert {
- color: $color-alert;
- }
-}
diff --git a/modules/order/front/catalog/index.html b/modules/order/front/catalog/index.html
deleted file mode 100644
index 0f7928c8b..000000000
--- a/modules/order/front/catalog/index.html
+++ /dev/null
@@ -1,166 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {{name}}
-
- {{categoryName}}
-
-
-
-
-
-
-
-
-
-
- More than {{model.limit}} results
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Id: {{$ctrl.itemId}}
-
-
-
-
- Name :
-
- {{$ctrl.itemName}}
-
-
-
- {{category.selection.name}}
-
-
- {{type.selection.name}}
-
-
-
-
- {{::tagGroup.tagSelection.name}} :
-
-
- ,
- "{{::tagValue.value}}"
-
-
-
-
-
diff --git a/modules/order/front/catalog/index.js b/modules/order/front/catalog/index.js
deleted file mode 100644
index c0777ebc9..000000000
--- a/modules/order/front/catalog/index.js
+++ /dev/null
@@ -1,377 +0,0 @@
-import ngModule from '../module';
-import Section from 'salix/components/section';
-import './style.scss';
-
-class Controller extends Section {
- constructor($element, $) {
- super($element, $);
- this.itemTypes = [];
- this._tagGroups = [];
-
- // Static autocomplete data
- this.orderWays = [
- {way: 'ASC', name: 'Ascendant'},
- {way: 'DESC', name: 'Descendant'},
- ];
- this.defaultOrderFields = [
- {field: 'relevancy DESC, name', name: 'Relevancy', priority: 999},
- {field: 'showOrder, price', name: 'Color and price', priority: 999},
- {field: 'name', name: 'Name', priority: 999},
- {field: 'price', name: 'Price', priority: 999}
- ];
- this.orderFields = [].concat(this.defaultOrderFields);
- this._orderWay = this.orderWays[0].way;
- this.orderField = this.orderFields[0].field;
- }
-
- $onChanges() {
- this.getData().then(() => {
- if (this.order && this.order.isConfirmed)
- this.$state.go('order.card.line');
- });
- }
-
- getData() {
- return this.$http.get(`Orders/${this.$params.id}`)
- .then(res => this.order = res.data);
- }
-
- /**
- * Fills order autocomplete with tags
- * obtained from last filtered
- */
- get order() {
- return this._order;
- }
-
- /**
- * Sets filter values from state params
- *
- * @param {Object} value - Order data
- */
- set order(value) {
- this._order = value;
-
- if (!value) return;
-
- this.$.$applyAsync(() => {
- if (this.$params.categoryId)
- this.categoryId = parseInt(this.$params.categoryId);
-
- if (this.$params.typeId)
- this.typeId = parseInt(this.$params.typeId);
-
- if (this.$params.tagGroups)
- this.tagGroups = JSON.parse(this.$params.tagGroups);
- });
- }
-
- get items() {
- return this._items;
- }
-
- set items(value) {
- this._items = value;
-
- if (!value) return;
-
- this.fetchResultTags(value);
- this.buildOrderFilter();
- }
-
- get categoryId() {
- return this._categoryId;
- }
-
- set categoryId(value = null) {
- this._categoryId = value;
- this.itemTypes = [];
- this.typeId = null;
-
- this.updateStateParams();
-
- if (this.tagGroups.length > 0)
- this.applyFilters();
-
- if (value)
- this.updateItemTypes();
- }
-
- changeCategory(id) {
- if (this._categoryId == id) id = null;
- this.categoryId = id;
- }
-
- get typeId() {
- return this._typeId;
- }
-
- set typeId(value) {
- this._typeId = value;
-
- this.updateStateParams();
-
- if (value || this.tagGroups.length > 0)
- this.applyFilters();
- }
-
- get tagGroups() {
- return this._tagGroups;
- }
-
- set tagGroups(value) {
- this._tagGroups = value;
-
- this.updateStateParams();
-
- if (value.length)
- this.applyFilters();
- }
-
- /**
- * Get order way ASC/DESC
- */
- get orderWay() {
- return this._orderWay;
- }
-
- set orderWay(value) {
- this._orderWay = value;
- if (value) this.applyOrder();
- }
-
- /**
- * Returns the order way selection
- */
- get orderSelection() {
- return this._orderSelection;
- }
-
- set orderSelection(value) {
- this._orderSelection = value;
-
- if (value) this.applyOrder();
- }
-
- /**
- * Apply order to model
- */
- applyOrder() {
- if (this.typeId || this.tagGroups.length > 0 || this.itemName)
- this.$.model.addFilter(null, {orderBy: this.getOrderBy()});
- }
-
- /**
- * Returns order param
- *
- * @return {Object} - Order param
- */
- getOrderBy() {
- const isTag = !!(this.orderSelection && this.orderSelection.isTag);
- return {
- field: this.orderField,
- way: this.orderWay,
- isTag: isTag
- };
- }
-
- /**
- * Refreshes item type dropdown data
- */
- updateItemTypes() {
- let params = {
- itemCategoryId: this.categoryId
- };
-
- const query = `Orders/${this.order.id}/getItemTypeAvailable`;
- this.$http.get(query, {params}).then(res =>
- this.itemTypes = res.data);
- }
-
- /**
- * Search by tag value
- * @param {object} event
- */
- onSearchByTag(event) {
- const value = this.$.search.value;
- if (event.key !== 'Enter' || !value) return;
- this.tagGroups.push({values: [{value: value}]});
- this.$.search.value = null;
- this.updateStateParams();
- this.applyFilters();
- }
-
- remove(index) {
- this.tagGroups.splice(index, 1);
- this.updateStateParams();
-
- if (this.tagGroups.length >= 0 || this.itemId || this.typeId)
- this.applyFilters();
- }
-
- removeItemId() {
- this.itemId = null;
- this.$.searchbar.doSearch({}, 'bar');
- }
-
- removeItemName() {
- this.itemName = null;
- this.$.searchbar.doSearch({}, 'bar');
- }
-
- applyFilters(filter = {}) {
- let newParams = {};
- let newFilter = Object.assign({}, filter);
- const model = this.$.model;
-
- if (this.categoryId)
- newFilter.categoryFk = this.categoryId;
-
- if (this.typeId)
- newFilter.typeFk = this.typeId;
-
- newParams = {
- orderFk: this.$params.id,
- orderBy: this.getOrderBy(),
- tagGroups: this.tagGroups,
- };
-
- return 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();
- const values = filter.values;
- const nonEmptyValues = values.filter(tagValue => {
- return tagValue.value;
- });
-
- filter.values = nonEmptyValues;
-
- if (filter.tagFk && nonEmptyValues.length) {
- this.tagGroups.push(filter);
- this.updateStateParams();
- this.applyFilters();
- }
- }
-
- /**
- * Updates url state params from filter values
- */
- updateStateParams() {
- const params = {};
-
- params.categoryId = undefined;
- if (this.categoryId)
- params.categoryId = this.categoryId;
-
- params.typeId = undefined;
- if (this.typeId)
- params.typeId = this.typeId;
-
- params.tagGroups = undefined;
- if (this.tagGroups && this.tagGroups.length)
- params.tagGroups = JSON.stringify(this.sanitizedTagGroupParam());
-
- this.$state.go(this.$state.current.name, params);
- }
-
- sanitizedTagGroupParam() {
- const tagGroups = [];
- for (let tagGroup of this.tagGroups) {
- const tagParam = {values: []};
-
- for (let tagValue of tagGroup.values)
- tagParam.values.push({value: tagValue.value});
-
- if (tagGroup.tagFk)
- tagParam.tagFk = tagGroup.tagFk;
-
- if (tagGroup.tagSelection) {
- tagParam.tagSelection = {
- name: tagGroup.tagSelection.name
- };
- }
-
- tagGroups.push(tagParam);
- }
-
- return tagGroups;
- }
-
- fetchResultTags(items) {
- const resultTags = [];
- for (let item of items) {
- for (let itemTag of item.tags) {
- const alreadyAdded = resultTags.findIndex(tag => {
- return tag.tagFk == itemTag.tagFk;
- });
-
- if (alreadyAdded == -1)
- resultTags.push({...itemTag, priority: 1});
- else
- resultTags[alreadyAdded].priority += 1;
- }
- }
- this.resultTags = resultTags;
- }
-
- buildOrderFilter() {
- const filter = [].concat(this.defaultOrderFields);
- for (let tag of this.resultTags)
- filter.push({...tag, field: tag.id, isTag: true});
-
- this.orderFields = filter;
- }
-
- onSearch(params) {
- if (!params) return;
-
- this.itemId = null;
- this.itemName = null;
-
- if (params.search) {
- if (/^\d+$/.test(params.search)) {
- this.itemId = params.search;
- return this.applyFilters({
- 'i.id': params.search
- });
- } else {
- this.itemName = params.search;
- return this.applyFilters({
- 'i.name': {like: `%${params.search}%`}
- });
- }
- } else return this.applyFilters();
- }
-
- formatTooltip(tagGroup) {
- const tagValues = tagGroup.values;
-
- let title = '';
- if (tagGroup.tagFk) {
- const tagName = tagGroup.tagSelection.name;
- title += `${tagName}: `;
- }
-
- for (let [i, tagValue] of tagValues.entries()) {
- if (i > 0) title += ', ';
- title += `"${tagValue.value}"`;
- }
-
- return `${title}`;
- }
-}
-
-ngModule.vnComponent('vnOrderCatalog', {
- template: require('./index.html'),
- controller: Controller
-});
diff --git a/modules/order/front/catalog/index.spec.js b/modules/order/front/catalog/index.spec.js
deleted file mode 100644
index 03d7c41ba..000000000
--- a/modules/order/front/catalog/index.spec.js
+++ /dev/null
@@ -1,386 +0,0 @@
-import './index.js';
-import crudModel from 'core/mocks/crud-model';
-
-describe('Order', () => {
- describe('Component vnOrderCatalog', () => {
- let $scope;
- let $state;
- let controller;
- let $httpBackend;
-
- beforeEach(ngModule('order'));
-
- beforeEach(inject(($componentController, _$state_, _$httpBackend_, $rootScope) => {
- $httpBackend = _$httpBackend_;
- $scope = $rootScope.$new();
- $scope.model = crudModel;
- $scope.search = {};
- $scope.itemId = {};
- $state = _$state_;
- $state.current.name = 'my.current.state';
- const $element = angular.element(' ');
- controller = $componentController('vnOrderCatalog', {$element, $scope});
- controller._order = {id: 4};
- controller.$params = {
- categoryId: 1,
- typeId: 2,
- id: 4
- };
- }));
-
- describe('getData()', () => {
- it(`should make a query an fetch the order data`, () => {
- controller._order = null;
-
- $httpBackend.expect('GET', `Orders/4`).respond(200, {id: 4, isConfirmed: true});
- $httpBackend.expect('GET', `Orders/4/getItemTypeAvailable?itemCategoryId=1`).respond();
- controller.getData();
- $httpBackend.flush();
-
- const order = controller.order;
-
- expect(order.id).toEqual(4);
- expect(order.isConfirmed).toBeTruthy();
- });
- });
-
- 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.categoryId).toEqual(1);
- expect(controller.typeId).toEqual(2);
- });
- });
-
- describe('items() setter', () => {
- it(`should return an object with order params`, () => {
- jest.spyOn(controller, 'fetchResultTags');
- jest.spyOn(controller, 'buildOrderFilter');
-
- const expectedResult = [{field: 'showOrder, price', name: 'Color and price', priority: 999}];
- const items = [{id: 1, name: 'My Item', tags: [
- {tagFk: 4, name: 'Length'},
- {tagFk: 5, name: 'Color'}
- ]}];
- controller.items = items;
-
- expect(controller.orderFields.length).toEqual(6);
- expect(controller.orderFields).toEqual(jasmine.arrayContaining(expectedResult));
- expect(controller.fetchResultTags).toHaveBeenCalledWith(items);
- expect(controller.buildOrderFilter).toHaveBeenCalledWith();
- });
- });
-
- describe('categoryId() setter', () => {
- it(`should set category property to null, call updateStateParams() method and not call applyFilters()`, () => {
- jest.spyOn(controller, 'updateStateParams');
-
- controller.categoryId = null;
-
- expect(controller.updateStateParams).toHaveBeenCalledWith();
- });
-
- it(`should set category property and then call updateStateParams() and applyFilters() methods`, () => {
- jest.spyOn(controller, 'updateStateParams');
-
- controller.categoryId = 2;
-
- expect(controller.updateStateParams).toHaveBeenCalledWith();
- });
- });
-
- describe('changeCategory()', () => {
- it(`should set categoryId property to null if the new value equals to the old one`, () => {
- controller.categoryId = 2;
- controller.changeCategory(2);
-
- expect(controller.categoryId).toBeNull();
- });
-
- it(`should set categoryId property`, () => {
- controller.categoryId = 2;
- controller.changeCategory(1);
-
- expect(controller.categoryId).toEqual(1);
- });
- });
-
- describe('typeId() setter', () => {
- it(`should set type property to null, call updateStateParams() method and not call applyFilters()`, () => {
- jest.spyOn(controller, 'updateStateParams');
- jest.spyOn(controller, 'applyFilters');
-
- controller.typeId = null;
-
- expect(controller.updateStateParams).toHaveBeenCalledWith();
- expect(controller.applyFilters).not.toHaveBeenCalledWith();
- });
-
- it(`should set category property and then call updateStateParams() and applyFilters() methods`, () => {
- jest.spyOn(controller, 'updateStateParams');
- jest.spyOn(controller, 'applyFilters');
-
- controller.typeId = 2;
-
- expect(controller.updateStateParams).toHaveBeenCalledWith();
- expect(controller.applyFilters).toHaveBeenCalledWith();
- });
- });
-
- describe('tagGroups() setter', () => {
- it(`should set tagGroups property and then call updateStateParams() and applyFilters() methods`, () => {
- jest.spyOn(controller, 'updateStateParams');
- jest.spyOn(controller, 'applyFilters');
-
- controller.tagGroups = [{tagFk: 11, values: [{value: 'Brown'}]}];
-
- 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'`, () => {
- jest.spyOn(controller, 'applyFilters');
-
- controller.order = {id: 4};
- controller.$.search.value = 'Brown';
- 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()`, () => {
- jest.spyOn(controller, 'applyFilters');
-
- controller.order = {id: 4};
- controller.$.search.value = 'Brown';
- controller.onSearchByTag({key: 'Enter'});
-
- expect(controller.applyFilters).toHaveBeenCalledWith();
- });
- });
-
- describe('onSearch()', () => {
- it(`should apply a filter by item id an then call the applyFilters method`, () => {
- jest.spyOn(controller, 'applyFilters');
-
- const itemId = 1;
- controller.onSearch({search: itemId});
-
- expect(controller.applyFilters).toHaveBeenCalledWith({
- 'i.id': itemId
- });
- });
-
- it(`should apply a filter by item name an then call the applyFilters method`, () => {
- jest.spyOn(controller, 'applyFilters');
-
- const itemName = 'Bow';
- controller.onSearch({search: itemName});
-
- expect(controller.applyFilters).toHaveBeenCalledWith({
- 'i.name': {like: `%${itemName}%`}
- });
- });
- });
-
- describe('applyFilters()', () => {
- it(`should call model applyFilter() method with a new filter`, () => {
- jest.spyOn(controller.$.model, 'applyFilter');
-
- controller._categoryId = 2;
- controller._typeId = 4;
-
- controller.applyFilters();
-
- expect(controller.$.model.applyFilter).toHaveBeenCalledWith(
- {where: {categoryFk: 2, typeFk: 4}},
- {orderFk: 4, orderBy: controller.getOrderBy(), tagGroups: []});
- });
- });
-
- describe('remove()', () => {
- it(`should remove a tag from tags property`, () => {
- jest.spyOn(controller, 'applyFilters');
-
- controller.tagGroups = [
- {tagFk: 1, values: [{value: 'Brown'}]},
- {tagFk: 67, values: [{value: 'Concussion'}]}
- ];
- controller.remove(0);
-
- const firstTag = controller.tagGroups[0];
-
- expect(controller.tagGroups.length).toEqual(1);
- expect(firstTag.tagFk).toEqual(67);
- expect(controller.applyFilters).toHaveBeenCalledWith();
- });
-
- it(`should remove a tag from tags property and call applyFilters() if there's no more tags`, () => {
- jest.spyOn(controller, 'applyFilters');
-
- controller._categoryId = 1;
- controller._typeId = 1;
- controller.tagGroups = [{tagFk: 1, values: [{value: 'Blue'}]}];
- controller.remove(0);
-
- expect(controller.tagGroups.length).toEqual(0);
- expect(controller.applyFilters).toHaveBeenCalledWith();
- });
- });
-
- describe('updateStateParams()', () => {
- it(`should call state go() method passing category and type state params`, () => {
- jest.spyOn(controller.$state, 'go');
-
- controller._categoryId = 2;
- controller._typeId = 4;
- controller._tagGroups = [
- {tagFk: 67, values: [{value: 'Concussion'}], tagSelection: {name: 'Category'}}
- ];
- const tagGroups = JSON.stringify([
- {values: [{value: 'Concussion'}], tagFk: 67, tagSelection: {name: 'Category'}}
- ]);
- const expectedResult = {categoryId: 2, typeId: 4, tagGroups: tagGroups};
- controller.updateStateParams();
-
- expect(controller.$state.go).toHaveBeenCalledWith('my.current.state', expectedResult);
- });
- });
-
- 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()`, () => {
- jest.spyOn(controller, 'getOrderBy');
- jest.spyOn(controller.$.model, 'addFilter');
-
- controller.field = 'relevancy DESC, name';
- controller.way = 'ASC';
- controller._categoryId = 1;
- controller._typeId = 1;
- let expectedOrder = {orderBy: controller.getOrderBy()};
-
- controller.applyOrder();
-
- expect(controller.getOrderBy).toHaveBeenCalledWith();
- expect(controller.$.model.addFilter).toHaveBeenCalledWith(null, expectedOrder);
- });
- });
-
- describe('fetchResultTags()', () => {
- it(`should create an array of non repeated tags then set the resultTags property`, () => {
- const items = [
- {
- id: 1, name: 'My Item 1', tags: [
- {tagFk: 4, name: 'Length', value: 1},
- {tagFk: 5, name: 'Color', value: 'red'}
- ]
- },
- {
- id: 2, name: 'My Item 2', tags: [
- {tagFk: 4, name: 'Length', value: 1},
- {tagFk: 5, name: 'Color', value: 'blue'}
- ]
- }];
- controller.fetchResultTags(items);
-
- expect(controller.resultTags.length).toEqual(2);
- });
- });
-
- describe('buildOrderFilter()', () => {
- it(`should create an array of non repeated tags plus default filters and then set the orderFields property`, () => {
- const items = [
- {
- id: 1, name: 'My Item 1', tags: [
- {tagFk: 4, name: 'Length'},
- {tagFk: 5, name: 'Color'}
- ]
- },
- {
- id: 2, name: 'My Item 2', tags: [
- {tagFk: 5, name: 'Color'},
- {tagFk: 6, name: 'Relevancy'}
- ]
- }];
-
- controller.fetchResultTags(items);
- controller.buildOrderFilter();
-
- expect(controller.orderFields.length).toEqual(7);
- });
- });
-
- describe('formatTooltip()', () => {
- it(`should return a formatted text with the tag name and values`, () => {
- const tagGroup = {
- values: [{value: 'Silver'}, {value: 'Brown'}],
- tagFk: 1,
- tagSelection: {
- name: 'Color'
- }
- };
-
- const result = controller.formatTooltip(tagGroup);
-
- expect(result).toEqual(`Color: "Silver", "Brown"`);
- });
-
- it(`should return a formatted text with the tag value`, () => {
- const tagGroup = {
- values: [{value: 'Silver'}]
- };
-
- const result = controller.formatTooltip(tagGroup);
-
- expect(result).toEqual(`"Silver"`);
- });
- });
-
- describe('sanitizedTagGroupParam()', () => {
- it(`should return an array of tags`, () => {
- const dirtyTagGroups = [{
- values: [{value: 'Silver'}, {value: 'Brown'}],
- tagFk: 1,
- tagSelection: {
- name: 'Color',
- $orgRow: {name: 'Color'}
- },
- $orgIndex: 1
- }];
- controller.tagGroups = dirtyTagGroups;
-
- const expectedResult = [{
- values: [{value: 'Silver'}, {value: 'Brown'}],
- tagFk: 1,
- tagSelection: {
- name: 'Color'
- }
- }];
- const result = controller.sanitizedTagGroupParam();
-
- expect(result).toEqual(expect.objectContaining(expectedResult));
- });
- });
- });
-});
-
diff --git a/modules/order/front/catalog/locale/es.yml b/modules/order/front/catalog/locale/es.yml
deleted file mode 100644
index fc78755ae..000000000
--- a/modules/order/front/catalog/locale/es.yml
+++ /dev/null
@@ -1,3 +0,0 @@
-Name: Nombre
-Search by item id or name: Buscar por id de artículo o nombre
-OR: O
\ No newline at end of file
diff --git a/modules/order/front/catalog/style.scss b/modules/order/front/catalog/style.scss
deleted file mode 100644
index 9ffe81dfb..000000000
--- a/modules/order/front/catalog/style.scss
+++ /dev/null
@@ -1,54 +0,0 @@
-@import "variables";
-
-vn-order-catalog vn-side-menu 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-autocomplete[vn-id="category"] {
- display: none
- }
-
- & > 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: 2.6rem;
- width: 16px;
- height: 16px;
- }
- }
- }
- }
- .chips {
- display: flex;
- flex-wrap: wrap;
- padding: $spacing-md;
- overflow: hidden;
- max-width: 100%;
- }
- vn-autocomplete[vn-id="type"] .list {
- max-height: 320px
- }
-}
\ No newline at end of file
diff --git a/modules/order/front/create/card.html b/modules/order/front/create/card.html
deleted file mode 100644
index ed6f752d3..000000000
--- a/modules/order/front/create/card.html
+++ /dev/null
@@ -1,38 +0,0 @@
-
- {{id}}: {{name}}
-
-
- {{nickname}}: {{street}}, {{city}}
-
-
-
-
-
diff --git a/modules/order/front/create/card.js b/modules/order/front/create/card.js
deleted file mode 100644
index 315cc8255..000000000
--- a/modules/order/front/create/card.js
+++ /dev/null
@@ -1,114 +0,0 @@
-import ngModule from '../module';
-import Component from 'core/lib/component';
-
-class Controller extends Component {
- constructor($element, $) {
- super($element, $);
- this.order = {};
- this.clientFk = this.$params.clientFk;
- }
-
- $onInit() {
- if (this.$params && this.$params.clientFk)
- this.clientFk = this.$params.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.$t('Data saved!'));
- this.$state.go('order.card.catalog', {id: res.data});
- });
- }
-}
-
-ngModule.vnComponent('vnOrderCreateCard', {
- template: require('./card.html'),
- controller: Controller,
- bindings: {
- order: ''
- }
-});
diff --git a/modules/order/front/create/card.spec.js b/modules/order/front/create/card.spec.js
deleted file mode 100644
index e37900af6..000000000
--- a/modules/order/front/create/card.spec.js
+++ /dev/null
@@ -1,104 +0,0 @@
-import './card.js';
-
-describe('Order', () => {
- describe('Component vnOrderCreateCard', () => {
- let controller;
- let $httpBackend;
- let $scope;
-
- beforeEach(ngModule('order'));
-
- beforeEach(inject(($componentController, _$httpBackend_, _vnApp_, $rootScope) => {
- $httpBackend = _$httpBackend_;
- $scope = $rootScope.$new();
- const $element = angular.element(' ');
- controller = $componentController('vnOrderCreateCard', {$element, $scope});
- 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 = 1101;
-
- expect(controller.addressFk).toEqual(1101);
- expect(controller.order.agencyModeFk).toBe(null);
- });
- });
-
- describe('getAvailableAgencies()', () => {
- it(`should make a query if landed and addressFk exists`, () => {
- controller.order.addressFk = 1101;
- controller.order.landed = 1101;
-
- $httpBackend.whenRoute('GET', 'Agencies/landsThatDay')
- .respond({data: 1});
-
- controller.getAvailableAgencies();
- $httpBackend.flush();
- });
- });
-
- describe('onSubmit()', () => {
- it(`should call createOrder()`, () => {
- jest.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 = 1101;
- controller.order.addressFk = 1101;
- controller.order.agencyModeFk = 1101;
-
- jest.spyOn(controller.vnApp, 'showSuccess');
- jest.spyOn(controller.$state, 'go');
- $httpBackend.expect('POST', 'Orders/new', {landed: 1101, addressId: 1101, agencyModeId: 1101}).respond(200, 1);
- controller.createOrder();
- $httpBackend.flush();
-
- expect(controller.vnApp.showSuccess).toHaveBeenCalled();
- 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
deleted file mode 100644
index 86df579a6..000000000
--- a/modules/order/front/create/index.html
+++ /dev/null
@@ -1,16 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/modules/order/front/create/index.js b/modules/order/front/create/index.js
deleted file mode 100644
index 317c4e27e..000000000
--- a/modules/order/front/create/index.js
+++ /dev/null
@@ -1,14 +0,0 @@
-import ngModule from '../module';
-import Section from 'salix/components/section';
-
-class Controller extends Section {
- async onSubmit() {
- let newOrderID = await this.$.card.createOrder();
- this.$state.go('order.card.summary', {id: newOrderID});
- }
-}
-
-ngModule.vnComponent('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
deleted file mode 100644
index af8c8f974..000000000
--- a/modules/order/front/create/index.spec.js
+++ /dev/null
@@ -1,34 +0,0 @@
-import './index.js';
-
-describe('Order', () => {
- describe('Component vnOrderCreate', () => {
- let $scope;
- let controller;
-
- beforeEach(ngModule('order'));
-
- beforeEach(inject(($componentController, $rootScope) => {
- $scope = $rootScope.$new();
- $scope.card = {createOrder: () => {}};
- const $element = angular.element(' ');
- controller = $componentController('vnOrderCreate', {$element, $scope});
- }));
-
- describe('onSubmit()', () => {
- it(`should call createOrder()`, () => {
- jest.spyOn(controller.$.card, 'createOrder');
- controller.onSubmit();
-
- expect(controller.$.card.createOrder).toHaveBeenCalledWith();
- });
-
- it(`should call go()`, async() => {
- jest.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
deleted file mode 100644
index 49cd64c4a..000000000
--- a/modules/order/front/create/locale/es.yml
+++ /dev/null
@@ -1,6 +0,0 @@
-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 an 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
deleted file mode 100644
index 538789027..000000000
--- a/modules/order/front/descriptor/index.html
+++ /dev/null
@@ -1,78 +0,0 @@
-
-
-
- Delete order
-
-
-
-
-
-
-
-
- {{$ctrl.order.client.salesPersonUser.name}}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/modules/order/front/descriptor/index.js b/modules/order/front/descriptor/index.js
deleted file mode 100644
index 5d22dd721..000000000
--- a/modules/order/front/descriptor/index.js
+++ /dev/null
@@ -1,32 +0,0 @@
-import ngModule from '../module';
-import Descriptor from 'salix/components/descriptor';
-
-class Controller extends Descriptor {
- get order() {
- return this.entity;
- }
-
- set order(value) {
- this.entity = value;
- }
-
- get ticketFilter() {
- return JSON.stringify({orderFk: this.id});
- }
-
- deleteOrder() {
- return this.$http.delete(`Orders/${this.id}`)
- .then(() => {
- this.$state.go('order.index');
- this.vnApp.showSuccess(this.$t('Order deleted'));
- });
- }
-}
-
-ngModule.vnComponent('vnOrderDescriptor', {
- template: require('./index.html'),
- controller: Controller,
- bindings: {
- order: '<'
- }
-});
diff --git a/modules/order/front/descriptor/index.spec.js b/modules/order/front/descriptor/index.spec.js
deleted file mode 100644
index e6147faee..000000000
--- a/modules/order/front/descriptor/index.spec.js
+++ /dev/null
@@ -1,29 +0,0 @@
-import './index.js';
-
-describe('Order Component vnOrderDescriptor', () => {
- let $httpBackend;
- let controller;
- const order = {id: 1};
-
- beforeEach(ngModule('order'));
-
- beforeEach(inject(($componentController, _$httpBackend_) => {
- $httpBackend = _$httpBackend_;
- controller = $componentController('vnOrderDescriptor', {$element: null}, {order});
- }));
-
- describe('deleteOrder()', () => {
- it(`should perform a DELETE query`, () => {
- jest.spyOn(controller.vnApp, 'showSuccess');
- jest.spyOn(controller.$state, 'go');
-
- $httpBackend.expectDELETE(`Orders/${order.id}`).respond();
- controller.deleteOrder();
- $httpBackend.flush();
-
- expect(controller.vnApp.showSuccess).toHaveBeenCalled();
- 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
deleted file mode 100644
index 0734d7638..000000000
--- a/modules/order/front/descriptor/locale/es.yml
+++ /dev/null
@@ -1,12 +0,0 @@
-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/index.js b/modules/order/front/index.js
index 4d5b5615e..a7209a0bd 100644
--- a/modules/order/front/index.js
+++ b/modules/order/front/index.js
@@ -1,17 +1,3 @@
export * from './module';
import './main';
-import './index/';
-import './card';
-import './descriptor';
-import './search-panel';
-import './catalog-search-panel';
-import './catalog-view';
-import './catalog';
-import './summary';
-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
deleted file mode 100644
index c4bed7307..000000000
--- a/modules/order/front/index/index.html
+++ /dev/null
@@ -1,90 +0,0 @@
-
-
-
-
-
-
-
-
- Id
- Sales person
- Client
- Confirmed
- Created
- Landed
- Hour
- Agency
- Total
-
-
-
-
- {{::order.id}}
-
-
- {{::order.name | dashIfEmpty}}
-
-
-
-
- {{::order.clientName}}
-
-
-
-
-
-
- {{::order.created | date: 'dd/MM/yyyy HH:mm'}}
-
-
- {{::order.landed | date:'dd/MM/yyyy'}}
-
-
- {{::(order.hourTheoretical
- ? order.hourTheoretical
- : order.hourEffective) | dashIfEmpty
- }}
- {{::order.agencyName}}
- {{::order.total | currency: 'EUR': 2 | dashIfEmpty}}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/modules/order/front/index/index.js b/modules/order/front/index/index.js
deleted file mode 100644
index 750f2e226..000000000
--- a/modules/order/front/index/index.js
+++ /dev/null
@@ -1,26 +0,0 @@
-import ngModule from '../module';
-import Section from 'salix/components/section';
-
-export default class Controller extends Section {
- preview(order) {
- this.selectedOrder = order;
- this.$.summary.show();
- }
-
- compareDate(date) {
- let today = Date.vnNew();
- today.setHours(0, 0, 0, 0);
-
- date = new Date(date);
- date.setHours(0, 0, 0, 0);
-
- const timeDifference = today - date;
- if (timeDifference == 0) return 'warning';
- if (timeDifference < 0) return 'success';
- }
-}
-
-ngModule.vnComponent('vnOrderIndex', {
- template: require('./index.html'),
- controller: Controller
-});
diff --git a/modules/order/front/index/index.spec.js b/modules/order/front/index/index.spec.js
deleted file mode 100644
index abe336478..000000000
--- a/modules/order/front/index/index.spec.js
+++ /dev/null
@@ -1,67 +0,0 @@
-import './index.js';
-describe('Component vnOrderIndex', () => {
- let controller;
- let $window;
- let orders = [{
- id: 1,
- clientFk: 1,
- isConfirmed: false
- }, {
- id: 2,
- clientFk: 1,
- isConfirmed: false
- }, {
- id: 3,
- clientFk: 1,
- isConfirmed: true
- }];
-
- beforeEach(ngModule('order'));
-
- beforeEach(inject(($componentController, _$window_) => {
- $window = _$window_;
- const $element = angular.element(' ');
- controller = $componentController('vnOrderIndex', {$element});
- }));
-
- describe('compareDate()', () => {
- it('should return warning when the date is the present', () => {
- let curDate = Date.vnNew();
- let result = controller.compareDate(curDate);
-
- expect(result).toEqual('warning');
- });
-
- it('should return sucess when the date is in the future', () => {
- let futureDate = Date.vnNew();
- 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 = Date.vnNew();
- pastDate = pastDate.setDate(pastDate.getDate() - 10);
- let result = controller.compareDate(pastDate);
-
- expect(result).toEqual(undefined);
- });
- });
-
- describe('preview()', () => {
- it('should show the dialog summary', () => {
- controller.$.summary = {show: () => {}};
- jest.spyOn(controller.$.summary, 'show');
-
- let event = new MouseEvent('click', {
- view: $window,
- bubbles: true,
- cancelable: true
- });
- controller.preview(event, orders[0]);
-
- expect(controller.$.summary.show).toHaveBeenCalledWith();
- });
- });
-});
diff --git a/modules/order/front/line/index.html b/modules/order/front/line/index.html
deleted file mode 100644
index 7be5a00af..000000000
--- a/modules/order/front/line/index.html
+++ /dev/null
@@ -1,96 +0,0 @@
-
-
-
-
-
-
-
- Id
- Description
- Warehouse
- Shipped
- Quantity
- Price
- Amount
-
-
-
-
-
-
-
-
-
-
- {{::row.itemFk}}
-
-
-
-
- {{::row.item.name}}
-
- {{::row.item.subName}}
-
-
-
-
-
- {{::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
deleted file mode 100644
index 94d1fbfbf..000000000
--- a/modules/order/front/line/index.js
+++ /dev/null
@@ -1,70 +0,0 @@
-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())
- .then(() => this.vnApp.showSuccess(this.$t('Data saved!')));
- }
-
- 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.vnComponent('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
deleted file mode 100644
index ad0e1edbc..000000000
--- a/modules/order/front/line/index.spec.js
+++ /dev/null
@@ -1,66 +0,0 @@
-import './index.js';
-
-describe('Order', () => {
- describe('Component vnOrderLine', () => {
- let $state;
- let controller;
- let $httpBackend;
-
- const vat = 10.5;
- const rows = [
- {
- quantity: 4,
- price: 10.5
- }, {
- quantity: 3,
- price: 2.4
- }
- ];
-
- beforeEach(ngModule('order'));
-
- beforeEach(inject(($componentController, _$state_, _$httpBackend_) => {
- $state = _$state_;
- $httpBackend = _$httpBackend_;
-
- $state.params.id = 1;
- $httpBackend.whenGET(`OrderRows`).respond(rows);
- $httpBackend.whenRoute('GET', `Orders/:id/getVAT`).respond(200, vat);
-
- controller = $componentController('vnOrderLine', {$element: null});
- }));
-
- describe('getRows()', () => {
- it('should make a query to get the rows of a given order', () => {
- controller.getRows();
- $httpBackend.flush();
-
- expect(controller.rows).toEqual(rows);
- });
- });
-
- describe('getVAT()', () => {
- it('should make a query to get the VAT of a given order', () => {
- controller.getVAT();
- $httpBackend.flush();
-
- expect(controller.VAT).toBe(vat);
- });
- });
-
- 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).toHaveBeenCalled();
- });
- });
- });
-});
diff --git a/modules/order/front/line/locale/es.yml b/modules/order/front/line/locale/es.yml
deleted file mode 100644
index d1368d369..000000000
--- a/modules/order/front/line/locale/es.yml
+++ /dev/null
@@ -1,3 +0,0 @@
-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
deleted file mode 100644
index 4da941a2c..000000000
--- a/modules/order/front/line/style.scss
+++ /dev/null
@@ -1,18 +0,0 @@
-@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/main/index.js b/modules/order/front/main/index.js
index caf819c9d..61b0201fd 100644
--- a/modules/order/front/main/index.js
+++ b/modules/order/front/main/index.js
@@ -2,8 +2,12 @@ import ngModule from '../module';
import ModuleMain from 'salix/components/module-main';
export default class Order extends ModuleMain {
- $postLink() {
- this.filter = {showEmpty: false};
+ constructor($element, $) {
+ super($element, $);
+ }
+ async $onInit() {
+ this.$state.go('home');
+ window.location.href = await this.vnApp.getUrl(`order/`);
}
}
diff --git a/modules/order/front/prices-popover/index.html b/modules/order/front/prices-popover/index.html
deleted file mode 100644
index 2551853e6..000000000
--- a/modules/order/front/prices-popover/index.html
+++ /dev/null
@@ -1,52 +0,0 @@
-
-
-
diff --git a/modules/order/front/prices-popover/index.js b/modules/order/front/prices-popover/index.js
deleted file mode 100644
index aa5570f59..000000000
--- a/modules/order/front/prices-popover/index.js
+++ /dev/null
@@ -1,115 +0,0 @@
-import ngModule from '../module';
-import Popover from 'core/components/popover';
-import './style.scss';
-
-class Controller extends Popover {
- constructor(...args) {
- super(...args);
- this.totalBasquet = 0;
- }
-
- set prices(value) {
- this._prices = value;
- if (value && value[0].grouping)
- this.getTotalQuantity();
- }
-
- get prices() {
- return this._prices;
- }
-
- show(parent, item) {
- this.id = item.id;
- this.item = JSON.parse(JSON.stringify(item));
- this.maxQuantity = this.item.available;
- this.prices = this.item.prices;
-
- super.show(parent);
- }
-
- onClose() {
- this.id = null;
- this.item = {};
- this.tags = {};
- this._prices = {};
- this.totalQuantity = 0;
- super.onClose();
- }
-
- getTotalQuantity() {
- let total = 0;
- for (let price of this.prices) {
- if (!price.quantity) price.quantity = 0;
- total += price.quantity;
- }
-
- this.totalQuantity = total;
- }
-
- addQuantity(price) {
- this.getTotalQuantity();
- const quantity = this.totalQuantity + price.grouping;
- if (quantity <= this.maxQuantity)
- price.quantity += price.grouping;
- }
-
- getGroupings() {
- const filledRows = [];
- for (let priceOption of this.prices) {
- if (priceOption.quantity && priceOption.quantity > 0) {
- const priceMatch = filledRows.find(row => {
- return row.warehouseFk == priceOption.warehouseFk
- && row.price == priceOption.price;
- });
-
- if (!priceMatch)
- filledRows.push(Object.assign({}, priceOption));
- else priceMatch.quantity += priceOption.quantity;
- }
- }
-
- return filledRows;
- }
-
- submit() {
- const filledRows = this.getGroupings();
-
- try {
- const hasInvalidGropings = filledRows.some(row =>
- row.quantity % row.grouping != 0
- );
-
- if (filledRows.length <= 0)
- throw new Error('First you must add some quantity');
-
- if (hasInvalidGropings)
- throw new Error(`The amounts doesn't match with the grouping`);
-
- const params = {
- orderFk: this.order.id,
- items: filledRows
- };
- this.$http.post(`OrderRows/addToOrder`, params)
- .then(() => {
- this.vnApp.showSuccess(this.$t('Data saved!'));
- this.hide();
- if (this.card) this.card.reload();
- });
- } catch (e) {
- this.vnApp.showError(this.$t(e.message));
- return false;
- }
- return true;
- }
-}
-
-ngModule.vnComponent('vnOrderPricesPopover', {
- slotTemplate: require('./index.html'),
- controller: Controller,
- bindings: {
- order: '<'
- },
- require: {
- card: '?^vnOrderCard'
- }
-});
diff --git a/modules/order/front/prices-popover/index.spec.js b/modules/order/front/prices-popover/index.spec.js
deleted file mode 100644
index 734a9e254..000000000
--- a/modules/order/front/prices-popover/index.spec.js
+++ /dev/null
@@ -1,171 +0,0 @@
-import './index.js';
-
-describe('Order', () => {
- describe('Component vnOrderPricesPopover', () => {
- let controller;
- let $httpBackend;
- let orderId = 16;
-
- beforeEach(ngModule('order'));
-
- beforeEach(inject(($componentController, $rootScope, _$httpBackend_) => {
- $httpBackend = _$httpBackend_;
- const $scope = $rootScope.$new();
- const $element = angular.element(' ');
- const $transclude = {
- $$boundTransclude: {
- $$slots: []
- }
- };
- controller = $componentController('vnOrderPricesPopover', {$element, $scope, $transclude});
- controller._prices = [
- {warehouseFk: 1, grouping: 10, quantity: 0},
- {warehouseFk: 1, grouping: 100, quantity: 100}
- ];
- controller.item = {available: 1000};
- controller.maxQuantity = 1000;
- controller.order = {id: orderId};
- }));
-
- describe('prices() setter', () => {
- it('should call to the getTotalQuantity() method', () => {
- controller.getTotalQuantity = jest.fn();
-
- controller.prices = [
- {grouping: 10, quantity: 0},
- {grouping: 100, quantity: 0},
- {grouping: 1000, quantity: 0},
- ];
-
- expect(controller.getTotalQuantity).toHaveBeenCalledWith();
- });
- });
-
- describe('getTotalQuantity()', () => {
- it('should set the totalQuantity property', () => {
- controller.getTotalQuantity();
-
- expect(controller.totalQuantity).toEqual(100);
- });
- });
-
- describe('addQuantity()', () => {
- it('should call to the getTotalQuantity() method and NOT set the quantity property', () => {
- jest.spyOn(controller, 'getTotalQuantity');
-
- controller.prices = [
- {grouping: 10, quantity: 0},
- {grouping: 100, quantity: 0},
- {grouping: 1000, quantity: 1000},
- ];
-
- const oneThousandGrouping = controller.prices[2];
-
- expect(oneThousandGrouping.quantity).toEqual(1000);
-
- controller.addQuantity(oneThousandGrouping);
-
- expect(controller.getTotalQuantity).toHaveBeenCalledWith();
- expect(oneThousandGrouping.quantity).toEqual(1000);
- });
-
- it('should call to the getTotalQuantity() method and then set the quantity property', () => {
- jest.spyOn(controller, 'getTotalQuantity');
-
- const oneHandredGrouping = controller.prices[1];
- controller.addQuantity(oneHandredGrouping);
-
- expect(controller.getTotalQuantity).toHaveBeenCalledWith();
- expect(oneHandredGrouping.quantity).toEqual(200);
- });
- });
-
- describe('getGroupings()', () => {
- it('should return a row with the total filled quantity', () => {
- jest.spyOn(controller, 'getTotalQuantity');
-
- controller.prices = [
- {warehouseFk: 1, grouping: 10, quantity: 10},
- {warehouseFk: 1, grouping: 100, quantity: 100},
- {warehouseFk: 1, grouping: 1000, quantity: 1000},
- ];
-
- const rows = controller.getGroupings();
- const firstRow = rows[0];
-
- expect(rows.length).toEqual(1);
- expect(firstRow.quantity).toEqual(1110);
- });
-
- it('should return two filled rows with a quantity', () => {
- jest.spyOn(controller, 'getTotalQuantity');
-
- controller.prices = [
- {warehouseFk: 1, grouping: 10, quantity: 10},
- {warehouseFk: 2, grouping: 10, quantity: 10},
- {warehouseFk: 1, grouping: 100, quantity: 0},
- {warehouseFk: 1, grouping: 1000, quantity: 1000},
- ];
-
- const rows = controller.getGroupings();
- const firstRow = rows[0];
- const secondRow = rows[1];
-
- expect(rows.length).toEqual(2);
- expect(firstRow.quantity).toEqual(1010);
- expect(secondRow.quantity).toEqual(10);
- });
- });
-
- describe('submit()', () => {
- it('should throw an error if none of the rows contains a quantity', () => {
- jest.spyOn(controller, 'getTotalQuantity');
- jest.spyOn(controller.vnApp, 'showError');
-
- controller.prices = [
- {warehouseFk: 1, grouping: 10, quantity: 0},
- {warehouseFk: 1, grouping: 100, quantity: 0}
- ];
-
- controller.submit();
-
- expect(controller.vnApp.showError).toHaveBeenCalledWith(`First you must add some quantity`);
- });
-
- it(`should throw an error if the quantity doesn't match the grouping value`, () => {
- jest.spyOn(controller, 'getTotalQuantity');
- jest.spyOn(controller.vnApp, 'showError');
-
- controller.prices = [
- {warehouseFk: 1, grouping: 10, quantity: 0},
- {warehouseFk: 1, grouping: 100, quantity: 1101}
- ];
-
- controller.submit();
-
- expect(controller.vnApp.showError).toHaveBeenCalledWith(`The amounts doesn't match with the grouping`);
- });
-
- it('should should make an http query and then show a success message', () => {
- jest.spyOn(controller, 'getTotalQuantity');
- jest.spyOn(controller.vnApp, 'showSuccess');
-
- controller.prices = [
- {warehouseFk: 1, grouping: 10, quantity: 0},
- {warehouseFk: 1, grouping: 100, quantity: 100}
- ];
-
- const params = {
- orderFk: orderId,
- items: [{warehouseFk: 1, grouping: 100, quantity: 100}]
- };
-
- $httpBackend.expectPOST('OrderRows/addToOrder', params).respond(200);
- controller.submit();
- $httpBackend.flush();
-
- expect(controller.vnApp.showSuccess).toHaveBeenCalledWith(`Data saved!`);
- });
- });
- });
-});
diff --git a/modules/order/front/prices-popover/locale/es.yml b/modules/order/front/prices-popover/locale/es.yml
deleted file mode 100644
index 27eac802d..000000000
--- a/modules/order/front/prices-popover/locale/es.yml
+++ /dev/null
@@ -1,3 +0,0 @@
-Qty.: Cant.
-First you must add some quantity: Primero debes agregar alguna cantidad
-The amounts doesn't match with the grouping: Las cantidades no coinciden con el grouping
\ No newline at end of file
diff --git a/modules/order/front/prices-popover/style.scss b/modules/order/front/prices-popover/style.scss
deleted file mode 100644
index deaeab044..000000000
--- a/modules/order/front/prices-popover/style.scss
+++ /dev/null
@@ -1,18 +0,0 @@
-@import "variables";
-
-.vn-order-prices-popover .content {
- .prices {
- vn-table {
- .price-kg {
- color: $color-font-secondary;
- font-size: .75rem
- }
- .vn-input-number {
- width: 80px;
- }
- }
- .footer {
- text-align: center;
- }
- }
-}
\ No newline at end of file
diff --git a/modules/order/front/routes.json b/modules/order/front/routes.json
index 2eeb60553..25c68300f 100644
--- a/modules/order/front/routes.json
+++ b/modules/order/front/routes.json
@@ -28,19 +28,19 @@
"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",
@@ -49,48 +49,6 @@
"params": {
"order": "$ctrl.order"
}
- },
- {
- "url": "/catalog?q&categoryId&typeId&tagGroups",
- "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
deleted file mode 100644
index 001fc0bcb..000000000
--- a/modules/order/front/search-panel/index.html
+++ /dev/null
@@ -1,86 +0,0 @@
-
-
-
diff --git a/modules/order/front/search-panel/index.js b/modules/order/front/search-panel/index.js
deleted file mode 100644
index 07be9ca24..000000000
--- a/modules/order/front/search-panel/index.js
+++ /dev/null
@@ -1,7 +0,0 @@
-import ngModule from '../module';
-import SearchPanel from 'core/components/searchbar/search-panel';
-
-ngModule.vnComponent('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
deleted file mode 100644
index 9801e151f..000000000
--- a/modules/order/front/search-panel/locale/es.yml
+++ /dev/null
@@ -1,11 +0,0 @@
-Order id: Id cesta
-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
-Show empty: Mostrar vacías
-Search orders by ticket id: Buscar pedido por id ticket
\ No newline at end of file
diff --git a/modules/order/front/summary/index.html b/modules/order/front/summary/index.html
deleted file mode 100644
index 218359992..000000000
--- a/modules/order/front/summary/index.html
+++ /dev/null
@@ -1,131 +0,0 @@
-
-
-
-
-
-
- Basket #{{$ctrl.summary.id}} - {{$ctrl.summary.client.name}}
- ({{$ctrl.summary.client.id}})
-
-
-
-
-
-
-
-
-
-
- {{$ctrl.summary.address.nickname}}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 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}}
-
-
-
-
- {{::row.item.name}}
-
- {{::row.item.subName}}
-
-
-
-
-
- {{::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
deleted file mode 100644
index cc1df8f5d..000000000
--- a/modules/order/front/summary/index.js
+++ /dev/null
@@ -1,41 +0,0 @@
-import ngModule from '../module';
-import Summary from 'salix/components/summary';
-import './style.scss';
-
-class Controller extends Summary {
- setSummary() {
- this.$http.get(`Orders/${this.order.id}/summary`)
- .then(res => this.summary = res.data);
- }
-
- get formattedAddress() {
- if (!this.summary) return null;
-
- 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();
- }
-
- save() {
- this.$http.post(`Orders/${this.order.id}/confirm`).then(() => {
- this.vnApp.showSuccess(this.$t('Order confirmed'));
- this.$state.go(`ticket.index`, {
- q: JSON.stringify({clientFk: this.order.clientFk})
- });
- });
- }
-}
-
-ngModule.vnComponent('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
deleted file mode 100644
index 0c04593e1..000000000
--- a/modules/order/front/summary/index.spec.js
+++ /dev/null
@@ -1,47 +0,0 @@
-import './index';
-
-describe('Order', () => {
- describe('Component vnOrderSummary', () => {
- let controller;
- let $httpBackend;
-
- beforeEach(ngModule('order'));
-
- beforeEach(inject(($componentController, _$httpBackend_) => {
- $httpBackend = _$httpBackend_;
- const $element = angular.element(' ');
- controller = $componentController('vnOrderSummary', {$element});
- controller.order = {id: 1};
- }));
-
- describe('getSummary()', () => {
- it('should now perform a GET query and define the summary property', () => {
- let res = {
- id: 1,
- nickname: 'Batman'
- };
- $httpBackend.expectGET(`Orders/1/summary`).respond(res);
- controller.setSummary();
- $httpBackend.flush();
-
- expect(controller.summary).toEqual(res);
- });
- });
-
- 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
deleted file mode 100644
index a2537c58f..000000000
--- a/modules/order/front/summary/style.scss
+++ /dev/null
@@ -1,20 +0,0 @@
-@import "./variables";
-
-vn-order-summary .summary{
- max-width: $width-lg;
-
- & > vn-horizontal > vn-one {
- min-width: 160px;
-
- &.taxes {
- border: $border-thin-light;
- text-align: right;
- padding: 8px;
-
- & > p {
- font-size: 1.2rem;
- margin: 3px;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/modules/order/front/volume/index.html b/modules/order/front/volume/index.html
deleted file mode 100644
index e0053f9ed..000000000
--- a/modules/order/front/volume/index.html
+++ /dev/null
@@ -1,66 +0,0 @@
-
-
-
-
-
-
-
diff --git a/modules/order/front/volume/index.js b/modules/order/front/volume/index.js
deleted file mode 100644
index c1bc5ec7d..000000000
--- a/modules/order/front/volume/index.js
+++ /dev/null
@@ -1,37 +0,0 @@
-import ngModule from '../module';
-import Section from 'salix/components/section';
-import './style.scss';
-
-class Controller extends Section {
- constructor($element, $) {
- super($element, $);
- this.filter = {
- include: {
- relation: 'item'
- },
- order: 'itemFk'
- };
- this.order = {};
- this.ticketVolumes = [];
- }
-
- onDataChange() {
- this.$http.get(`Orders/${this.$params.id}/getVolumes`)
- .then(res => {
- this.$.model.data.forEach(order => {
- res.data.volumes.forEach(volume => {
- if (order.itemFk === volume.itemFk)
- order.volume = volume.volume;
- });
- });
- });
- }
-}
-
-ngModule.vnComponent('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
deleted file mode 100644
index 6d7b18865..000000000
--- a/modules/order/front/volume/index.spec.js
+++ /dev/null
@@ -1,42 +0,0 @@
-import './index';
-
-describe('Order', () => {
- describe('Component vnOrderVolume', () => {
- let controller;
- let $httpBackend;
- let $scope;
-
- beforeEach(ngModule('order'));
-
- beforeEach(inject(($componentController, $state, _$httpBackend_, $rootScope) => {
- $httpBackend = _$httpBackend_;
- $scope = $rootScope.$new();
- $scope.model = {
- data: [
- {itemFk: 1},
- {itemFk: 2}
- ]
- };
-
- $state.params.id = 1;
- const $element = angular.element(' ');
- controller = $componentController('vnOrderVolume', {$element, $scope});
- }));
-
- it('should join the sale volumes to its respective sale', () => {
- let response = {
- volumes: [
- {itemFk: 1, volume: 0.008},
- {itemFk: 2, volume: 0.003}
- ]
- };
-
- $httpBackend.expectGET(`Orders/1/getVolumes`).respond(response);
- controller.onDataChange();
- $httpBackend.flush();
-
- expect(controller.$.model.data[0].volume).toBe(0.008);
- expect(controller.$.model.data[1].volume).toBe(0.003);
- });
- });
-});
diff --git a/modules/order/front/volume/style.scss b/modules/order/front/volume/style.scss
deleted file mode 100644
index da13eca0d..000000000
--- a/modules/order/front/volume/style.scss
+++ /dev/null
@@ -1,12 +0,0 @@
-
-@import "./variables";
-
-vn-order-volume {
- .header {
- text-align: right;
-
- & > div {
- margin-bottom: $spacing-xs;
- }
- }
-}
diff --git a/modules/route/back/methods/agency-term/filter.js b/modules/route/back/methods/agency-term/filter.js
index 9d1268958..d52d93e95 100644
--- a/modules/route/back/methods/agency-term/filter.js
+++ b/modules/route/back/methods/agency-term/filter.js
@@ -66,9 +66,9 @@ module.exports = Self => {
case 'agencyFk':
return {'agencyFk': value};
case 'from':
- return {'created': {gte: value}};
+ return {'dated': {gte: value}};
case 'to':
- return {'created': {lte: value}};
+ return {'dated': {lte: value}};
}
});
@@ -81,7 +81,7 @@ module.exports = Self => {
`SELECT *
FROM (
SELECT r.id routeFk,
- r.created,
+ r.dated,
r.agencyModeFk,
am.name agencyModeName,
am.agencyFk,
@@ -103,7 +103,7 @@ module.exports = Self => {
LEFT JOIN vn.ticket t ON t.routeFk = r.id
LEFT JOIN vn.supplierAgencyTerm sat ON sat.agencyFk = a.id
LEFT JOIN vn.supplier s ON s.id = sat.supplierFk
- WHERE r.created > DATE_ADD(?, INTERVAL -2 MONTH) AND sat.supplierFk IS NOT NULL
+ WHERE r.dated > DATE_ADD(?, INTERVAL -2 MONTH) AND sat.supplierFk IS NOT NULL
GROUP BY r.id
) a`
, [date]);
diff --git a/modules/route/back/methods/route/downloadCmrsZip.js b/modules/route/back/methods/cmr/downloadZip.js
similarity index 87%
rename from modules/route/back/methods/route/downloadCmrsZip.js
rename to modules/route/back/methods/cmr/downloadZip.js
index 895ff7a16..fcf4ce61c 100644
--- a/modules/route/back/methods/route/downloadCmrsZip.js
+++ b/modules/route/back/methods/cmr/downloadZip.js
@@ -1,7 +1,7 @@
const JSZip = require('jszip');
module.exports = Self => {
- Self.remoteMethodCtx('downloadCmrsZip', {
+ Self.remoteMethodCtx('downloadZip', {
description: 'Download a zip file with multiple cmrs pdfs',
accessType: 'READ',
accepts: [
@@ -27,13 +27,13 @@ module.exports = Self => {
}
],
http: {
- path: '/downloadCmrsZip',
+ path: '/downloadZip',
verb: 'GET'
},
accessScopes: ['DEFAULT', 'read:multimedia']
});
- Self.downloadCmrsZip = async function(ctx, ids, options) {
+ Self.downloadZip = async function(ctx, ids, options) {
const models = Self.app.models;
const myOptions = {};
const zip = new JSZip();
@@ -44,7 +44,7 @@ module.exports = Self => {
const downloadAddZip = async id => {
ctx.args = ctx.args || {};
ctx.args.id = Number(id);
- const [data] = await models.Route.cmr(ctx, myOptions);
+ const [data] = await models.Cmr.print(ctx, myOptions);
zip.file(`${id}.pdf`, data, {binary: true});
};
diff --git a/modules/route/back/methods/route/cmrs.js b/modules/route/back/methods/cmr/filter.js
similarity index 98%
rename from modules/route/back/methods/route/cmrs.js
rename to modules/route/back/methods/cmr/filter.js
index 6f271a4cf..d5a217b1c 100644
--- a/modules/route/back/methods/route/cmrs.js
+++ b/modules/route/back/methods/cmr/filter.js
@@ -3,7 +3,7 @@ const buildFilter = require('vn-loopback/util/filter').buildFilter;
const mergeFilters = require('vn-loopback/util/filter').mergeFilters;
module.exports = Self => {
- Self.remoteMethod('cmrs', {
+ Self.remoteMethod('filter', {
description: 'Returns an array of cmrs',
accessType: 'READ',
accepts: [
@@ -57,12 +57,12 @@ module.exports = Self => {
root: true
},
http: {
- path: `/cmrs`,
+ path: `/filter`,
verb: 'GET'
}
});
- Self.cmrs = async(
+ Self.filter = async(
filter, cmrFk, ticketFk, routeFk, country, clientFk, hasCmrDms, shipped, warehouseFk, options
) => {
const params = {cmrFk, ticketFk, routeFk, country, clientFk, hasCmrDms, warehouseFk, shipped};
diff --git a/modules/route/back/methods/route/cmr.js b/modules/route/back/methods/cmr/print.js
similarity index 82%
rename from modules/route/back/methods/route/cmr.js
rename to modules/route/back/methods/cmr/print.js
index 5033dee2f..2fe807829 100644
--- a/modules/route/back/methods/route/cmr.js
+++ b/modules/route/back/methods/cmr/print.js
@@ -1,6 +1,6 @@
module.exports = Self => {
- Self.remoteMethodCtx('cmr', {
- description: 'Returns the cmr',
+ Self.remoteMethodCtx('print', {
+ description: 'Returns the cmr pdf',
accessType: 'READ',
accepts: [
{
@@ -27,11 +27,11 @@ module.exports = Self => {
}
],
http: {
- path: '/:id/cmr',
+ path: '/:id/print',
verb: 'GET'
},
accessScopes: ['DEFAULT', 'read:multimedia']
});
- Self.cmr = (ctx, id) => Self.printReport(ctx, id, 'cmr');
+ Self.print = (ctx, id) => Self.printReport(ctx, id, 'cmr');
};
diff --git a/modules/route/back/methods/route/specs/downloadCmrsZip.spec.js b/modules/route/back/methods/cmr/specs/downloadZip.spec.js
similarity index 83%
rename from modules/route/back/methods/route/specs/downloadCmrsZip.spec.js
rename to modules/route/back/methods/cmr/specs/downloadZip.spec.js
index 7312a5d44..74870038f 100644
--- a/modules/route/back/methods/route/specs/downloadCmrsZip.spec.js
+++ b/modules/route/back/methods/cmr/specs/downloadZip.spec.js
@@ -1,6 +1,6 @@
const models = require('vn-loopback/server/server').models;
-describe('route downloadCmrsZip()', () => {
+describe('route downloadZip()', () => {
it('should create a zip file with the given cmr ids', async() => {
const tx = await models.Route.beginTransaction({});
const ctx = {
@@ -13,7 +13,7 @@ describe('route downloadCmrsZip()', () => {
};
let cmrs = '1,2';
try {
- const stream = await models.Route.downloadCmrsZip(ctx, cmrs);
+ const stream = await models.Cmr.downloadZip(ctx, cmrs);
expect(stream[0]).toBeDefined();
await tx.rollback();
diff --git a/modules/route/back/methods/route/clone.js b/modules/route/back/methods/route/clone.js
index d56118e08..c5c4d846a 100644
--- a/modules/route/back/methods/route/clone.js
+++ b/modules/route/back/methods/route/clone.js
@@ -10,10 +10,10 @@ module.exports = Self => {
description: 'The routes ids to clone'
},
{
- arg: 'created',
+ arg: 'dated',
type: 'date',
required: true,
- description: 'The created date for all routes'
+ description: 'The date for all routes'
}
],
returns: {
@@ -26,7 +26,7 @@ module.exports = Self => {
}
});
- Self.clone = async(ids, created) => {
+ Self.clone = async(ids, dated) => {
const tx = await Self.beginTransaction({});
try {
const options = {transaction: tx};
@@ -39,7 +39,7 @@ module.exports = Self => {
throw new Error(`The amount of routes found don't match`);
const routes = originalRoutes.map(route => {
- route.created = created;
+ route.dated = dated;
return route;
});
diff --git a/modules/route/back/methods/route/driverRouteEmail.js b/modules/route/back/methods/route/driverRouteEmail.js
index 62147db87..bbac2b0e8 100644
--- a/modules/route/back/methods/route/driverRouteEmail.js
+++ b/modules/route/back/methods/route/driverRouteEmail.js
@@ -39,8 +39,6 @@ module.exports = Self => {
const {reportMail} = agencyMode();
let user;
let account;
- let userEmail;
- ctx.args.recipients = reportMail ? reportMail.split(',').map(email => email.trim()) : [];
if (workerFk) {
user = await models.VnUser.findById(workerFk, {
@@ -50,17 +48,10 @@ module.exports = Self => {
account = await models.Account.findById(workerFk);
}
- if (user?.active && account)
- userEmail = user.emailUser().email;
-
- if (userEmail)
- ctx.args.recipients.push(userEmail);
-
- ctx.args.recipients = [...new Set(ctx.args.recipients)];
-
- if (!ctx.args.recipients.length)
- throw new UserError('An email is necessary');
+ if (user?.active && account) ctx.args.recipient = user.emailUser().email;
+ else ctx.args.recipient = reportMail;
+ if (!ctx.args.recipient) throw new UserError('An email is necessary');
return Self.sendTemplate(ctx, 'driver-route');
};
};
diff --git a/modules/route/back/methods/route/filter.js b/modules/route/back/methods/route/filter.js
index 925927cc8..70bf7ba67 100644
--- a/modules/route/back/methods/route/filter.js
+++ b/modules/route/back/methods/route/filter.js
@@ -93,9 +93,9 @@ module.exports = Self => {
case 'search':
return {'id': value};
case 'from':
- return {'created': {gte: value}};
+ return {'dated': {gte: value}};
case 'to':
- return {'created': {lte: value}};
+ return {'dated': {lte: value}};
case 'description':
return {'description': {like: `%${value}%`}};
case 'isOk':
@@ -119,7 +119,7 @@ module.exports = Self => {
SELECT
r.id,
r.workerFk,
- r.created,
+ r.dated,
r.vehicleFk,
r.agencyModeFk,
r.time,
diff --git a/modules/route/back/methods/route/getByWorker.js b/modules/route/back/methods/route/getByWorker.js
index 5d1881c20..92086bba0 100644
--- a/modules/route/back/methods/route/getByWorker.js
+++ b/modules/route/back/methods/route/getByWorker.js
@@ -46,14 +46,14 @@ module.exports = Self => {
and: [
{
or: [
- {'created': currentDate},
- {'created': nextDay}
+ {'dated': currentDate},
+ {'dated': nextDay}
]
}
]
},
order: [
- 'created ASC',
+ 'dated ASC',
'time ASC',
'agencyName ASC'
]
diff --git a/modules/route/back/methods/route/getSuggestedTickets.js b/modules/route/back/methods/route/getSuggestedTickets.js
index e1b90d359..daaff2bc8 100644
--- a/modules/route/back/methods/route/getSuggestedTickets.js
+++ b/modules/route/back/methods/route/getSuggestedTickets.js
@@ -43,10 +43,10 @@ module.exports = Self => {
for (let zoneAgencyMode of zoneAgencyModes)
zoneIds.push(zoneAgencyMode.zoneFk);
- const minDate = new Date(route.created);
+ const minDate = new Date(route.dated);
minDate.setHours(0, 0, 0, 0);
- const maxDate = new Date(route.created);
+ const maxDate = new Date(route.dated);
maxDate.setHours(23, 59, 59, 59);
let tickets = await Self.app.models.Ticket.find({
diff --git a/modules/route/back/methods/route/insertTicket.js b/modules/route/back/methods/route/insertTicket.js
index 4ac8bad1a..41c910116 100644
--- a/modules/route/back/methods/route/insertTicket.js
+++ b/modules/route/back/methods/route/insertTicket.js
@@ -42,10 +42,10 @@ module.exports = Self => {
try {
const route = await models.Route.findById(routeId, null, myOptions);
- const minDate = new Date(route.created);
+ const minDate = new Date(route.dated);
minDate.setHours(0, 0, 0, 0);
- const maxDate = new Date(route.created);
+ const maxDate = new Date(route.dated);
maxDate.setHours(23, 59, 59, 59);
const ticket = await models.Ticket.findOne({
where: {
diff --git a/modules/route/back/methods/route/optimizePriority.js b/modules/route/back/methods/route/optimizePriority.js
new file mode 100644
index 000000000..56db4ffb5
--- /dev/null
+++ b/modules/route/back/methods/route/optimizePriority.js
@@ -0,0 +1,122 @@
+const UserError = require('vn-loopback/util/user-error');
+
+module.exports = Self => {
+ Self.remoteMethod('optimizePriority', {
+ description: 'Updates the ticket priority of tickets without priority',
+ accepts: {
+ arg: 'id',
+ type: 'number',
+ required: true,
+ description: 'Route id',
+ http: {source: 'path'}
+ },
+ returns: {
+ type: 'object',
+ root: true
+ },
+ http: {
+ path: '/:id/optimizePriority',
+ verb: 'POST'
+ }
+ });
+
+ Self.optimizePriority = async(id, options) => {
+ const models = Self.app.models;
+ const myOptions = {};
+ let tx;
+
+ if (typeof options == 'object')
+ Object.assign(myOptions, options);
+
+ const tickets = await models.Ticket.find({
+ where: {routeFk: id}
+ }, myOptions);
+
+ let ticketAddress = [];
+ for (const ticket of tickets) {
+ ticketAddress.push({
+ ticketId: ticket.id,
+ addressId: ticket.addressFk,
+ zoneId: ticket.zoneFk,
+ priority: ticket.priority
+ });
+ }
+
+ // Igualamos los priority del mismo addressId
+ const addressPriorityMap = ticketAddress.reduce((acc, {addressId, priority}) => {
+ if (priority !== null) {
+ acc[addressId] = acc[addressId] === undefined
+ ? priority
+ : Math.max(acc[addressId], priority);
+ }
+ return acc;
+ });
+ ticketAddress.forEach(item => {
+ const maxPriority = addressPriorityMap[item.addressId];
+ if (maxPriority) item.priority = maxPriority;
+ });
+
+ // Añadimos las direcciones a optimizar
+ let addressIds = [];
+ ticketAddress.forEach(h => {
+ if (!addressIds.includes(h.addressId) && !h.priority)
+ addressIds.push(h.addressId);
+ });
+ if (!addressIds.length) throw new UserError('All tickets have a route order');
+
+ // Obtenemos el zoneId más frecuente
+ const zoneFrequency = ticketAddress.reduce((acc, {zoneId}) => {
+ if (zoneId != null) acc[zoneId] = (acc[zoneId] || 0) + 1;
+ return acc;
+ }, {});
+ const [mostFrequentZoneId] = Object.entries(zoneFrequency)
+ .reduce((maxEntry, entry) => entry[1] > maxEntry[1] ? entry : maxEntry, [null, 0]);
+
+ // Obtenemos los address inicio y fin
+ const maxPosition = Math.max(...ticketAddress.map(g => g.priority));
+ let firstAddress = (await models.Zone.findById(mostFrequentZoneId, myOptions))?.addressFk
+ || (await models.ZoneConfig.findOne())?.defaultAddressFk;
+ const lastAddress = firstAddress;
+ if (maxPosition) firstAddress = ticketAddress.find(g => g.priority === maxPosition)?.addressId;
+
+ // Revisamos las coincidencias y actualizamos la prioridad en el array
+ const addressPositions = await models.OsrmConfig.optimize(addressIds, firstAddress, lastAddress, myOptions);
+ await Promise.all(ticketAddress.map(async i => {
+ const foundPosition = addressPositions.find(item => item.addressId === i.addressId);
+ if (foundPosition) i.priority = foundPosition.position + (maxPosition + 1);
+ }));
+
+ // Suavizado de prioridad para que no hayan escalones
+ const allPriorities = ticketAddress
+ .map(item => item.priority)
+ .filter(p => p !== null);
+ const uniquePriorities = [...new Set(allPriorities)].sort((a, b) => a - b);
+ const priorityMap = {};
+ uniquePriorities.forEach((p, index) => {
+ priorityMap[p] = index + 1;
+ });
+ ticketAddress.forEach(item => {
+ if (item.priority !== null) item.priority = priorityMap[item.priority];
+ });
+
+ if (!myOptions.transaction) {
+ tx = await Self.beginTransaction({});
+ myOptions.transaction = tx;
+ }
+
+ // Realizamos el update en la base de datos
+ try {
+ await Promise.all(ticketAddress.map(async y => {
+ if (y.priority) {
+ const ticket = await models.Ticket.findById(y.ticketId);
+ await ticket.updateAttribute('priority', y.priority, myOptions);
+ }
+ }));
+ if (tx) await tx.commit();
+ return;
+ } catch (err) {
+ if (tx) await tx.rollback();
+ throw err;
+ }
+ };
+};
diff --git a/modules/route/back/methods/route/specs/optimizePriority.spec.js b/modules/route/back/methods/route/specs/optimizePriority.spec.js
new file mode 100644
index 000000000..c1c2dc45e
--- /dev/null
+++ b/modules/route/back/methods/route/specs/optimizePriority.spec.js
@@ -0,0 +1,36 @@
+const models = require('vn-loopback/server/server').models;
+const routeId = 1;
+
+describe('route optimizePriority())', function() {
+ it('should execute without throwing errors', async function() {
+ const tx = await models.Route.beginTransaction({});
+ let error;
+ try {
+ const options = {transaction: tx};
+ await models.Ticket.updateAll(
+ {routeFk: routeId},
+ {priority: null},
+ options
+ );
+ await models.Route.optimizePriority(routeId, options);
+ await tx.rollback();
+ } catch (e) {
+ error = e;
+ await tx.rollback();
+ }
+
+ expect(error).toBeUndefined();
+ });
+
+ it('should execute with error', async function() {
+ let error;
+ try {
+ await models.Route.optimizePriority(routeId);
+ } catch (e) {
+ error = e;
+ }
+
+ expect(error).toBeDefined();
+ expect(error.message).toBe('All tickets have a route order');
+ });
+});
diff --git a/modules/route/back/model-config.json b/modules/route/back/model-config.json
index ccae87bd9..fb1c5d7fd 100644
--- a/modules/route/back/model-config.json
+++ b/modules/route/back/model-config.json
@@ -5,6 +5,9 @@
"AgencyTermConfig": {
"dataSource": "vn"
},
+ "Cmr": {
+ "dataSource": "vn"
+ },
"DeliveryPoint": {
"dataSource": "vn"
},
@@ -20,6 +23,12 @@
"Route": {
"dataSource": "vn"
},
+ "RouteAction": {
+ "dataSource": "vn"
+ },
+ "RouteComplement": {
+ "dataSource": "vn"
+ },
"RouteLog": {
"dataSource": "vn"
},
@@ -29,4 +38,4 @@
"RoutesMonitor": {
"dataSource": "vn"
}
-}
+}
\ No newline at end of file
diff --git a/modules/route/back/models/cmr.js b/modules/route/back/models/cmr.js
new file mode 100644
index 000000000..f9a153d52
--- /dev/null
+++ b/modules/route/back/models/cmr.js
@@ -0,0 +1,5 @@
+module.exports = Self => {
+ require('../methods/cmr/print')(Self);
+ require('../methods/cmr/filter')(Self);
+ require('../methods/cmr/downloadZip')(Self);
+};
diff --git a/modules/route/back/models/route.js b/modules/route/back/models/route.js
index 242623d6e..f73ff3e51 100644
--- a/modules/route/back/models/route.js
+++ b/modules/route/back/models/route.js
@@ -14,10 +14,7 @@ module.exports = Self => {
require('../methods/route/driverRouteEmail')(Self);
require('../methods/route/sendSms')(Self);
require('../methods/route/downloadZip')(Self);
- require('../methods/route/cmr')(Self);
- require('../methods/route/cmrs')(Self);
- require('../methods/route/downloadCmrsZip')(Self);
- require('../methods/route/cmrEmail')(Self);
require('../methods/route/getExpeditionSummary')(Self);
require('../methods/route/getByWorker')(Self);
+ require('../methods/route/optimizePriority')(Self);
};
diff --git a/modules/route/back/models/route.json b/modules/route/back/models/route.json
index f8be9023c..8f4eab761 100644
--- a/modules/route/back/models/route.json
+++ b/modules/route/back/models/route.json
@@ -15,7 +15,7 @@
"id": true,
"description": "Identifier"
},
- "created": {
+ "dated": {
"type": "date"
},
"time": {
diff --git a/modules/route/back/models/routeAction.json b/modules/route/back/models/routeAction.json
new file mode 100644
index 000000000..88f7a8226
--- /dev/null
+++ b/modules/route/back/models/routeAction.json
@@ -0,0 +1,30 @@
+{
+ "name": "RouteAction",
+ "base": "VnModel",
+ "mixins": {
+ "Loggable": true
+ },
+ "options": {
+ "mysql": {
+ "table": "routeAction"
+ }
+ },
+ "properties": {
+ "id": {
+ "type": "number",
+ "id": true,
+ "description": "Identifier"
+ },
+ "name": {
+ "type": "string",
+ "required": true
+ },
+ "price": {
+ "type": "number"
+ },
+ "isMainlineDelivered": {
+ "type": "boolean",
+ "required": true
+ }
+ }
+}
\ No newline at end of file
diff --git a/modules/route/back/models/routeComplement.json b/modules/route/back/models/routeComplement.json
new file mode 100644
index 000000000..e2086f78d
--- /dev/null
+++ b/modules/route/back/models/routeComplement.json
@@ -0,0 +1,37 @@
+{
+ "name": "RouteComplement",
+ "base": "VnModel",
+ "mixins": {
+ "Loggable": true
+ },
+ "options": {
+ "mysql": {
+ "table": "routeComplement"
+ }
+ },
+ "properties": {
+ "id": {
+ "type": "number",
+ "id": true,
+ "description": "Identifier"
+ },
+ "dated": {
+ "type": "date"
+ },
+ "price": {
+ "type": "number"
+ }
+ },
+ "relations": {
+ "worker": {
+ "type": "belongsTo",
+ "model": "Worker",
+ "foreignKey": "workerFk"
+ },
+ "routeAction": {
+ "type": "belongsTo",
+ "model": "RouteAction",
+ "foreignKey": "routeActionFk"
+ }
+ }
+}
\ No newline at end of file
diff --git a/modules/route/front/descriptor/index.html b/modules/route/front/descriptor/index.html
index 4e7e99f1a..0079168a6 100644
--- a/modules/route/front/descriptor/index.html
+++ b/modules/route/front/descriptor/index.html
@@ -32,7 +32,7 @@
+ value="{{$ctrl.route.dated | date: 'dd/MM/yyyy'}}">
+ value="{{$ctrl.summary.route.dated | date: 'dd/MM/yyyy'}}">
diff --git a/modules/shelving/back/models/parking.json b/modules/shelving/back/models/parking.json
index 47a3305ae..a9393fc6a 100644
--- a/modules/shelving/back/models/parking.json
+++ b/modules/shelving/back/models/parking.json
@@ -38,5 +38,13 @@
"model": "Sector",
"foreignKey": "sectorFk"
}
+ },
+ "scope": {
+ "include": {
+ "relation": "sector",
+ "scope": {
+ "fields": ["id", "description"]
+ }
+ }
}
}
diff --git a/modules/shelving/back/models/sector.json b/modules/shelving/back/models/sector.json
index 61d8d0628..16aa0ba6a 100644
--- a/modules/shelving/back/models/sector.json
+++ b/modules/shelving/back/models/sector.json
@@ -59,6 +59,9 @@
"isReserve": {
"type": "boolean",
"required": true
+ },
+ "isOnReservationMode": {
+ "type": "boolean"
}
}
-}
+}
\ No newline at end of file
diff --git a/modules/shelving/back/models/shelving.json b/modules/shelving/back/models/shelving.json
index 46fce31e8..84e260b9e 100644
--- a/modules/shelving/back/models/shelving.json
+++ b/modules/shelving/back/models/shelving.json
@@ -1,6 +1,6 @@
{
"name": "Shelving",
- "base": "VnModel",
+ "base": "VnModel",
"mixins": {
"Loggable": true
},
@@ -44,6 +44,11 @@
"type": "belongsTo",
"model": "Worker",
"foreignKey": "id"
+ },
+ "itemShelving": {
+ "type": "hasMany",
+ "model": "ItemShelving",
+ "foreignKey": "shelvingFk"
}
}
-}
+}
\ No newline at end of file
diff --git a/modules/supplier/back/methods/supplier/getSummary.js b/modules/supplier/back/methods/supplier/getSummary.js
index 67767e7b4..8fcaaa53f 100644
--- a/modules/supplier/back/methods/supplier/getSummary.js
+++ b/modules/supplier/back/methods/supplier/getSummary.js
@@ -43,7 +43,8 @@ module.exports = Self => {
'sageWithholdingFk',
'workerFk',
'supplierActivityFk',
- 'healthRegister'
+ 'healthRegister',
+ 'companySize'
],
include: [
{
diff --git a/modules/supplier/back/methods/supplier/getWithPackaging.js b/modules/supplier/back/methods/supplier/getWithPackaging.js
new file mode 100644
index 000000000..41b080964
--- /dev/null
+++ b/modules/supplier/back/methods/supplier/getWithPackaging.js
@@ -0,0 +1,45 @@
+module.exports = Self => {
+ Self.remoteMethod('getWithPackaging', {
+ description: 'Returns the list of suppliers with an entry of type packaging',
+ accessType: 'READ',
+ returns: {
+ type: 'object',
+ root: true
+ },
+ http: {
+ path: `/getWithPackaging`,
+ verb: 'GET'
+ },
+ nolimit: true
+ });
+ Self.getWithPackaging = async options => {
+ const models = Self.app.models;
+ const myOptions = {};
+ const oneYearAgo = Date.vnNew();
+ oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
+
+ if (typeof options == 'object')
+ Object.assign(myOptions, options);
+
+ const entries = await models.Entry.find({
+ where: {
+ typeFk: 'packaging',
+ created: {gte: oneYearAgo}
+ },
+ include: {
+ relation: 'supplier',
+ scope: {
+ fields: ['id', 'name']
+ }
+ },
+ fields: {supplierFk: true}
+ }, myOptions);
+
+ const result = entries.map(item => ({
+ id: item.supplier().id,
+ name: item.supplier().name
+ }));
+ return Array.from(new Map(result.map(entry => [entry.id, entry])).values());
+ };
+};
+
diff --git a/modules/supplier/back/methods/supplier/specs/getWithPackaging.spec.js b/modules/supplier/back/methods/supplier/specs/getWithPackaging.spec.js
new file mode 100644
index 000000000..b6a780a10
--- /dev/null
+++ b/modules/supplier/back/methods/supplier/specs/getWithPackaging.spec.js
@@ -0,0 +1,19 @@
+const {models} = require('vn-loopback/server/server');
+
+describe('Supplier getWithPackaging()', () => {
+ beforeAll.mockLoopBackContext();
+ it('should return a list of suppliers with an entry of type packaging', async() => {
+ const tx = await models.Supplier.beginTransaction({});
+ const myOptions = {transaction: tx};
+
+ try {
+ const result = await models.Supplier.getWithPackaging(myOptions);
+
+ expect(result.length).toEqual(1);
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
+});
diff --git a/modules/supplier/back/models/supplier.js b/modules/supplier/back/models/supplier.js
index 2d3ffef3e..7e6908d57 100644
--- a/modules/supplier/back/models/supplier.js
+++ b/modules/supplier/back/models/supplier.js
@@ -12,6 +12,7 @@ module.exports = Self => {
require('../methods/supplier/campaignMetricsEmail')(Self);
require('../methods/supplier/newSupplier')(Self);
require('../methods/supplier/getItemsPackaging')(Self);
+ require('../methods/supplier/getWithPackaging')(Self);
Self.validatesPresenceOf('name', {
message: 'The social name cannot be empty'
diff --git a/modules/supplier/back/models/supplier.json b/modules/supplier/back/models/supplier.json
index 90b266ba9..b79a6b80d 100644
--- a/modules/supplier/back/models/supplier.json
+++ b/modules/supplier/back/models/supplier.json
@@ -113,6 +113,9 @@
},
"isVies": {
"type": "boolean"
+ },
+ "companySize": {
+ "type": "string"
}
},
"relations": {
diff --git a/modules/ticket/back/methods/expedition-state/addExpeditionState.js b/modules/ticket/back/methods/expedition-state/addExpeditionState.js
index 80d74ee92..0ba402ff7 100644
--- a/modules/ticket/back/methods/expedition-state/addExpeditionState.js
+++ b/modules/ticket/back/methods/expedition-state/addExpeditionState.js
@@ -44,6 +44,7 @@ module.exports = Self => {
const typeFk = expeditionStateType.id;
expeditionId = expedition.expeditionFk;
+ expeditionPosition = expedition?.scanOrder ?? null;
const isScannedExpedition = expedition.isScanned ?? false;
await models.ExpeditionState.create({
@@ -51,6 +52,7 @@ module.exports = Self => {
typeFk,
userFk: userId,
isScanned: isScannedExpedition,
+ scanOrder: expeditionPosition
}, myOptions);
}
diff --git a/modules/ticket/back/methods/expedition-state/filter.js b/modules/ticket/back/methods/expedition-state/filter.js
index 1483780f7..3a4e7a87c 100644
--- a/modules/ticket/back/methods/expedition-state/filter.js
+++ b/modules/ticket/back/methods/expedition-state/filter.js
@@ -29,7 +29,7 @@ module.exports = Self => {
Object.assign(myOptions, options);
const stmt = new ParameterizedSQL(
- `SELECT es.created, u.name, u.id workerFk, est.description state
+ `SELECT es.created, u.name, u.id workerFk, est.description state, es.isScanned
FROM vn.expeditionState es
JOIN vn.expeditionStateType est ON est.id = es.typeFk
JOIN account.user u ON u.id = es.userFk
diff --git a/modules/ticket/back/methods/expedition-state/specs/addExpeditionState.spec.js b/modules/ticket/back/methods/expedition-state/specs/addExpeditionState.spec.js
index 747352286..71bc453de 100644
--- a/modules/ticket/back/methods/expedition-state/specs/addExpeditionState.spec.js
+++ b/modules/ticket/back/methods/expedition-state/specs/addExpeditionState.spec.js
@@ -2,6 +2,7 @@ const models = require('vn-loopback/server/server').models;
describe('expeditionState addExpeditionState()', () => {
const ctx = beforeAll.getCtx();
+ beforeAll.mockLoopBackContext();
it('should update the expedition states', async() => {
const tx = await models.ExpeditionState.beginTransaction({});
try {
diff --git a/modules/ticket/back/methods/expedition/deleteExpeditions.js b/modules/ticket/back/methods/expedition/deleteExpeditions.js
index 75993a485..267811d25 100644
--- a/modules/ticket/back/methods/expedition/deleteExpeditions.js
+++ b/modules/ticket/back/methods/expedition/deleteExpeditions.js
@@ -52,7 +52,8 @@ module.exports = Self => {
const deletedExpedition = await models.Expedition.destroyById(expeditionId);
deletedExpeditions.push(deletedExpedition);
- } catch (e) {
+ } catch (error) {
+ console.error('error: ', error);
notDeletedExpeditions.push(expeditionId);
}
}
diff --git a/modules/ticket/back/methods/expedition/filter.js b/modules/ticket/back/methods/expedition/filter.js
index 43be14349..801d00a9b 100644
--- a/modules/ticket/back/methods/expedition/filter.js
+++ b/modules/ticket/back/methods/expedition/filter.js
@@ -49,7 +49,9 @@ module.exports = Self => {
es.workerFk expeditionScanWorkerFk,
su.name scannerUserName,
es.scanned,
- est.description state
+ est.description state,
+ de.longName,
+ de.itemFk
FROM vn.expedition e
LEFT JOIN vn.expeditionStateType est ON est.id = e.stateTypeFk
INNER JOIN vn.item i1 ON i1.id = e.freightItemFk
@@ -59,6 +61,7 @@ module.exports = Self => {
LEFT JOIN account.user u ON u.id = e.workerFk
LEFT JOIN vn.expeditionScan es ON es.expeditionFk = e.id
LEFT JOIN account.user su ON su.id = es.workerFk
+ LEFT JOIN dipole.expedition_PrintOut de ON de.expeditionFk = e.id
) e
`);
stmt.merge(conn.makeWhere(filter.where));
diff --git a/modules/ticket/back/methods/expedition/moveExpeditions.js b/modules/ticket/back/methods/expedition/moveExpeditions.js
index cef35ab86..3ad41897f 100644
--- a/modules/ticket/back/methods/expedition/moveExpeditions.js
+++ b/modules/ticket/back/methods/expedition/moveExpeditions.js
@@ -13,7 +13,8 @@ module.exports = Self => {
{
arg: 'landed',
type: 'date',
- description: `The landing date`
+ description: `The landing date`,
+ required: true
},
{
arg: 'warehouseId',
@@ -79,11 +80,17 @@ module.exports = Self => {
const expeditionUpdated = expeditionToUpdate.updateAttribute('ticketFk', ticket.id, myOptions);
promises.push(expeditionUpdated);
}
-
await Promise.all(promises);
+ await models.Ticket.updateAll({id: ticket.id}, {packages: promises.length}, myOptions);
+ const state = await models.State.findOne({where: {code: 'PACKED'}});
+
+ await models.Ticket.state(ctx, {
+ ticketFk: ticket.id,
+ stateFk: state.id,
+ userFk: ctx.req.accessToken.userId
+ }, myOptions);
if (tx) await tx.commit();
-
return ticket;
} catch (e) {
if (tx) await tx.rollback();
diff --git a/modules/ticket/back/methods/expedition/specs/moveExpeditions.spec.js b/modules/ticket/back/methods/expedition/specs/moveExpeditions.spec.js
index c1c7c2c12..0edae9c6a 100644
--- a/modules/ticket/back/methods/expedition/specs/moveExpeditions.spec.js
+++ b/modules/ticket/back/methods/expedition/specs/moveExpeditions.spec.js
@@ -17,14 +17,55 @@ describe('ticket moveExpeditions()', () => {
agencyModeId: 1,
routeId: null,
expeditionIds: [1, 2]
-
};
-
+ const newestTicketIdInFixtures = await models.Ticket.findOne({
+ order: 'id DESC'
+ }, options);
const ticket = await models.Expedition.moveExpeditions(ctx, options);
- const newestTicketIdInFixtures = 27;
+ expect(ticket.id).toBeGreaterThan(newestTicketIdInFixtures.id);
- expect(ticket.id).toBeGreaterThan(newestTicketIdInFixtures);
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
+
+ it('should move expeditions to a new ticket, set state to PACKED, and update packages count correctly', async() => {
+ const tx = await models.Expedition.beginTransaction({});
+ const myCtx = ctx;
+
+ try {
+ const options = {transaction: tx};
+ myCtx.args = {
+ clientId: 1101,
+ landed: Date.vnNew(),
+ warehouseId: 1,
+ addressId: 121,
+ agencyModeId: 1,
+ routeId: null,
+ expeditionIds: [1, 2]
+ };
+
+ const newestTicketIdInFixtures = await models.Ticket.findOne({
+ order: 'id DESC'
+ }, options);
+ const ticket = await models.Expedition.moveExpeditions(myCtx, options);
+
+ expect(ticket.id).toBeGreaterThan(newestTicketIdInFixtures.id);
+
+ const updatedTicket = await models.Ticket.findById(ticket.id, null, options);
+ const packedState = await models.State.findOne({where: {code: 'PACKED'}}, options);
+
+ const state = await models.TicketState.findOne({where: {ticketFk: ticket.id}}, options);
+
+ expect(state.stateFk).toBe(packedState.id);
+ expect(state.userFk).toBe(myCtx.req.accessToken.userId);
+
+ const expectedPackagesCount = myCtx.args.expeditionIds.length;
+
+ expect(updatedTicket.$packages).toBe(expectedPackagesCount);
await tx.rollback();
} catch (e) {
@@ -33,4 +74,3 @@ describe('ticket moveExpeditions()', () => {
}
});
});
-
diff --git a/modules/ticket/back/methods/sale/clone.js b/modules/ticket/back/methods/sale/clone.js
index 24346f3ba..0b658a69e 100644
--- a/modules/ticket/back/methods/sale/clone.js
+++ b/modules/ticket/back/methods/sale/clone.js
@@ -142,12 +142,19 @@ module.exports = Self => {
ctx.args.addressId = ticket.addressFk;
const newTicket = await models.Ticket.new(ctx, myOptions);
-
- await models.TicketRefund.create({
- originalTicketFk: ticketId,
- refundTicketFk: newTicket.id
- }, myOptions);
-
+ const existingRefund = await models.TicketRefund.findOne({
+ where: {
+ originalTicketFk: ticketId,
+ refundTicketFk: newTicket.id
+ },
+ myOptions
+ });
+ if (!existingRefund) {
+ await models.TicketRefund.create({
+ originalTicketFk: ticketId,
+ refundTicketFk: newTicket.id
+ }, myOptions);
+ }
return newTicket;
}
};
diff --git a/modules/ticket/back/methods/sale/recalculatePrice.js b/modules/ticket/back/methods/sale/recalculatePrice.js
index fd3d6aa9b..ea71032d0 100644
--- a/modules/ticket/back/methods/sale/recalculatePrice.js
+++ b/modules/ticket/back/methods/sale/recalculatePrice.js
@@ -48,7 +48,7 @@ module.exports = Self => {
CALL vn.sale_recalcComponent(null);
DROP TEMPORARY TABLE tmp.recalculateSales;`;
- const recalculation = await Self.rawSql(query, salesIds, myOptions);
+ const recalculation = await Self.rawSql(query, [salesIds], myOptions);
if (tx) await tx.commit();
diff --git a/modules/ticket/back/methods/sale/specs/updatePrice.spec.js b/modules/ticket/back/methods/sale/specs/updatePrice.spec.js
index 9d1403df0..100f74bf0 100644
--- a/modules/ticket/back/methods/sale/specs/updatePrice.spec.js
+++ b/modules/ticket/back/methods/sale/specs/updatePrice.spec.js
@@ -85,6 +85,25 @@ describe('sale updatePrice()', () => {
}
});
+ it('should check if priceFixed has changed', async() => {
+ const tx = await models.Sale.beginTransaction({});
+
+ try {
+ const options = {transaction: tx};
+
+ const price = 3;
+ const beforeUpdate = await models.Sale.findById(saleId, null, options);
+ await models.Sale.updatePrice(ctx, saleId, price, options);
+ const afterUpdate = await models.Sale.findById(saleId, null, options);
+
+ expect(beforeUpdate.priceFixed).not.toEqual(afterUpdate.priceFixed);
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
+
it('should set price as a decimal number and check the sale has the mana component changing the salesPersonMana', async() => {
const tx = await models.Sale.beginTransaction({});
diff --git a/modules/ticket/back/methods/sale/updatePrice.js b/modules/ticket/back/methods/sale/updatePrice.js
index 191fd09e3..d4f128082 100644
--- a/modules/ticket/back/methods/sale/updatePrice.js
+++ b/modules/ticket/back/methods/sale/updatePrice.js
@@ -91,7 +91,21 @@ module.exports = Self => {
value: componentValue
}, myOptions);
}
- await sale.updateAttributes({price: newPrice}, myOptions);
+
+ const [priceFixed] = await Self.rawSql(`
+ SELECT SUM(value) value
+ FROM sale s
+ JOIN saleComponent sc ON sc.saleFk = s.id
+ JOIN component c ON c.id = sc.componentFk
+ JOIN componentType ct ON ct.id = c.typeFk
+ WHERE ct.isBase
+ AND s.id = ?
+ `, [id], myOptions);
+
+ await sale.updateAttributes({
+ price: newPrice,
+ priceFixed: priceFixed.value
+ }, myOptions);
await Self.rawSql('CALL vn.manaSpellersRequery(?)', [userId], myOptions);
await Self.rawSql('CALL vn.ticket_recalc(?, NULL)', [sale.ticketFk], myOptions);
diff --git a/modules/ticket/back/methods/sale/updateQuantity.js b/modules/ticket/back/methods/sale/updateQuantity.js
index 36d75ffed..4de1bcbd6 100644
--- a/modules/ticket/back/methods/sale/updateQuantity.js
+++ b/modules/ticket/back/methods/sale/updateQuantity.js
@@ -82,7 +82,7 @@ module.exports = Self => {
const message = $t('Changed sale quantity', {
ticketId: sale.ticket().id,
- changes: change,
+ changes: JSON.stringify(change),
ticketUrl: `${url}ticket/${sale.ticket().id}/sale`,
});
diff --git a/modules/ticket/back/methods/sale/usesMana.js b/modules/ticket/back/methods/sale/usesMana.js
index 31beb3a4c..b4768d80a 100644
--- a/modules/ticket/back/methods/sale/usesMana.js
+++ b/modules/ticket/back/methods/sale/usesMana.js
@@ -31,6 +31,6 @@ module.exports = Self => {
const usesMana = departments.find(department => department.id == workerDepartment.departmentFk);
- return usesMana ? true : false;
+ return !!usesMana;
};
};
diff --git a/modules/ticket/back/methods/ticket-request/confirm.js b/modules/ticket/back/methods/ticket-request/confirm.js
index 7c17d0010..45ee287de 100644
--- a/modules/ticket/back/methods/ticket-request/confirm.js
+++ b/modules/ticket/back/methods/ticket-request/confirm.js
@@ -54,9 +54,17 @@ module.exports = Self => {
throw new UserError(`That item doesn't exists`);
const request = await models.TicketRequest.findById(ctx.args.id, {
- include: {relation: 'ticket'}
+ include: {
+ relation: 'ticket',
+ scope: {
+ include: {
+ relation: 'client',
+ scope: {
+ fields: ['id', 'name', 'salesPersonFk']
+ }
+ }
+ }}
}, myOptions);
-
const itemStock = await models.Item.getVisibleAvailable(
ctx.args.itemFk,
request.ticket().warehouseFk,
@@ -89,19 +97,19 @@ module.exports = Self => {
const query = `CALL vn.sale_calculateComponent(?, NULL)`;
await Self.rawSql(query, [sale.id], myOptions);
- const url = await Self.app.models.Url.getUrl();
- const requesterId = request.requesterFk;
-
- const message = $t('Bought units from buy request', {
- quantity: sale.quantity,
- concept: sale.concept,
- itemId: sale.itemFk,
- ticketId: sale.ticketFk,
- url: `${url}ticket/${sale.ticketFk}/summary`,
- urlItem: `${url}item/${sale.itemFk}/summary`
- });
- await models.Chat.sendCheckingPresence(ctx, requesterId, message, myOptions);
-
+ const salesPerson = request.ticket().client().salesPersonFk;
+ if (salesPerson) {
+ const url = await Self.app.models.Url.getUrl();
+ const message = $t('Bought units from buy request', {
+ quantity: sale.quantity,
+ concept: sale.concept,
+ itemId: sale.itemFk,
+ ticketId: sale.ticketFk,
+ url: `${url}ticket/${sale.ticketFk}/summary`,
+ urlItem: `${url}item/${sale.itemFk}/summary`
+ });
+ await models.Chat.sendCheckingPresence(ctx, salesPerson, message, myOptions);
+ }
if (tx) await tx.commit();
return sale;
diff --git a/modules/ticket/back/methods/ticket-request/deny.js b/modules/ticket/back/methods/ticket-request/deny.js
index 44f1e48a1..26e6f63ff 100644
--- a/modules/ticket/back/methods/ticket-request/deny.js
+++ b/modules/ticket/back/methods/ticket-request/deny.js
@@ -1,18 +1,22 @@
+const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('deny', {
- description: 'sets a ticket request to denied and returns the changes',
+ description: 'Sets a ticket request to denied and returns the changes',
accessType: 'WRITE',
- accepts: [{
- arg: 'id',
- type: 'number',
- required: true,
- description: 'The request ID',
- }, {
- arg: 'observation',
- type: 'String',
- required: true,
- description: 'The request observation',
- }],
+ accepts: [
+ {
+ arg: 'id',
+ type: 'number',
+ required: true,
+ description: 'The request ID',
+ },
+ {
+ arg: 'observation',
+ type: 'string',
+ required: true,
+ description: 'The request observation',
+ }
+ ],
returns: {
type: 'number',
root: true
@@ -29,7 +33,7 @@ module.exports = Self => {
const myOptions = {};
let tx;
- if (typeof options == 'object')
+ if (typeof options === 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
@@ -39,7 +43,7 @@ module.exports = Self => {
try {
const userId = ctx.req.accessToken.userId;
- const worker = await Self.app.models.Worker.findOne({where: {id: userId}}, myOptions);
+ const worker = await models.Worker.findById(userId, {fields: ['id']}, myOptions);
const params = {
isOk: false,
@@ -47,19 +51,32 @@ module.exports = Self => {
response: ctx.args.observation,
};
- const request = await Self.app.models.TicketRequest.findById(ctx.args.id, null, myOptions);
- await request.updateAttributes(params, myOptions);
+ const request = await models.TicketRequest.findById(ctx.args.id, {
+ include: {
+ relation: 'ticket',
+ scope: {
+ include: {
+ relation: 'client',
+ scope: {
+ fields: ['id', 'name', 'salesPersonFk']
+ }
+ }
+ }
+ }
+ }, myOptions);
- const url = await Self.app.models.Url.getUrl();
- const requesterId = request.requesterFk;
+ const salesPerson = request.ticket().client().salesPersonFk;
+ if (salesPerson) {
+ const url = await models.Url.getUrl();
+ const message = $t('Deny buy request', {
+ ticketId: request.ticketFk,
+ url: `${url}ticket/${request.ticketFk}/request/index`,
+ observation: params.response
+ });
- const message = $t('Deny buy request', {
- ticketId: request.ticketFk,
- url: `${url}ticket/${request.ticketFk}/request/index`,
- observation: params.response
- });
-
- await models.Chat.sendCheckingPresence(ctx, requesterId, message, myOptions);
+ await models.Chat.sendCheckingPresence(ctx, salesPerson, message, myOptions);
+ await request.updateAttributes(params, myOptions);
+ }
if (tx) await tx.commit();
diff --git a/modules/ticket/back/methods/ticket-request/filter.js b/modules/ticket/back/methods/ticket-request/filter.js
index 5364cef9a..c2edcae81 100644
--- a/modules/ticket/back/methods/ticket-request/filter.js
+++ b/modules/ticket/back/methods/ticket-request/filter.js
@@ -59,6 +59,16 @@ module.exports = Self => {
arg: 'state',
type: 'string',
description: `Search request by request state`
+ },
+ {
+ arg: 'myTeam',
+ type: 'boolean',
+ description: `Team partners`
+ },
+ {
+ arg: 'daysOnward',
+ type: 'number',
+ description: 'The days onward'
}
],
returns: {
@@ -75,6 +85,8 @@ module.exports = Self => {
const conn = Self.dataSource.connector;
const userId = ctx.req.accessToken.userId;
const myOptions = {};
+ const models = Self.app.models;
+ const args = ctx.args;
if (typeof options == 'object')
Object.assign(myOptions, options);
@@ -82,6 +94,24 @@ module.exports = Self => {
if (ctx.args.mine)
ctx.args.attenderFk = userId;
+ const teamMembersId = [];
+ if (args.myTeam != null) {
+ const worker = await models.Worker.findById(userId, {
+ include: {
+ relation: 'collegues'
+ }
+ }, myOptions);
+ const collegues = worker.collegues() || [];
+ for (let collegue of collegues)
+ teamMembersId.push(collegue.collegueFk);
+
+ if (teamMembersId.length == 0)
+ teamMembersId.push(userId);
+ }
+
+ const today = Date.vnNew();
+ const future = Date.vnNew();
+
let where = buildFilter(ctx.args, (param, value) => {
switch (param) {
case 'search':
@@ -113,9 +143,18 @@ module.exports = Self => {
return {'w.id': value};
case 'salesPersonFk':
return {'c.salesPersonFk': value};
+ case 'myTeam':
+ if (value)
+ return {'tr.requesterFk': {inq: teamMembersId}};
+ else
+ return {'tr.requesterFk': {nin: teamMembersId}};
+ case 'daysOnward':
+ today.setHours(0, 0, 0, 0);
+ future.setDate(today.getDate() + value);
+ future.setHours(23, 59, 59, 999);
+ return {'t.shipped': {between: [today, future]}};
}
});
-
if (!where)
where = {};
where['tw.ticketFk'] = null;
diff --git a/modules/ticket/back/methods/ticket/closeAll.js b/modules/ticket/back/methods/ticket/closeAll.js
index 143c0a3f0..71122808c 100644
--- a/modules/ticket/back/methods/ticket/closeAll.js
+++ b/modules/ticket/back/methods/ticket/closeAll.js
@@ -1,11 +1,17 @@
-const UserError = require('vn-loopback/util/user-error');
const closure = require('./closure');
module.exports = Self => {
Self.remoteMethodCtx('closeAll', {
description: 'Makes the closure process from all warehouses',
accessType: 'WRITE',
- accepts: [],
+ accepts: [
+ {
+ arg: 'options',
+ type: 'object',
+ http: {source: 'body'},
+ description: 'Optional parameters, including transaction.'
+ }
+ ],
returns: {
type: 'object',
root: true
@@ -16,21 +22,20 @@ module.exports = Self => {
}
});
- Self.closeAll = async ctx => {
+ Self.closeAll = async(ctx, options) => {
+ const userId = ctx.req.accessToken.userId;
+ const myOptions = {userId};
+
+ if (typeof options == 'object')
+ Object.assign(myOptions, options);
+
+ let tx;
+ // IMPORTANT: Due to its high cost in production, wrapping this process in a transaction may cause timeouts.
+
const toDate = Date.vnNew();
toDate.setHours(0, 0, 0, 0);
toDate.setDate(toDate.getDate() - 1);
- const todayMinDate = Date.vnNew();
- todayMinDate.setHours(0, 0, 0, 0);
-
- const todayMaxDate = Date.vnNew();
- todayMaxDate.setHours(23, 59, 59, 59);
-
- // Prevent closure for current day
- if (toDate >= todayMinDate && toDate <= todayMaxDate)
- throw new UserError('You cannot close tickets for today');
-
const tickets = await Self.rawSql(`
SELECT t.id,
t.clientFk,
@@ -41,7 +46,7 @@ module.exports = Self => {
c.salesPersonFk,
c.isToBeMailed,
c.hasToInvoice,
- co.hasDailyInvoice,
+ c.hasDailyInvoice,
eu.email salesPersonEmail,
t.addressFk
FROM ticket t
@@ -53,16 +58,17 @@ module.exports = Self => {
JOIN province p ON p.id = c.provinceFk
JOIN country co ON co.id = p.countryFk
LEFT JOIN account.emailUser eu ON eu.userFk = c.salesPersonFk
+ JOIN ticketConfig tc ON TRUE
WHERE (al.code = 'PACKED' OR (am.code = 'refund' AND al.code <> 'delivered'))
- AND DATE(t.shipped) BETWEEN ? - INTERVAL 2 DAY AND util.dayEnd(?)
+ AND t.shipped BETWEEN ? - INTERVAL tc.closureDaysAgo DAY AND util.dayEnd(?)
AND t.refFk IS NULL
GROUP BY t.id
- `, [toDate, toDate]);
+ `, [toDate, toDate], myOptions);
const ticketIds = tickets.map(ticket => ticket.id);
await Self.rawSql(`
INSERT INTO util.debug (variable, value)
VALUES ('nightInvoicing', ?)
- `, [ticketIds.join(',')]);
+ `, [ticketIds.join(',')], myOptions);
await Self.rawSql(`
WITH ticketNotInvoiceable AS(
@@ -108,6 +114,7 @@ module.exports = Self => {
JOIN alertLevel al ON al.id = ts.alertLevel
JOIN client c ON c.id = t.clientFk
JOIN province p ON p.id = c.provinceFk
+ JOIN ticketConfig tc ON TRUE
LEFT JOIN autonomy a ON a.id = p.autonomyFk
JOIN country co ON co.id = p.countryFk
LEFT JOIN account.emailUser eu ON eu.userFk = c.salesPersonFk
@@ -116,9 +123,9 @@ module.exports = Self => {
LEFT JOIN vn.invoiceOutSerial ios ON ios.taxAreaFk = 'WORLD'
AND ios.code = invoiceSerial(t.clientFk, t.companyFk, 'multiple')
WHERE (al.code = 'PACKED' OR (am.code = 'refund' AND al.code <> 'delivered'))
- AND DATE(t.shipped) BETWEEN ? - INTERVAL 2 DAY AND util.dayEnd(?)
+ AND t.shipped BETWEEN ? - INTERVAL tc.closureDaysAgo DAY AND util.dayEnd(?)
AND t.refFk IS NULL
- AND IFNULL(a.hasDailyInvoice, co.hasDailyInvoice)
+ AND c.hasDailyInvoice
GROUP BY ticketFk
HAVING hasErrorToInvoice
OR hasErrorTaxDataChecked
@@ -131,9 +138,9 @@ module.exports = Self => {
) SELECT IF(errors = '{"tickets": null}',
'No errors',
util.notification_send('invoice-ticket-closure', errors, NULL))
- FROM ticketNotInvoiceable`, [toDate, toDate]);
+ FROM ticketNotInvoiceable`, [toDate, toDate], myOptions);
- await closure(ctx, Self, tickets);
+ await closure(ctx, Self, tickets, myOptions);
await Self.rawSql(`
UPDATE ticket t
@@ -141,13 +148,17 @@ module.exports = Self => {
JOIN alertLevel al ON al.id = ts.alertLevel
JOIN agencyMode am ON am.id = t.agencyModeFk
JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
+ JOIN ticketConfig tc ON TRUE
LEFT JOIN ticketObservation tob ON tob.ticketFk = t.id
SET t.routeFk = NULL
- WHERE DATE(t.shipped) BETWEEN ? - INTERVAL 2 DAY AND util.dayEnd(?)
+ WHERE t.shipped BETWEEN ? - INTERVAL tc.closureDaysAgo DAY AND util.dayEnd(?)
AND al.code NOT IN ('DELIVERED', 'PACKED')
AND NOT t.packages
AND tob.id IS NULL
- AND t.routeFk`, [toDate, toDate], {userId: ctx.req.accessToken.userId});
+ AND t.routeFk`, [toDate, toDate], myOptions);
+
+ if (tx)
+ await tx.commit();
return {
message: 'Success'
diff --git a/modules/ticket/back/methods/ticket/closeByTicket.js b/modules/ticket/back/methods/ticket/closeByTicket.js
index 40fe048a5..8a21267b6 100644
--- a/modules/ticket/back/methods/ticket/closeByTicket.js
+++ b/modules/ticket/back/methods/ticket/closeByTicket.js
@@ -50,7 +50,7 @@ module.exports = Self => {
c.salesPersonFk,
c.isToBeMailed,
c.hasToInvoice,
- co.hasDailyInvoice,
+ c.hasDailyInvoice,
eu.email salesPersonEmail,
t.addressFk
FROM expedition e
@@ -58,8 +58,6 @@ module.exports = Self => {
JOIN ticketState ts ON ts.ticketFk = t.id
JOIN alertLevel al ON al.id = ts.alertLevel
JOIN client c ON c.id = t.clientFk
- JOIN province p ON p.id = c.provinceFk
- JOIN country co ON co.id = p.countryFk
LEFT JOIN account.emailUser eu ON eu.userFk = c.salesPersonFk
WHERE al.code = 'PACKED'
AND t.id = ?
diff --git a/modules/ticket/back/methods/ticket/closure.js b/modules/ticket/back/methods/ticket/closure.js
index a75596bac..e4cb49007 100644
--- a/modules/ticket/back/methods/ticket/closure.js
+++ b/modules/ticket/back/methods/ticket/closure.js
@@ -12,17 +12,21 @@ module.exports = async function(ctx, Self, tickets, options) {
Object.assign(myOptions, options);
let tx;
- if (!myOptions.transaction) {
- tx = await Self.beginTransaction({});
- myOptions.transaction = tx;
- }
+ // IMPORTANT: Due to its high cost in production, wrapping this process in a transaction may cause timeouts.
if (tickets.length == 0) return;
const failedtickets = [];
for (const ticket of tickets) {
try {
- await Self.app.models.InvoiceOut.getSerial(ticket.clientFk, ticket.companyFk, ticket.addressFk, 'quick');
+ await Self.rawSql(`CALL util.debugAdd('invoicingTicket', ?)`, [ticket.id], myOptions);
+
+ await Self.app.models.InvoiceOut.getSerial(
+ ticket.clientFk,
+ ticket.companyFk,
+ ticket.addressFk,
+ 'quick',
+ myOptions);
await Self.rawSql(
`CALL vn.ticket_closeByTicket(?)`,
[ticket.id],
@@ -149,6 +153,11 @@ module.exports = async function(ctx, Self, tickets, options) {
myOptions);
}
} catch (error) {
+ await Self.rawSql(`
+ INSERT INTO util.debug (variable, value)
+ VALUES ('invoicingTicketError', ?)
+ `, [ticket.id + ' - ' + error]);
+
if (error.responseCode == 450) {
await invalidEmail(ticket);
continue;
diff --git a/modules/ticket/back/methods/ticket/filter.js b/modules/ticket/back/methods/ticket/filter.js
index 06781c3c8..c61223470 100644
--- a/modules/ticket/back/methods/ticket/filter.js
+++ b/modules/ticket/back/methods/ticket/filter.js
@@ -228,52 +228,58 @@ module.exports = Self => {
stmt = new ParameterizedSQL(`
CREATE OR REPLACE TEMPORARY TABLE tmp.filter
(INDEX (id))
- ENGINE = MEMORY
+ ENGINE = InnoDB
SELECT t.id,
- t.shipped,
- CAST(DATE(t.shipped) AS CHAR) shippedDate,
- HOUR(t.shipped) shippedHour,
- t.nickname,
- t.refFk,
- t.routeFk,
- t.warehouseFk,
- t.clientFk,
- t.totalWithoutVat,
- t.totalWithVat,
- io.id invoiceOutId,
- a.provinceFk,
- p.name province,
- w.name warehouse,
- am.name agencyMode,
- am.id agencyModeFk,
- st.name state,
- st.classColor,
- wk.lastName salesPerson,
- ts.stateFk stateFk,
- ts.alertLevel alertLevel,
- ts.code alertLevelCode,
- u.name userName,
- c.salesPersonFk,
- z.hour zoneLanding,
- HOUR(z.hour) zoneHour,
- MINUTE(z.hour) zoneMinute,
- z.name zoneName,
- z.id zoneFk,
- CAST(z.hour AS CHAR) hour,
- a.nickname addressNickname
- FROM ticket t
- LEFT JOIN invoiceOut io ON t.refFk = io.ref
- 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.id
- LEFT JOIN route r ON r.id = t.routeFk
+ t.shipped,
+ CAST(DATE(t.shipped) AS CHAR) shippedDate,
+ HOUR(t.shipped) shippedHour,
+ t.nickname,
+ t.refFk,
+ t.routeFk,
+ t.warehouseFk,
+ t.clientFk,
+ t.totalWithoutVat,
+ t.totalWithVat,
+ io.id invoiceOutId,
+ a.provinceFk,
+ p.name province,
+ w.name warehouse,
+ am.name agencyMode,
+ am.id agencyModeFk,
+ st.name state,
+ st.classColor,
+ wk.lastName salesPerson,
+ ts.stateFk stateFk,
+ ts.alertLevel alertLevel,
+ ts.code alertLevelCode,
+ u.name userName,
+ c.salesPersonFk,
+ z.hour zoneLanding,
+ HOUR(z.hour) zoneHour,
+ MINUTE(z.hour) zoneMinute,
+ z.name zoneName,
+ z.id zoneFk,
+ CAST(z.hour AS CHAR) hour,
+ a.nickname addressNickname,
+ (SELECT GROUP_CONCAT(DISTINCT i2.itemPackingTypeFk ORDER BY i2.itemPackingTypeFk SEPARATOR ',')
+ FROM sale s2
+ JOIN item i2 ON i2.id = s2.itemFk
+ WHERE s2.ticketFk = t.id
+ ) AS packing,
+ c.credit
+ FROM ticket t
+ LEFT JOIN invoiceOut io ON t.refFk = io.ref
+ 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.id
+ LEFT JOIN route r ON r.id = t.routeFk
`);
if (args.orderFk) {
@@ -292,6 +298,7 @@ module.exports = Self => {
}
stmt.merge(conn.makeWhere(filter.where));
+
stmts.push(stmt);
stmt = new ParameterizedSQL(`
diff --git a/modules/ticket/back/methods/ticket/getSales.js b/modules/ticket/back/methods/ticket/getSales.js
index e721d90ae..5b2288d31 100644
--- a/modules/ticket/back/methods/ticket/getSales.js
+++ b/modules/ticket/back/methods/ticket/getSales.js
@@ -37,6 +37,7 @@ module.exports = Self => {
'name',
'subName',
'itemPackingTypeFk',
+ 'size',
'tag5',
'value5',
'tag6',
diff --git a/modules/ticket/back/methods/ticket/getTicketsAdvance.js b/modules/ticket/back/methods/ticket/getTicketsAdvance.js
index 1bd5f83de..58d46173c 100644
--- a/modules/ticket/back/methods/ticket/getTicketsAdvance.js
+++ b/modules/ticket/back/methods/ticket/getTicketsAdvance.js
@@ -50,6 +50,16 @@ module.exports = Self => {
type: 'boolean',
description: 'True when lines and stock of origin are equal'
},
+ {
+ arg: 'departmentFk',
+ type: 'number',
+ description: 'Department identifier'
+ },
+ {
+ arg: 'onlyWithDestination',
+ type: 'Boolean',
+ description: 'True when only tickets with destination are returned'
+ },
{
arg: 'filter',
type: 'object',
@@ -96,6 +106,10 @@ module.exports = Self => {
};
case 'isFullMovable':
return {'f.isFullMovable': value};
+ case 'departmentFk':
+ return {'f.departmentFk': value};
+ case 'onlyWithDestination':
+ return {'f.id': value ? {neq: null} : null};
}
});
diff --git a/modules/ticket/back/methods/ticket/saveCmr.js b/modules/ticket/back/methods/ticket/saveCmr.js
index 339ac1e38..5ac748751 100644
--- a/modules/ticket/back/methods/ticket/saveCmr.js
+++ b/modules/ticket/back/methods/ticket/saveCmr.js
@@ -41,7 +41,7 @@ module.exports = Self => {
for (const ticketId of tickets) {
const ticket = await models.Ticket.findById(ticketId, null, myOptions);
- if (ticket.cmrFk) {
+ if (ticket.$cmrFk) {
const hasDmsCmr = await Self.rawSql(`
SELECT d.id
FROM ticketDms td
@@ -53,8 +53,7 @@ module.exports = Self => {
if (hasDmsCmr.length)
throw new UserError('This ticket already has a cmr saved');
- ctx.args.id = ticket.cmrFk;
- const response = await models.Route.cmr(ctx, myOptions);
+ const response = await models.Cmr.print(ctx, ticket.$cmrFk, myOptions);
const pdfStream = Readable.from(Buffer.from(response[0]));
const data = {
workerFk: ctx.req.accessToken.userId,
diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js
index bc0da686c..ac2a7bc66 100644
--- a/modules/ticket/back/methods/ticket/saveSign.js
+++ b/modules/ticket/back/methods/ticket/saveSign.js
@@ -151,7 +151,7 @@ module.exports = Self => {
await Self.rawSql(`CALL vn.ticket_setState(?, ?)`, [ticketId, stateCode], myOptions);
- if (ticket?.address()?.province()?.country()?.code != 'ES' && ticket.cmrFk) {
+ if (ticket?.address()?.province()?.country()?.code != 'ES' && ticket.$cmrFk) {
await models.Ticket.saveCmr(ctx, [ticketId], myOptions);
externalTickets.push(ticketId);
}
@@ -161,6 +161,6 @@ module.exports = Self => {
if (tx) await tx.rollback();
throw e;
}
- await models.Route.cmrEmail(ctx, externalTickets);
+ await models.Ticket.sendCmrEmail(ctx, externalTickets);
};
};
diff --git a/modules/route/back/methods/route/cmrEmail.js b/modules/ticket/back/methods/ticket/sendCmrEmail.js
similarity index 92%
rename from modules/route/back/methods/route/cmrEmail.js
rename to modules/ticket/back/methods/ticket/sendCmrEmail.js
index 0c4cc5061..27f22ca14 100644
--- a/modules/route/back/methods/route/cmrEmail.js
+++ b/modules/ticket/back/methods/ticket/sendCmrEmail.js
@@ -2,7 +2,7 @@ const {Email} = require('vn-print');
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
- Self.remoteMethodCtx('cmrEmail', {
+ Self.remoteMethodCtx('sendCmrEmail', {
description: 'Sends the email with an cmr attached PDF',
accessType: 'WRITE',
accepts: [
@@ -14,12 +14,12 @@ module.exports = Self => {
}
],
http: {
- path: '/cmrEmail',
+ path: '/sendCmrEmail',
verb: 'POST'
}
});
- Self.cmrEmail = async function(ctx, tickets, options) {
+ Self.sendCmrEmail = async function(ctx, tickets, options) {
const models = Self.app.models;
const myOptions = {};
let tx;
@@ -70,7 +70,7 @@ module.exports = Self => {
await email.send({
overrideAttachments: true,
attachments: [{
- filename: `${ticket.cmrFk}.pdf`,
+ filename: `${ticket.$cmrFk}.pdf`,
content: response[0]
}]
});
diff --git a/modules/ticket/back/methods/ticket/setDeleted.js b/modules/ticket/back/methods/ticket/setDeleted.js
index a684e1cbc..fcab95ee2 100644
--- a/modules/ticket/back/methods/ticket/setDeleted.js
+++ b/modules/ticket/back/methods/ticket/setDeleted.js
@@ -49,9 +49,12 @@ module.exports = Self => {
where: {originalTicketFk: id}
}, myOptions);
+ const hasRefund = !!ticketRefunds?.length;
+
const allDeleted = ticketRefunds.every(refund => refund.refundTicket().isDeleted);
- if (ticketRefunds?.length && !allDeleted) {
+ if (!hasRefund) await models.TicketRefund.destroyAll({refundTicketFk: id}, myOptions);
+ if (hasRefund && !allDeleted) {
const notDeleted = [];
for (const refund of ticketRefunds)
if (!refund.refundTicket().isDeleted) notDeleted.push(refund.refundTicket().id);
diff --git a/modules/ticket/back/methods/ticket/specs/closeAll.spec.js b/modules/ticket/back/methods/ticket/specs/closeAll.spec.js
new file mode 100644
index 000000000..f01541eec
--- /dev/null
+++ b/modules/ticket/back/methods/ticket/specs/closeAll.spec.js
@@ -0,0 +1,54 @@
+const models = require('vn-loopback/server/server').models;
+const LoopBackContext = require('loopback-context');
+
+describe('Ticket Closure - closeAll function', () => {
+ let ctx = {
+ req: {
+ getLocale: () => 'es',
+ accessToken: {userId: 1106},
+ headers: {origin: 'http://localhost'},
+ __: value => value,
+ },
+ args: {}
+ };
+ let options;
+ let tx;
+ let originalVnNew;
+
+ beforeEach(async() => {
+ spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({active: ctx.req});
+
+ tx = await models.Ticket.beginTransaction({});
+ options = {transaction: tx};
+ originalVnNew = Date.vnNew;
+ spyOn(Date, 'vnNew').and.callFake(() => {
+ const mockDate = originalVnNew();
+ mockDate.setDate(mockDate.getDate() + 1);
+ return mockDate;
+ });
+ });
+
+ afterEach(async() => {
+ if (tx)
+ await tx.rollback();
+ });
+
+ it('should set routeFk to NULL when conditions are met', async() => {
+ const ticketsBefore = await models.Ticket.find({
+ where: {
+ routeFk: {neq: null}
+ }
+ }, options);
+
+ await models.Ticket.closeAll(ctx, options);
+
+ const ticketsAfter = await models.Ticket.find({
+ where: {
+ id: {inq: ticketsBefore.map(ticket => ticket.id)},
+ routeFk: {neq: null}
+ }
+ }, options);
+
+ expect(ticketsBefore.length).toBeGreaterThan(ticketsAfter.length);
+ });
+});
diff --git a/modules/ticket/back/methods/ticket/specs/closure.spec.js b/modules/ticket/back/methods/ticket/specs/closure.spec.js
index 303c38233..cafe178cb 100644
--- a/modules/ticket/back/methods/ticket/specs/closure.spec.js
+++ b/modules/ticket/back/methods/ticket/specs/closure.spec.js
@@ -50,9 +50,9 @@ describe('Ticket closure functionality', () => {
expect(ticketStateBefore.code).not.toBe(ticketStateAfter.code);
- const ticketAfter = await models.TicketState.findById(ticketId, null, options);
+ const ticketAfter = await models.Ticket.findById(ticketId, null, options);
- expect(ticketAfter.refFk).toBeUndefined();
+ expect(ticketAfter.refFk).toBeNull();
});
it('should send Incoterms authorization email on first order', async() => {
diff --git a/modules/ticket/back/methods/ticket/specs/getTicketsAdvance.spec.js b/modules/ticket/back/methods/ticket/specs/getTicketsAdvance.spec.js
index 488cd1fc2..157cdb1ff 100644
--- a/modules/ticket/back/methods/ticket/specs/getTicketsAdvance.spec.js
+++ b/modules/ticket/back/methods/ticket/specs/getTicketsAdvance.spec.js
@@ -6,6 +6,10 @@ describe('TicketFuture getTicketsAdvance()', () => {
today.setHours(0, 0, 0, 0);
let tomorrow = Date.vnNew();
tomorrow.setDate(today.getDate() + 1);
+ const salesDeptId = 43;
+ const spain1DeptId = 95;
+ const warehouseId = 1;
+ beforeAll.mockLoopBackContext();
it('should return the tickets passing the required data', async() => {
const tx = await models.Ticket.beginTransaction({});
@@ -16,7 +20,7 @@ describe('TicketFuture getTicketsAdvance()', () => {
const args = {
dateFuture: tomorrow,
dateToAdvance: today,
- warehouseFk: 1,
+ warehouseFk: warehouseId,
};
ctx.args = args;
@@ -39,7 +43,7 @@ describe('TicketFuture getTicketsAdvance()', () => {
const args = {
dateFuture: tomorrow,
dateToAdvance: today,
- warehouseFk: 1,
+ warehouseFk: warehouseId,
isFullMovable: true
};
@@ -64,7 +68,7 @@ describe('TicketFuture getTicketsAdvance()', () => {
const args = {
dateFuture: tomorrow,
dateToAdvance: today,
- warehouseFk: 1,
+ warehouseFk: warehouseId,
isFullMovable: false
};
@@ -89,7 +93,7 @@ describe('TicketFuture getTicketsAdvance()', () => {
const args = {
dateFuture: tomorrow,
dateToAdvance: today,
- warehouseFk: 1,
+ warehouseFk: warehouseId,
ipt: 'V'
};
@@ -114,7 +118,7 @@ describe('TicketFuture getTicketsAdvance()', () => {
const args = {
dateFuture: tomorrow,
dateToAdvance: today,
- warehouseFk: 1,
+ warehouseFk: warehouseId,
tfIpt: 'V'
};
@@ -129,4 +133,91 @@ describe('TicketFuture getTicketsAdvance()', () => {
throw e;
}
});
+
+ it('should return the tickets matching the right department', async() => {
+ const tx = await models.Ticket.beginTransaction({});
+
+ try {
+ const options = {transaction: tx};
+ ctx.args = {
+ dateFuture: tomorrow,
+ dateToAdvance: today,
+ warehouseFk: warehouseId,
+ };
+
+ await models.Ticket.updateAll({id: {inq: [12, 31]}}, {clientFk: 1}, options);
+ const client = await models.Client.findById(1, null, options);
+ await client.updateAttribute('salesPersonFk', 1, options);
+ const business = await models.Business.findById(1, null, options);
+ await business.updateAttributes({departmentFk: spain1DeptId}, options);
+
+ const saleTickets = await models.Ticket.getTicketsAdvance(ctx, options);
+ const filteredSaleTickets = await models.Ticket.getTicketsAdvance(
+ {args: {...ctx.args, departmentFk: spain1DeptId}},
+ options);
+
+ expect(saleTickets.length).toBeGreaterThan(filteredSaleTickets.length);
+ expect(saleTickets.some(ticket => ticket.departmentFk === salesDeptId)).toBeTrue();
+ expect(saleTickets.some(ticket => ticket.departmentFk === spain1DeptId)).toBeTrue();
+
+ expect(filteredSaleTickets.some(ticket => ticket.departmentFk === salesDeptId)).toBeFalse();
+ expect(filteredSaleTickets.some(ticket => ticket.departmentFk === spain1DeptId)).toBeTrue();
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
+
+ it('should return the tickets with only destination', async() => {
+ const tx = await models.Ticket.beginTransaction({});
+
+ try {
+ const options = {transaction: tx};
+
+ const args = {
+ dateFuture: today,
+ dateToAdvance: today.setHours(23, 59, 59, 999),
+ warehouseFk: warehouseId,
+ };
+ ctx.args = args;
+
+ const allTickets = await models.Ticket.getTicketsAdvance(ctx, options);
+ ctx.args.onlyWithDestination = true;
+ const withDestinationTickets = await models.Ticket.getTicketsAdvance(ctx, options);
+
+ expect(allTickets.filter(ticket => ticket.id).length).toBe(withDestinationTickets.length);
+
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
+
+ it('should return the tickets without only destination', async() => {
+ const tx = await models.Ticket.beginTransaction({});
+
+ try {
+ const options = {transaction: tx};
+
+ const args = {
+ dateFuture: today,
+ dateToAdvance: today.setHours(23, 59, 59, 999),
+ warehouseFk: warehouseId,
+ };
+ ctx.args = args;
+
+ const allTickets = await models.Ticket.getTicketsAdvance(ctx, options);
+ ctx.args.onlyWithDestination = false;
+ const withoutDestinationTickets = await models.Ticket.getTicketsAdvance(ctx, options);
+
+ expect(allTickets.filter(ticket => !ticket.id).length).toBe(withoutDestinationTickets.length);
+
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+ });
});
diff --git a/modules/ticket/back/methods/ticket/specs/makeInvoice.spec.js b/modules/ticket/back/methods/ticket/specs/makeInvoice.spec.js
index 88812dc92..f9e4bcac0 100644
--- a/modules/ticket/back/methods/ticket/specs/makeInvoice.spec.js
+++ b/modules/ticket/back/methods/ticket/specs/makeInvoice.spec.js
@@ -77,6 +77,8 @@ describe('ticket makeInvoice()', () => {
await tx.rollback();
}
- expect(error.message).toEqual(`The address of the customer must have information about Incoterms and Customs Agent`);
+ expect(error.message).toEqual(
+ `The address of the customer must have information about Incoterms and Customs Agent`
+ );
});
});
diff --git a/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js b/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js
index 782c31c02..b70c94cee 100644
--- a/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js
+++ b/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js
@@ -113,5 +113,27 @@ describe('ticket setDeleted()', () => {
expect(error.message).not.toContain('Tickets with associated refunds');
});
+
+ it('should delete the refund - original ticket relation', async() => {
+ const tx = await models.Ticket.beginTransaction({});
+ try {
+ const options = {transaction: tx};
+
+ const ticketId = 24;
+ const refundTicket = await models.TicketRefund.findOne({where: {refundTicketFk: ticketId}}, options);
+
+ expect(refundTicket).toBeTruthy();
+
+ await models.Ticket.setDeleted(ctx, ticketId, options);
+ const removedRefundTicket = await models.TicketRefund.findOne({
+ where: {refundTicketFk: ticketId}},
+ options);
+
+ expect(removedRefundTicket).toBeNull();
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ }
+ });
});
});
diff --git a/modules/ticket/back/methods/ticket/transferSales.js b/modules/ticket/back/methods/ticket/transferSales.js
index 5f5fdde67..580a8e1f7 100644
--- a/modules/ticket/back/methods/ticket/transferSales.js
+++ b/modules/ticket/back/methods/ticket/transferSales.js
@@ -81,6 +81,10 @@ module.exports = Self => {
if (ticketId != id && hasClaimedSales)
throw new UserError(`Can't transfer claimed sales`);
+ const missingSales = sales.some(({id}) => !map.has(id));
+ if (missingSales)
+ throw new UserError($t('Sales already moved'));
+
for (const sale of sales) {
const originalSale = map.get(sale.id);
if (sale.quantity == originalSale?.quantity) {
diff --git a/modules/ticket/back/models/expedition-state.js b/modules/ticket/back/models/expedition-state.js
index 496dd88d3..f819dc05c 100644
--- a/modules/ticket/back/models/expedition-state.js
+++ b/modules/ticket/back/models/expedition-state.js
@@ -1,4 +1,66 @@
+const LoopBackContext = require('loopback-context');
+
module.exports = function(Self) {
require('../methods/expedition-state/filter')(Self);
require('../methods/expedition-state/addExpeditionState')(Self);
+
+ Self.observe('before save', async ctx => {
+ const models = Self.app.models;
+ const changes = ctx.data || ctx.instance;
+ const instance = ctx.currentInstance;
+ const loopBackContext = LoopBackContext.getCurrentContext();
+ const httpCtx = {req: loopBackContext.active};
+ const httpRequest = httpCtx.req.http.req;
+ const $t = httpRequest.__;
+ const myOptions = {};
+
+ if (ctx.options && ctx.options.transaction)
+ myOptions.transaction = ctx.options.transaction;
+
+ const newStateType = changes?.typeFk;
+ if (newStateType == null) return;
+
+ const expeditionId = changes?.expeditionFk || instance?.expeditionFk;
+
+ const {code} = await models.ExpeditionStateType.findById(
+ newStateType,
+ {
+ fields: ['code']
+ },
+ myOptions);
+
+ if (code !== 'LOST') return;
+
+ const dataExpedition = await models.Expedition.findById(
+ expeditionId, {
+ fields: ['ticketFk'],
+ include: [{
+ relation: 'ticket',
+ scope: {
+ fields: ['clientFk'],
+ include: [{
+ relation: 'client',
+ scope: {
+ fields: ['name', 'salesPersonFk']
+ }
+ }]
+ }
+ }],
+
+ }, myOptions);
+
+ const salesPersonFk = dataExpedition.ticket()?.client()?.salesPersonFk;
+
+ if (salesPersonFk) {
+ const url = await Self.app.models.Url.getUrl();
+ const fullUrl = `${url}ticket/${dataExpedition.ticketFk}/expedition`;
+ const message = $t('ticketLostExpedition', {
+ ticketId: dataExpedition.ticketFk,
+ expeditionId: expeditionId,
+ url: fullUrl
+ });
+ await models.Chat.sendCheckingPresence(httpCtx, salesPersonFk, message);
+ }
+ });
};
+
diff --git a/modules/ticket/back/models/expedition-state.json b/modules/ticket/back/models/expedition-state.json
index 159a9275e..7d8079b33 100644
--- a/modules/ticket/back/models/expedition-state.json
+++ b/modules/ticket/back/models/expedition-state.json
@@ -19,13 +19,17 @@
"type": "number"
},
"typeFk": {
- "type": "number"
+ "type": "number",
+ "required": true
},
"userFk": {
"type": "number"
},
"isScanned": {
"type": "boolean"
+ },
+ "scanOrder": {
+ "type": "number"
}
},
"relations": {
diff --git a/modules/ticket/back/models/expedition.json b/modules/ticket/back/models/expedition.json
index 2dcca1e87..f3f912ec3 100644
--- a/modules/ticket/back/models/expedition.json
+++ b/modules/ticket/back/models/expedition.json
@@ -1,63 +1,66 @@
{
- "name": "Expedition",
- "base": "VnModel",
- "mixins": {
- "Loggable": true
+ "name": "Expedition",
+ "base": "VnModel",
+ "mixins": {
+ "Loggable": true
+ },
+ "options": {
+ "mysql": {
+ "table": "expedition"
+ }
+ },
+ "properties": {
+ "id": {
+ "id": true,
+ "type": "number",
+ "description": "Identifier"
},
- "options": {
- "mysql": {
- "table": "expedition"
- }
+ "freightItemFk": {
+ "type": "number"
},
- "properties": {
- "id": {
- "id": true,
- "type": "number",
- "description": "Identifier"
- },
- "freightItemFk": {
- "type": "number"
- },
- "created": {
- "type": "date"
- },
- "counter": {
- "type": "number"
- },
- "externalId": {
- "type": "string"
- }
+ "created": {
+ "type": "date"
},
- "relations": {
- "ticket": {
- "type": "belongsTo",
- "model": "Ticket",
- "foreignKey": "ticketFk"
- },
- "agencyMode": {
- "type": "belongsTo",
- "model": "AgencyMode",
- "foreignKey": "agencyModeFk"
- },
- "worker": {
- "type": "belongsTo",
- "model": "Worker",
- "foreignKey": "workerFk"
- },
- "packages": {
- "type": "hasMany",
- "model": "TicketPackaging",
- "foreignKey": "ticketFk"
- },
- "freightItem": {
- "type": "belongsTo",
- "model": "Item",
- "foreignKey": "freightItemFk"
- },
- "packaging": {
- "type": "belongsTo",
- "model": "Package",
- "foreignKey": "packagingFk"
- }
+ "counter": {
+ "type": "number"
+ },
+ "externalId": {
+ "type": "string"
+ },
+ "stateTypeFk": {
+ "type": "number"
+ }
+ },
+ "relations": {
+ "ticket": {
+ "type": "belongsTo",
+ "model": "Ticket",
+ "foreignKey": "ticketFk"
+ },
+ "agencyMode": {
+ "type": "belongsTo",
+ "model": "AgencyMode",
+ "foreignKey": "agencyModeFk"
+ },
+ "worker": {
+ "type": "belongsTo",
+ "model": "Worker",
+ "foreignKey": "workerFk"
+ },
+ "packages": {
+ "type": "hasMany",
+ "model": "TicketPackaging",
+ "foreignKey": "ticketFk"
+ },
+ "freightItem": {
+ "type": "belongsTo",
+ "model": "Item",
+ "foreignKey": "freightItemFk"
+ },
+ "packaging": {
+ "type": "belongsTo",
+ "model": "Package",
+ "foreignKey": "packagingFk"
}
}
+}
\ No newline at end of file
diff --git a/modules/ticket/back/models/sale.json b/modules/ticket/back/models/sale.json
index 96a36bbc9..947115f5c 100644
--- a/modules/ticket/back/models/sale.json
+++ b/modules/ticket/back/models/sale.json
@@ -28,6 +28,9 @@
"discount": {
"type": "number"
},
+ "priceFixed": {
+ "type": "number"
+ },
"reserved": {
"type": "boolean"
},
diff --git a/modules/ticket/back/models/saleGroup.json b/modules/ticket/back/models/saleGroup.json
index aa78b4167..5f432b514 100644
--- a/modules/ticket/back/models/saleGroup.json
+++ b/modules/ticket/back/models/saleGroup.json
@@ -29,6 +29,11 @@
"type": "belongsTo",
"model": "Parking",
"foreignKey": "parkingFk"
+ },
+ "state": {
+ "type": "belongsTo",
+ "model": "State",
+ "foreignKey": "stateFk"
}
}
-}
+}
\ No newline at end of file
diff --git a/modules/ticket/back/models/ticket-methods.js b/modules/ticket/back/models/ticket-methods.js
index 7fe968b26..620b3e184 100644
--- a/modules/ticket/back/models/ticket-methods.js
+++ b/modules/ticket/back/models/ticket-methods.js
@@ -40,6 +40,7 @@ module.exports = function(Self) {
require('../methods/ticket/expeditionPalletLabel')(Self);
require('../methods/ticket/saveSign')(Self);
require('../methods/ticket/saveCmr')(Self);
+ require('../methods/ticket/sendCmrEmail')(Self);
require('../methods/ticket/invoiceTickets')(Self);
require('../methods/ticket/invoiceTicketsAndPdf')(Self);
require('../methods/ticket/docuwareDownload')(Self);
diff --git a/modules/ticket/front/sale/index.js b/modules/ticket/front/sale/index.js
index 4f8494ed0..3672c467d 100644
--- a/modules/ticket/front/sale/index.js
+++ b/modules/ticket/front/sale/index.js
@@ -387,10 +387,10 @@ class Controller extends Section {
}
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.$http.post(`Orders/newFromTicket`, {ticketFk: this.ticket.id}).then(async res => {
+ const path = await this.vnApp.getUrl(`order/${res.data}/catalog`);
+ window.open(path, '_blank');
this.vnApp.showSuccess(this.$t('Order created'));
});
}
diff --git a/modules/ticket/front/sale/index.spec.js b/modules/ticket/front/sale/index.spec.js
index 931776619..8ff9aa624 100644
--- a/modules/ticket/front/sale/index.spec.js
+++ b/modules/ticket/front/sale/index.spec.js
@@ -567,14 +567,10 @@ describe('Ticket', () => {
const expectedResponse = {id: 123};
window.open = jasmine.createSpy('open');
- controller.$state.href = jasmine.createSpy('href')
- .and.returnValue('/somePath');
$httpBackend.expect('POST', `Orders/newFromTicket`, expectedParams).respond(expectedResponse);
controller.newOrderFromTicket();
$httpBackend.flush();
-
- expect(window.open).toHaveBeenCalledWith('/somePath', '_blank');
});
});
diff --git a/modules/travel/back/methods/travel/extraCommunityFilter.js b/modules/travel/back/methods/travel/extraCommunityFilter.js
index dcb704ff5..2f3f998d6 100644
--- a/modules/travel/back/methods/travel/extraCommunityFilter.js
+++ b/modules/travel/back/methods/travel/extraCommunityFilter.js
@@ -1,4 +1,3 @@
-
const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
const buildFilter = require('vn-loopback/util/filter').buildFilter;
const mergeFilters = require('vn-loopback/util/filter').mergeFilters;
@@ -87,7 +86,7 @@ module.exports = Self => {
return /^\d+$/.test(value)
? {'t.id': value}
: {'t.ref': {like: `%${value}%`}};
- case 'ref':
+ case 'reference':
return {'t.ref': {like: `%${value}%`}};
case 'shippedFrom':
return {'t.shipped': {gte: value}};
@@ -115,42 +114,39 @@ module.exports = Self => {
`CREATE TEMPORARY TABLE tmp.travel
(INDEX (id))
ENGINE = MEMORY
- SELECT
- t.id,
+ SELECT t.id,
t.ref,
t.shipped,
t.landed,
t.kg,
- am.id AS agencyModeFk,
- am.name AS agencyModeName,
- wo.id AS warehouseOutFk,
- wo.name AS warehouseOutName,
- w.name AS warehouseInFk,
- w.name AS warehouseInName,
- SUM(b.stickers) AS stickers,
- s.id AS cargoSupplierFk,
- s.nickname AS cargoSupplierNickname,
- s.name AS supplierName,
- CAST(SUM(b.weight * b.stickers) as DECIMAL(10,0)) as loadedKg,
+ am.id agencyModeFk,
+ am.name agencyModeName,
+ wo.id warehouseOutFk,
+ wo.name warehouseOutName,
+ w.name warehouseInFk,
+ w.name warehouseInName,
+ SUM(b.stickers) stickers,
+ s.id cargoSupplierFk,
+ s.nickname cargoSupplierNickname,
+ s.name supplierName,
+ CAST(SUM(b.weight * b.stickers) AS DECIMAL(10,0)) loadedKg,
CAST(
SUM(
- vc.aerealVolumetricDensity *
- b.stickers *
+ vc.aerealVolumetricDensity *
+ b.stickers *
IF(pkg.volume, pkg.volume, pkg.width * pkg.depth * pkg.height) / 1000000
- ) as DECIMAL(10,0)
- ) as volumeKg,
- GREATEST(
- CAST(SUM(b.weight * b.stickers) AS INT),
- CAST(
- SUM(vc.aerealVolumetricDensity *
- b.stickers *
+ ) AS DECIMAL(10,0)
+ ) volumeKg,
+ CAST(
+ GREATEST(
+ SUM(b.weight * b.stickers) ,
+ SUM(vc.aerealVolumetricDensity *
+ b.stickers *
IF(pkg.volume,
pkg.volume,
- pkg.width * pkg.depth * pkg.height
- ) / 1000000
- ) AS INT
- )
- / t.kg * 100, 0) percentageKg
+ pkg.width * pkg.depth * pkg.height) / 1000000)
+ ) / t.kg * 100 AS INT
+ ) percentageKg
FROM travel t
LEFT JOIN supplier s ON s.id = t.cargoSupplierFk
LEFT JOIN entry e ON e.travelFk = t.id
@@ -189,11 +185,12 @@ module.exports = Self => {
CAST(SUM(b.weight * b.stickers) AS DECIMAL(10,0)) as loadedkg,
CAST(
SUM(
- vc.aerealVolumetricDensity *
- b.stickers *
+ vc.aerealVolumetricDensity *
+ b.stickers *
IF(pkg.volume, pkg.volume, pkg.width * pkg.depth * pkg.height) / 1000000
) AS DECIMAL(10,0)
- ) as volumeKg
+ ) as volumeKg,
+ MAX(i.isCustomInspectionRequired) isCustomInspectionRequired
FROM tmp.travel tr
JOIN entry e ON e.travelFk = tr.id
JOIN buy b ON b.entryFk = e.id
diff --git a/modules/travel/back/methods/travel/filter.js b/modules/travel/back/methods/travel/filter.js
index e24a7659c..30c1a45fa 100644
--- a/modules/travel/back/methods/travel/filter.js
+++ b/modules/travel/back/methods/travel/filter.js
@@ -83,6 +83,14 @@ module.exports = Self => {
arg: 'daysOnward',
type: 'number',
description: 'The days onward'
+ }, {
+ arg: 'shipped',
+ type: 'date',
+ description: 'The shipped date'
+ }, {
+ arg: 'landed',
+ type: 'date',
+ description: 'The landed date'
}
],
returns: {
@@ -108,6 +116,10 @@ module.exports = Self => {
: {'t.ref': {like: `%${value}%`}};
case 'ref':
return {'t.ref': {like: `%${value}%`}};
+ case 'shipped':
+ return {'t.shipped': value};
+ case 'landed':
+ return {'t.landed': value};
case 'shippedFrom':
return {'t.shipped': {gte: value}};
case 'shippedTo':
@@ -117,7 +129,6 @@ module.exports = Self => {
case 'landedTo':
return {'t.landed': {lte: value}};
case 'daysOnward':
-
today.setHours(0, 0, 0, 0);
future.setDate(today.getDate() + value);
future.setHours(23, 59, 59, 999);
@@ -155,6 +166,8 @@ module.exports = Self => {
t.landingHour,
t.cargoSupplierFk,
t.totalEntries,
+ t.isRaid,
+ t.daysInForward,
am.name agencyModeName,
win.name warehouseInName,
wout.name warehouseOutName,
diff --git a/modules/travel/back/methods/travel/getTravel.js b/modules/travel/back/methods/travel/getTravel.js
index 171b64db1..59d30a0c7 100644
--- a/modules/travel/back/methods/travel/getTravel.js
+++ b/modules/travel/back/methods/travel/getTravel.js
@@ -44,7 +44,6 @@ module.exports = Self => {
],
};
- let travel = await Self.app.models.Travel.findOne(filter);
- return travel;
+ return Self.app.models.Travel.findOne(filter);
};
};
diff --git a/modules/travel/back/methods/travel/specs/extraCommunityFilter.spec.js b/modules/travel/back/methods/travel/specs/extraCommunityFilter.spec.js
index 7e90c7681..8fa013fe4 100644
--- a/modules/travel/back/methods/travel/specs/extraCommunityFilter.spec.js
+++ b/modules/travel/back/methods/travel/specs/extraCommunityFilter.spec.js
@@ -112,4 +112,17 @@ describe('Travel extraCommunityFilter()', () => {
expect(result.length).toEqual(2);
});
+
+ it('should return field isCustomInspectionRequired true', async() => {
+ const ctx = {
+ args: {
+ id: 2
+ }
+ };
+
+ const result = await app.models.Travel.extraCommunityFilter(ctx, filter);
+
+ expect(result[0].entries[0].isCustomInspectionRequired).toBeTruthy();
+ expect(result[0].entries[1].isCustomInspectionRequired).toBeFalsy();
+ });
});
diff --git a/modules/travel/back/methods/travel/specs/getEntries.spec.js b/modules/travel/back/methods/travel/specs/getEntries.spec.js
index fcaa80d02..9286a9d55 100644
--- a/modules/travel/back/methods/travel/specs/getEntries.spec.js
+++ b/modules/travel/back/methods/travel/specs/getEntries.spec.js
@@ -3,9 +3,10 @@ const models = require('vn-loopback/server/server').models;
describe('travel getEntries()', () => {
const travelId = 1;
it('should check the response contains the id', async() => {
- const entries = await models.Travel.getEntries(travelId);
+ const result = await models.Travel.getEntries(travelId);
+ const entries = await models.Entry.find({where: {travelFk: travelId}});
- expect(entries.length).toEqual(1);
+ expect(entries.length).toEqual(result.length);
expect(entries[0].id).toEqual(1);
});
diff --git a/modules/travel/back/models/travel.json b/modules/travel/back/models/travel.json
index 0ebf683e7..a2a9e478e 100644
--- a/modules/travel/back/models/travel.json
+++ b/modules/travel/back/models/travel.json
@@ -50,6 +50,12 @@
},
"landingHour": {
"type": "string"
+ },
+ "isRaid": {
+ "type": "boolean"
+ },
+ "daysInForward": {
+ "type": "number"
}
},
"relations": {
diff --git a/modules/travel/front/basic-data/index.html b/modules/travel/front/basic-data/index.html
deleted file mode 100644
index 783208d9a..000000000
--- a/modules/travel/front/basic-data/index.html
+++ /dev/null
@@ -1,92 +0,0 @@
-
-
-
-
-
-
diff --git a/modules/travel/front/basic-data/index.js b/modules/travel/front/basic-data/index.js
deleted file mode 100644
index 581fd71e5..000000000
--- a/modules/travel/front/basic-data/index.js
+++ /dev/null
@@ -1,21 +0,0 @@
-import ngModule from '../module';
-import Section from 'salix/components/section';
-
-class Controller extends Section {
- onSubmit() {
- return this.$.watcher.submit().then(() =>
- this.card.reload()
- );
- }
-}
-
-ngModule.vnComponent('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
deleted file mode 100644
index 11894d6e0..000000000
--- a/modules/travel/front/basic-data/index.spec.js
+++ /dev/null
@@ -1,28 +0,0 @@
-import './index.js';
-
-describe('Travel Component vnTravelBasicData', () => {
- let controller;
-
- beforeEach(angular.mock.module('travel', $translateProvider => {
- $translateProvider.translations('en', {});
- }));
-
- beforeEach(inject($componentController => {
- const $element = angular.element(' ');
- controller = $componentController('vnTravelBasicData', {$element});
- controller.card = {reload: () => {}};
- controller.$.watcher = {submit: () => {}};
- }));
-
- describe('onSubmit()', () => {
- it('should call the card reload method after the watcher submits', done => {
- jest.spyOn(controller.card, 'reload');
- jest.spyOn(controller.$.watcher, 'submit').mockReturnValue(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
deleted file mode 100644
index d95675612..000000000
--- a/modules/travel/front/basic-data/locale/es.yml
+++ /dev/null
@@ -1 +0,0 @@
-Undo changes: Deshacer cambios
diff --git a/modules/travel/front/card/index.html b/modules/travel/front/card/index.html
deleted file mode 100644
index 91964be21..000000000
--- a/modules/travel/front/card/index.html
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
diff --git a/modules/travel/front/card/index.js b/modules/travel/front/card/index.js
deleted file mode 100644
index d46244cb5..000000000
--- a/modules/travel/front/card/index.js
+++ /dev/null
@@ -1,31 +0,0 @@
-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.vnComponent('vnTravelCard', {
- template: require('./index.html'),
- controller: Controller
-});
-
diff --git a/modules/travel/front/create/index.html b/modules/travel/front/create/index.html
deleted file mode 100644
index 593887a22..000000000
--- a/modules/travel/front/create/index.html
+++ /dev/null
@@ -1,61 +0,0 @@
-
-
-
diff --git a/modules/travel/front/create/index.js b/modules/travel/front/create/index.js
deleted file mode 100644
index a85917ca8..000000000
--- a/modules/travel/front/create/index.js
+++ /dev/null
@@ -1,48 +0,0 @@
-import ngModule from '../module';
-import Section from 'salix/components/section';
-
-class Controller extends Section {
- $onChanges() {
- if (this.$params && this.$params.q)
- this.travel = JSON.parse(this.$params.q);
- }
-
- onShippedChange(value) {
- let hasFilledProperties;
- let hasAgencyMode;
- if (this.travel) {
- hasAgencyMode = Boolean(this.travel.agencyModeFk);
- hasFilledProperties = this.travel.landed || this.travel.warehouseInFk || this.travel.warehouseOutFk;
- }
- if (!hasAgencyMode || hasFilledProperties)
- return;
-
- const query = `travels/getAverageDays`;
- const params = {
- agencyModeFk: this.travel.agencyModeFk
- };
- this.$http.get(query, {params}).then(res => {
- if (!res.data)
- return;
-
- const landed = new Date(value);
- const futureDate = landed.getDate() + res.data.dayDuration;
- landed.setDate(futureDate);
-
- this.travel.landed = landed;
- this.travel.warehouseInFk = res.data.warehouseInFk;
- this.travel.warehouseOutFk = res.data.warehouseOutFk;
- });
- }
-
- onSubmit() {
- return this.$.watcher.submit().then(
- res => this.$state.go('travel.card.basicData', {id: res.data.id})
- );
- }
-}
-
-ngModule.vnComponent('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
deleted file mode 100644
index cdff8cfb9..000000000
--- a/modules/travel/front/create/index.spec.js
+++ /dev/null
@@ -1,88 +0,0 @@
-import './index';
-import watcher from 'core/mocks/watcher';
-
-describe('Travel Component vnTravelCreate', () => {
- let $scope;
- let $state;
- let controller;
- let $httpBackend;
-
- beforeEach(ngModule('travel'));
-
- beforeEach(inject(($componentController, $rootScope, _$state_, _$httpBackend_) => {
- $httpBackend = _$httpBackend_;
- $scope = $rootScope.$new();
- $state = _$state_;
- $scope.watcher = watcher;
- const $element = angular.element(' ');
- controller = $componentController('vnTravelCreate', {$element, $scope});
- }));
-
- describe('onSubmit()', () => {
- it(`should call submit() on the watcher then expect a callback`, () => {
- jest.spyOn($state, 'go');
-
- controller.onSubmit();
-
- expect(controller.$state.go).toHaveBeenCalledWith('travel.card.basicData', {id: 1234});
- });
- });
-
- describe('$onChanges()', () => {
- it('should update the travel data when $params.q is defined', () => {
- controller.$params = {q: '{"ref": 1,"agencyModeFk": 1}'};
-
- const params = {q: '{"ref": 1, "agencyModeFk": 1}'};
- const json = JSON.parse(params.q);
-
- controller.$onChanges();
-
- expect(controller.travel).toEqual(json);
- });
- });
-
- describe('onShippedChange()', () => {
- it(`should do nothing if there's no agencyModeFk in the travel.`, () => {
- controller.travel = {};
- controller.onShippedChange();
-
- expect(controller.travel.landed).toBeUndefined();
- expect(controller.travel.warehouseInFk).toBeUndefined();
- expect(controller.travel.warehouseOutFk).toBeUndefined();
- });
-
- it(`should do nothing if there's no response data.`, () => {
- controller.travel = {agencyModeFk: 4};
- const tomorrow = Date.vnNew();
-
- const query = `travels/getAverageDays?agencyModeFk=${controller.travel.agencyModeFk}`;
- $httpBackend.expectGET(query).respond(undefined);
- controller.onShippedChange(tomorrow);
- $httpBackend.flush();
-
- expect(controller.travel.warehouseInFk).toBeUndefined();
- expect(controller.travel.warehouseOutFk).toBeUndefined();
- expect(controller.travel.dayDuration).toBeUndefined();
- });
-
- it(`should fill the fields when it's selected a date and agency.`, () => {
- controller.travel = {agencyModeFk: 1};
- const tomorrow = Date.vnNew();
- tomorrow.setDate(tomorrow.getDate() + 9);
- const expectedResponse = {
- id: 8,
- dayDuration: 9,
- warehouseInFk: 5,
- warehouseOutFk: 1
- };
-
- const query = `travels/getAverageDays?agencyModeFk=${controller.travel.agencyModeFk}`;
- $httpBackend.expectGET(query).respond(expectedResponse);
- controller.onShippedChange(tomorrow);
- $httpBackend.flush();
-
- expect(controller.travel.warehouseInFk).toEqual(expectedResponse.warehouseInFk);
- expect(controller.travel.warehouseOutFk).toEqual(expectedResponse.warehouseOutFk);
- });
- });
-});
diff --git a/modules/travel/front/descriptor-menu/index.html b/modules/travel/front/descriptor-menu/index.html
deleted file mode 100644
index 19831860b..000000000
--- a/modules/travel/front/descriptor-menu/index.html
+++ /dev/null
@@ -1,59 +0,0 @@
-
-
-
-
-
- Clone travel
-
-
- Clone travel and his entries
-
-
- Delete travel
-
-
- Add entry
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/modules/travel/front/descriptor-menu/index.js b/modules/travel/front/descriptor-menu/index.js
deleted file mode 100644
index f68502ec3..000000000
--- a/modules/travel/front/descriptor-menu/index.js
+++ /dev/null
@@ -1,95 +0,0 @@
-import ngModule from '../module';
-import Section from 'salix/components/section';
-import './style.scss';
-
-class Controller extends Section {
- constructor($element, $) {
- super($element, $);
- }
-
- get travelId() {
- return this._travelId;
- }
-
- set travelId(value) {
- this._travelId = value;
-
- if (value) this.loadData();
- }
-
- loadData() {
- const filter = {
- fields: [
- 'id',
- 'ref',
- 'shipped',
- 'landed',
- 'totalEntries',
- 'agencyModeFk',
- 'warehouseInFk',
- 'warehouseOutFk',
- 'cargoSupplierFk'
- ],
- include: [
- {
- relation: 'warehouseIn',
- scope: {
- fields: ['name']
- }
- }, {
- relation: 'warehouseOut',
- scope: {
- fields: ['name']
- }
- }
- ]
- };
- this.$http.get(`Travels/${this.travelId}`, {filter})
- .then(res => this.travel = res.data);
-
- this.$http.get(`Travels/${this.travelId}/getEntries`)
- .then(res => this.entries = res.data);
- }
-
- get isBuyer() {
- return this.aclService.hasAny(['buyer']);
- }
-
- onDeleteAccept() {
- this.$http.delete(`Travels/${this.travelId}`)
- .then(() => this.$state.go('travel.index'))
- .then(() => this.vnApp.showSuccess(this.$t('Travel deleted')));
- }
-
- onCloneAccept() {
- const params = JSON.stringify({
- ref: this.travel.ref,
- agencyModeFk: this.travel.agencyModeFk,
- shipped: this.travel.shipped,
- landed: this.travel.landed,
- warehouseInFk: this.travel.warehouseInFk,
- warehouseOutFk: this.travel.warehouseOutFk
- });
- this.$state.go('travel.create', {q: params});
- }
-
- async redirectToCreateEntry() {
- this.$state.go('home');
- window.location.href = await this.vnApp.getUrl(`entry/create?travelFk=${this.travelId}`);
- }
-
- onCloneWithEntriesAccept() {
- this.$http.post(`Travels/${this.travelId}/cloneWithEntries`)
- .then(res => this.$state.go('travel.card.basicData', {id: res.data}));
- }
-}
-
-Controller.$inject = ['$element', '$scope'];
-
-ngModule.vnComponent('vnTravelDescriptorMenu', {
- template: require('./index.html'),
- controller: Controller,
- bindings: {
- travelId: '<',
- }
-});
diff --git a/modules/travel/front/descriptor-menu/index.spec.js b/modules/travel/front/descriptor-menu/index.spec.js
deleted file mode 100644
index 40319e8e2..000000000
--- a/modules/travel/front/descriptor-menu/index.spec.js
+++ /dev/null
@@ -1,71 +0,0 @@
-import './index.js';
-
-describe('Travel Component vnTravelDescriptorMenu', () => {
- let controller;
- let $httpBackend;
- beforeEach(ngModule('travel'));
-
- beforeEach(inject(($componentController, _$httpBackend_) => {
- $httpBackend = _$httpBackend_;
- const $element = angular.element(' ');
- controller = $componentController('vnTravelDescriptorMenu', {$element});
- controller._travelId = 5;
- }));
-
- describe('onCloneAccept()', () => {
- it('should call state.go with the travel data', () => {
- jest.spyOn(controller.$state, 'go').mockReturnValue('ok');
-
- controller.travel = {
- ref: 'the ref',
- agencyModeFk: 'the agency',
- shipped: 'the shipped date',
- landed: 'the landing date',
- warehouseInFk: 'the receiver warehouse',
- warehouseOutFk: 'the sender warehouse'
- };
-
- controller.onCloneAccept();
-
- const params = JSON.stringify({
- ref: controller.travel.ref,
- agencyModeFk: controller.travel.agencyModeFk,
- shipped: controller.travel.shipped,
- landed: controller.travel.landed,
- warehouseInFk: controller.travel.warehouseInFk,
- warehouseOutFk: controller.travel.warehouseOutFk
- });
-
- expect(controller.$state.go).toHaveBeenCalledWith('travel.create', {'q': params});
- });
- });
-
- describe('onDeleteAccept()', () => {
- it('should perform a delete query', () => {
- jest.spyOn(controller.$state, 'go').mockReturnValue('ok');
- controller.travelId = 1;
-
- $httpBackend.when('GET', `Travels/${controller.travelId}`).respond(200);
- $httpBackend.when('GET', `Travels/${controller.travelId}/getEntries`).respond(200);
- $httpBackend.expect('DELETE', `Travels/${controller.travelId}`).respond(200);
- controller.onDeleteAccept();
- $httpBackend.flush();
-
- expect(controller.$state.go).toHaveBeenCalledWith('travel.index');
- });
- });
-
- describe('onCloneWithEntriesAccept()', () => {
- it('should make an HTTP query and then call to the $state.go method with the returned id', () => {
- jest.spyOn(controller.$state, 'go').mockReturnValue('ok');
-
- $httpBackend.expect('POST', `Travels/${controller.travelId}/cloneWithEntries`).respond(200, 9);
- controller.onCloneWithEntriesAccept();
- $httpBackend.flush();
-
- expect(controller.$state.go).toHaveBeenCalledWith('travel.card.basicData', {
- id: jasmine.any(Number)
- });
- });
- });
-});
diff --git a/modules/travel/front/descriptor-menu/locale/es.yml b/modules/travel/front/descriptor-menu/locale/es.yml
deleted file mode 100644
index e019d1769..000000000
--- a/modules/travel/front/descriptor-menu/locale/es.yml
+++ /dev/null
@@ -1,8 +0,0 @@
-Clone travel: Clonar envío
-Add entry: Añadir entrada
-Clone travel and his entries: Clonar travel y sus entradas
-Do you want to clone this travel and all containing entries?: ¿Quieres clonar este travel y todas las entradas que contiene?
-Delete travel: Eliminar envío
-The travel will be deleted: El envío será eliminado
-Do you want to delete this travel?: ¿Quieres eliminar este envío?
-Travel deleted: Envío eliminado
\ No newline at end of file
diff --git a/modules/travel/front/descriptor-menu/style.scss b/modules/travel/front/descriptor-menu/style.scss
deleted file mode 100644
index beab9335e..000000000
--- a/modules/travel/front/descriptor-menu/style.scss
+++ /dev/null
@@ -1,24 +0,0 @@
-@import "./effects";
-@import "variables";
-
-vn-travel-descriptor-menu {
- & > vn-icon-button[icon="more_vert"] {
- display: flex;
- min-width: 45px;
- height: 45px;
- box-sizing: border-box;
- align-items: center;
- justify-content: center;
- }
- & > vn-icon-button[icon="more_vert"] {
- @extend %clickable;
- color: inherit;
-
- & > vn-icon {
- padding: 10px;
- }
- vn-icon {
- font-size: 1.75rem;
- }
- }
-}
\ No newline at end of file
diff --git a/modules/travel/front/descriptor-popover/index.html b/modules/travel/front/descriptor-popover/index.html
deleted file mode 100644
index 376423bbc..000000000
--- a/modules/travel/front/descriptor-popover/index.html
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/modules/travel/front/descriptor/index.html b/modules/travel/front/descriptor/index.html
deleted file mode 100644
index bbf5721fd..000000000
--- a/modules/travel/front/descriptor/index.html
+++ /dev/null
@@ -1,48 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/modules/travel/front/descriptor/index.js b/modules/travel/front/descriptor/index.js
deleted file mode 100644
index b1f2f53be..000000000
--- a/modules/travel/front/descriptor/index.js
+++ /dev/null
@@ -1,63 +0,0 @@
-import ngModule from '../module';
-import Descriptor from 'salix/components/descriptor';
-
-class Controller extends Descriptor {
- get travel() {
- return this.entity;
- }
-
- set travel(value) {
- this.entity = value;
- }
-
- get travelFilter() {
- let travelFilter;
- const travel = this.travel;
-
- if (travel && travel.agencyModeFk) {
- travelFilter = this.travel && JSON.stringify({
- agencyModeFk: this.travel.agencyModeFk
- });
- }
- return travelFilter;
- }
-
- loadData() {
- const filter = {
- fields: [
- 'id',
- 'ref',
- 'shipped',
- 'landed',
- 'totalEntries',
- 'warehouseInFk',
- 'warehouseOutFk',
- 'cargoSupplierFk'
- ],
- include: [
- {
- relation: 'warehouseIn',
- scope: {
- fields: ['name']
- }
- }, {
- relation: 'warehouseOut',
- scope: {
- fields: ['name']
- }
- }
- ]
- };
-
- return this.getData(`Travels/${this.id}`, {filter})
- .then(res => this.entity = res.data);
- }
-}
-
-ngModule.vnComponent('vnTravelDescriptor', {
- template: require('./index.html'),
- controller: Controller,
- bindings: {
- travel: '<'
- }
-});
diff --git a/modules/travel/front/descriptor/index.spec.js b/modules/travel/front/descriptor/index.spec.js
deleted file mode 100644
index 0a88c8607..000000000
--- a/modules/travel/front/descriptor/index.spec.js
+++ /dev/null
@@ -1,26 +0,0 @@
-import './index.js';
-
-describe('vnTravelDescriptor', () => {
- let controller;
- let $httpBackend;
-
- beforeEach(ngModule('travel'));
-
- beforeEach(inject(($componentController, _$httpBackend_) => {
- $httpBackend = _$httpBackend_;
- controller = $componentController('vnTravelDescriptor', {$element: null});
- }));
-
- describe('loadData()', () => {
- it(`should perform a get query to store the worker data into the controller`, () => {
- const id = 1;
- const response = 'foo';
-
- $httpBackend.expectRoute('GET', `Travels/${id}`).respond(response);
- controller.id = id;
- $httpBackend.flush();
-
- expect(controller.travel).toEqual(response);
- });
- });
-});
diff --git a/modules/travel/front/descriptor/locale/es.yml b/modules/travel/front/descriptor/locale/es.yml
deleted file mode 100644
index 3e6d62735..000000000
--- a/modules/travel/front/descriptor/locale/es.yml
+++ /dev/null
@@ -1,6 +0,0 @@
-Reference: Referencia
-Wh. In: Alm. entrada
-Wh. Out: Alm. salida
-Shipped: F. envío
-Landed: F. entrega
-Total entries: Entradas totales
\ No newline at end of file
diff --git a/modules/travel/front/extra-community-search-panel/index.html b/modules/travel/front/extra-community-search-panel/index.html
deleted file mode 100644
index c0d726718..000000000
--- a/modules/travel/front/extra-community-search-panel/index.html
+++ /dev/null
@@ -1,92 +0,0 @@
-
-
-
-
-
diff --git a/modules/travel/front/extra-community-search-panel/index.js b/modules/travel/front/extra-community-search-panel/index.js
deleted file mode 100644
index 1add11dce..000000000
--- a/modules/travel/front/extra-community-search-panel/index.js
+++ /dev/null
@@ -1,31 +0,0 @@
-import ngModule from '../module';
-import SearchPanel from 'core/components/searchbar/search-panel';
-
-class Controller extends SearchPanel {
- constructor($, $element) {
- super($, $element);
-
- this.filter = this.$.filter;
- }
-
- get shippedFrom() {
- return this.filter.shippedFrom;
- }
-
- set shippedFrom(value) {
- this.filter.shippedFrom = value;
- }
-
- get landedTo() {
- return this.filter.landedTo;
- }
-
- set landedTo(value) {
- this.filter.landedTo = value;
- }
-}
-
-ngModule.vnComponent('vnExtraCommunitySearchPanel', {
- template: require('./index.html'),
- controller: Controller
-});
diff --git a/modules/travel/front/extra-community/index.html b/modules/travel/front/extra-community/index.html
deleted file mode 100644
index 8132bddb1..000000000
--- a/modules/travel/front/extra-community/index.html
+++ /dev/null
@@ -1,189 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Id
-
-
- Supplier
-
-
- Agency
-
-
- Amount
-
-
- Reference
-
-
- Packages
-
-
- Bl. KG
-
-
- Phy. KG
-
-
- Vol. KG
-
-
- Wh. Out
-
-
- W. Shipped
-
-
- Wh. In
-
-
- W. Landed
-
-
-
-
-
-
-
-
- {{::entry.id}}
-
-
-
-
- {{::entry.supplierName}}
-
-
- {{::entry.invoiceAmount | currency: 'EUR': 2}}
-
- {{::entry.reference}}
- {{::entry.stickers}}
-
- {{::entry.loadedkg}}
- {{::entry.volumeKg}}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/modules/travel/front/extra-community/index.js b/modules/travel/front/extra-community/index.js
deleted file mode 100644
index 6e9c39f43..000000000
--- a/modules/travel/front/extra-community/index.js
+++ /dev/null
@@ -1,162 +0,0 @@
-import ngModule from '../module';
-import Section from 'salix/components/section';
-import './style.scss';
-
-class Controller extends Section {
- constructor($element, $, vnReport) {
- super($element, $);
-
- this.vnReport = vnReport;
-
- const draggable = this.element.querySelector('.travel-list');
- draggable.addEventListener('dragstart',
- event => this.dragStart(event));
- draggable.addEventListener('dragend',
- event => this.dragEnd(event));
-
- draggable.addEventListener('dragover',
- event => this.dragOver(event));
- draggable.addEventListener('dragenter',
- event => this.dragEnter(event));
- draggable.addEventListener('dragleave',
- event => this.dragLeave(event));
-
- this.draggableElement = 'tr[draggable]';
- this.droppableElement = 'tbody[vn-droppable]';
-
- const twoDays = 2;
- const shippedFrom = Date.vnNew();
- shippedFrom.setDate(shippedFrom.getDate() - twoDays);
- shippedFrom.setHours(0, 0, 0, 0);
-
- const sevenDays = 7;
- const landedTo = Date.vnNew();
- landedTo.setDate(landedTo.getDate() + sevenDays);
- landedTo.setHours(23, 59, 59, 59);
-
- this.defaultFilter = {
- shippedFrom: shippedFrom,
- landedTo: landedTo,
- continent: 'AM'
- };
-
- this.smartTableOptions = {};
- }
-
- onDragInterval() {
- if (this.dragClientY > 0 && this.dragClientY < 75)
- this.$window.scrollTo(0, this.$window.scrollY - 10);
-
- const maxHeight = window.screen.availHeight - (window.outerHeight - window.innerHeight);
- if (this.dragClientY > maxHeight - 75 && this.dragClientY < maxHeight)
- this.$window.scrollTo(0, this.$window.scrollY + 10);
- }
-
- findDraggable($event) {
- const target = $event.target;
- const draggable = target.closest(this.draggableElement);
-
- return draggable;
- }
-
- findDroppable($event) {
- const target = $event.target;
- const droppable = target.closest(this.droppableElement);
-
- return droppable;
- }
-
- dragStart($event) {
- const draggable = this.findDraggable($event);
- draggable.classList.add('dragging');
-
- const id = parseInt(draggable.id);
- this.entryId = id;
- this.entry = draggable;
- this.interval = setInterval(() => this.onDragInterval(), 50);
- }
-
- dragEnd($event) {
- const draggable = this.findDraggable($event);
- draggable.classList.remove('dragging');
- this.entryId = null;
- this.entry = null;
-
- clearInterval(this.interval);
- }
-
- onDrop($event) {
- const model = this.$.model;
- const droppable = this.findDroppable($event);
- const travelId = parseInt(droppable.id);
-
- const currentDroppable = this.entry.closest(this.droppableElement);
-
- if (currentDroppable == droppable) return;
-
- if (this.entryId && travelId) {
- const path = `Entries/${this.entryId}`;
- this.$http.patch(path, {travelFk: travelId})
- .then(() => model.refresh())
- .then(() => this.vnApp.showSuccess(this.$t('Data saved!')));
- }
- }
-
- undrop() {
- if (!this.dropping) return;
- this.dropping.classList.remove('dropping');
- this.dropping = null;
- }
-
- dragOver($event) {
- this.dragClientY = $event.clientY;
- $event.preventDefault();
- }
-
- 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();
- }
- }
-
- save(id, data) {
- const endpoint = `Travels/${id}`;
- this.$http.patch(endpoint, data)
- .then(() => this.vnApp.showSuccess(this.$t('Data saved!')));
- }
-
- get reportParams() {
- const userParams = this.$.model.userParams;
- const currentFilter = this.$.model.currentFilter;
-
- return Object.assign({
- authorization: this.vnToken.tokenMultimedia,
- filter: currentFilter
- }, userParams);
- }
-
- showReport() {
- this.vnReport.show(`Travels/extra-community-pdf`, this.reportParams);
- }
-}
-
-Controller.$inject = ['$element', '$scope', 'vnReport'];
-
-ngModule.vnComponent('vnTravelExtraCommunity', {
- template: require('./index.html'),
- controller: Controller
-});
diff --git a/modules/travel/front/extra-community/index.spec.js b/modules/travel/front/extra-community/index.spec.js
deleted file mode 100644
index 18ddee665..000000000
--- a/modules/travel/front/extra-community/index.spec.js
+++ /dev/null
@@ -1,128 +0,0 @@
-import './index.js';
-
-describe('Travel Component vnTravelExtraCommunity', () => {
- let controller;
- let $httpBackend;
-
- beforeEach(ngModule('travel'));
-
- beforeEach(inject(($componentController, _$httpBackend_) => {
- $httpBackend = _$httpBackend_;
- const $element = angular.element('
');
- controller = $componentController('vnTravelExtraCommunity', {$element});
- controller.$.model = {};
- controller.$.model.refresh = jest.fn();
- }));
-
- describe('findDraggable()', () => {
- it('should find the draggable element', () => {
- const draggable = document.createElement('tr');
- draggable.setAttribute('draggable', true);
-
- const $event = new Event('dragstart');
- const target = document.createElement('div');
- draggable.appendChild(target);
- target.dispatchEvent($event);
-
- const result = controller.findDraggable($event);
-
- expect(result).toEqual(draggable);
- });
- });
-
- describe('findDroppable()', () => {
- it('should find the droppable element', () => {
- const droppable = document.createElement('tbody');
- droppable.setAttribute('vn-droppable', true);
-
- const $event = new Event('drop');
- const target = document.createElement('div');
- droppable.appendChild(target);
- target.dispatchEvent($event);
-
- const result = controller.findDroppable($event);
-
- expect(result).toEqual(droppable);
- });
- });
-
- describe('dragStart()', () => {
- it(`should add the class "dragging" to the draggable element
- and then set the entryId controller property`, () => {
- const draggable = document.createElement('tr');
- draggable.setAttribute('draggable', true);
- draggable.setAttribute('id', 3);
-
- jest.spyOn(controller, 'findDraggable').mockReturnValue(draggable);
-
- const $event = new Event('dragStart');
- controller.dragStart($event);
-
- const firstClass = draggable.classList[0];
-
- expect(firstClass).toEqual('dragging');
- expect(controller.entryId).toEqual(3);
- expect(controller.entry).toEqual(draggable);
- });
- });
-
- describe('dragEnd()', () => {
- it(`should remove the class "dragging" from the draggable element
- and then set the entryId controller property to null`, () => {
- const draggable = document.createElement('tr');
- draggable.setAttribute('draggable', true);
- draggable.setAttribute('id', 3);
- draggable.classList.add('dragging');
-
- jest.spyOn(controller, 'findDraggable').mockReturnValue(draggable);
-
- const $event = new Event('dragStart');
- controller.dragEnd($event);
-
- const classList = draggable.classList;
-
- expect(classList.length).toEqual(0);
- expect(controller.entryId).toBeNull();
- expect(controller.entry).toBeNull();
- });
- });
-
- describe('onDrop()', () => {
- it('should make an HTTP patch query', () => {
- const droppable = document.createElement('tbody');
- droppable.setAttribute('vn-droppable', true);
- droppable.setAttribute('id', 1);
-
- jest.spyOn(controller, 'findDroppable').mockReturnValue(droppable);
-
- const oldDroppable = document.createElement('tbody');
- oldDroppable.setAttribute('vn-droppable', true);
- const entry = document.createElement('div');
- oldDroppable.appendChild(entry);
-
- controller.entryId = 3;
- controller.entry = entry;
-
- const $event = new Event('drop');
- const expectedData = {travelFk: 1};
- $httpBackend.expect('PATCH', `Entries/3`, expectedData).respond(200);
- controller.onDrop($event);
- $httpBackend.flush();
- });
- });
-
- describe('save()', () => {
- it('should make an HTTP query', () => {
- jest.spyOn(controller.vnApp, 'showSuccess');
-
- const travelId = 1;
- const data = {ref: 'New reference'};
- const expectedData = {ref: 'New reference'};
- $httpBackend.expect('PATCH', `Travels/${travelId}`, expectedData).respond(200);
- controller.save(travelId, data);
- $httpBackend.flush();
-
- expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!');
- });
- });
-});
diff --git a/modules/travel/front/extra-community/locale/es.yml b/modules/travel/front/extra-community/locale/es.yml
deleted file mode 100644
index ed6179c91..000000000
--- a/modules/travel/front/extra-community/locale/es.yml
+++ /dev/null
@@ -1,11 +0,0 @@
-Family: Familia
-Extra community: Extra comunitarios
-Freighter: Transitario
-Bl. KG: KG Bloq.
-Phy. KG: KG físico
-Vol. KG: KG Vol.
-Search by travel id or reference: Buscar por id de travel o referencia
-Search by extra community travel: Buscar por envío extra comunitario
-Continent Out: Cont. salida
-W. Shipped: F. envío
-W. Landed: F. llegada
diff --git a/modules/travel/front/extra-community/style.scss b/modules/travel/front/extra-community/style.scss
deleted file mode 100644
index fb64822f9..000000000
--- a/modules/travel/front/extra-community/style.scss
+++ /dev/null
@@ -1,67 +0,0 @@
-@import "variables";
-
-vn-travel-extra-community {
- .header {
- margin-bottom: 16px;
- line-height: 1;
- padding: 7px;
- padding-bottom: 7px;
- padding-bottom: 4px;
- font-weight: lighter;
- background-color: $color-bg;
- color: white;
- border-bottom: 1px solid #f7931e;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- cursor: pointer;
- .multi-line{
- padding-top: 15px;
- padding-bottom: 15px;
- }
- }
-
- table[vn-droppable] {
- border-radius: 0;
- }
-
- tr[draggable] {
- transition: all .5s;
- cursor: move;
- overflow: auto;
- outline: 0;
- height: 65px;
- pointer-events: fill;
- user-select: all;
- }
-
- tr[draggable] *::selection {
- background-color: transparent;
- }
-
- tr[draggable]:hover {
- background-color: $color-hover-cd;
- }
-
- tr[draggable].dragging {
- background-color: $color-primary-light;
- color: $color-font-light;
- font-weight: bold;
- }
-
-
- .multi-line{
- max-width: 200px;
- word-wrap: normal;
- white-space: normal;
- }
-
- vn-td-editable text {
- background-color: transparent;
- padding: 0;
- border: 0;
- border-bottom: 1px dashed $color-active;
- border-radius: 0;
- color: $color-active
- }
-}
diff --git a/modules/travel/front/index.js b/modules/travel/front/index.js
index e4375c59d..a7209a0bd 100644
--- a/modules/travel/front/index.js
+++ b/modules/travel/front/index.js
@@ -1,18 +1,3 @@
export * from './module';
import './main';
-import './index/';
-import './search-panel';
-import './descriptor';
-import './card';
-import './summary';
-import './basic-data';
-import './log';
-import './create';
-import './thermograph/index/';
-import './thermograph/create/';
-import './thermograph/edit/';
-import './descriptor-popover';
-import './descriptor-menu';
-import './extra-community';
-import './extra-community-search-panel';
diff --git a/modules/travel/front/index/index.html b/modules/travel/front/index/index.html
deleted file mode 100644
index a768e4a29..000000000
--- a/modules/travel/front/index/index.html
+++ /dev/null
@@ -1,107 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
- Reference
- Agency
- Warehouse Out
- Shipped
-
- Warehouse In
- Landed
-
- Total entries
-
-
-
-
-
- {{::travel.ref}}
- {{::travel.agencyModeName}}
- {{::travel.warehouseOutName}}
-
-
- {{::travel.shipped | date:'dd/MM/yyyy'}}
-
-
-
-
-
-
- {{::travel.warehouseInName}}
-
-
- {{::travel.landed | date:'dd/MM/yyyy'}}
-
-
-
-
-
-
- {{::travel.totalEntries}}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/modules/travel/front/index/index.js b/modules/travel/front/index/index.js
deleted file mode 100644
index a570146fe..000000000
--- a/modules/travel/front/index/index.js
+++ /dev/null
@@ -1,39 +0,0 @@
-import ngModule from '../module';
-import Section from 'salix/components/section';
-import './style.scss';
-
-export default class Controller extends Section {
- preview(travel) {
- this.travelSelected = travel;
- this.$.summary.show();
- }
-
- onCloneAccept(travel) {
- const params = JSON.stringify({
- ref: travel.ref,
- agencyModeFk: travel.agencyModeFk,
- shipped: travel.shipped,
- landed: travel.landed,
- warehouseInFk: travel.warehouseInFk,
- warehouseOutFk: travel.warehouseOutFk
- });
- this.$state.go('travel.create', {q: params});
- }
-
- compareDate(date) {
- let today = Date.vnNew();
- today.setHours(0, 0, 0, 0);
-
- date = new Date(date);
- date.setHours(0, 0, 0, 0);
-
- const timeDifference = today - date;
- if (timeDifference == 0) return 'warning';
- if (timeDifference < 0) return 'success';
- }
-}
-
-ngModule.vnComponent('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
deleted file mode 100644
index 9083c4519..000000000
--- a/modules/travel/front/index/index.spec.js
+++ /dev/null
@@ -1,78 +0,0 @@
-import './index.js';
-
-describe('Travel Component vnTravelIndex', () => {
- let controller;
- let travel = {
- id: 1,
- warehouseInFk: 1,
- totalEntries: 3,
- isDelivered: false
- };
-
- beforeEach(ngModule('travel'));
-
- beforeEach(inject($componentController => {
- const $element = angular.element(' ');
- controller = $componentController('vnTravelIndex', {$element});
- controller.$.summary = {show: jasmine.createSpy('show')};
- }));
-
- describe('preview()', () => {
- it('should show the dialog summary', () => {
- let event = new MouseEvent('click', {
- bubbles: true,
- cancelable: true
- });
- controller.preview(event, travel);
-
- expect(controller.$.summary.show).toHaveBeenCalledWith();
- });
- });
-
- describe('onCloneAccept()', () => {
- it('should call go() then update travelSelected in the controller', () => {
- jest.spyOn(controller.$state, 'go');
-
- const travel = {
- ref: 1,
- agencyModeFk: 1
- };
- const travelParams = {
- ref: travel.ref,
- agencyModeFk: travel.agencyModeFk
- };
- const queryParams = JSON.stringify(travelParams);
- controller.onCloneAccept(travel);
-
- expect(controller.$state.go).toHaveBeenCalledWith('travel.create', {q: queryParams});
- });
- });
-
- describe('compareDate()', () => {
- it('should return warning if the date passed to compareDate() is todays', () => {
- const today = Date.vnNew();
-
- const result = controller.compareDate(today);
-
- expect(result).toEqual('warning');
- });
-
- it('should return success if the date passed to compareDate() is in the future', () => {
- const tomorrow = Date.vnNew();
- tomorrow.setDate(tomorrow.getDate() + 1);
-
- const result = controller.compareDate(tomorrow);
-
- expect(result).toEqual('success');
- });
-
- it('should return undefined if the date passed to compareDate() is in the past', () => {
- const yesterday = Date.vnNew();
- yesterday.setDate(yesterday.getDate() - 1);
-
- const result = controller.compareDate(yesterday);
-
- expect(result).toBeUndefined();
- });
- });
-});
diff --git a/modules/travel/front/index/locale/es.yml b/modules/travel/front/index/locale/es.yml
deleted file mode 100644
index 5ce4c502f..000000000
--- a/modules/travel/front/index/locale/es.yml
+++ /dev/null
@@ -1,3 +0,0 @@
-Do you want to clone this travel?: ¿Desea clonar este envio?
-All it's properties will be copied: Todas sus propiedades serán copiadas
-Clone: Clonar
\ No newline at end of file
diff --git a/modules/travel/front/index/style.scss b/modules/travel/front/index/style.scss
deleted file mode 100644
index ca1cf538b..000000000
--- a/modules/travel/front/index/style.scss
+++ /dev/null
@@ -1,11 +0,0 @@
-@import "variables";
-
-vn-travel-index {
- vn-icon {
- color: $color-font-secondary
- }
-
- vn-icon.active {
- color: $color-success
- }
-}
diff --git a/modules/travel/front/log/index.html b/modules/travel/front/log/index.html
deleted file mode 100644
index fc4622e5a..000000000
--- a/modules/travel/front/log/index.html
+++ /dev/null
@@ -1 +0,0 @@
-
\ No newline at end of file
diff --git a/modules/travel/front/log/index.js b/modules/travel/front/log/index.js
deleted file mode 100644
index 7af601b5c..000000000
--- a/modules/travel/front/log/index.js
+++ /dev/null
@@ -1,7 +0,0 @@
-import ngModule from '../module';
-import Section from 'salix/components/section';
-
-ngModule.vnComponent('vnTravelLog', {
- template: require('./index.html'),
- controller: Section,
-});
diff --git a/modules/travel/front/main/index.html b/modules/travel/front/main/index.html
index 131d9409e..e69de29bb 100644
--- a/modules/travel/front/main/index.html
+++ b/modules/travel/front/main/index.html
@@ -1,6 +0,0 @@
-
-
-
-
-
-
diff --git a/modules/travel/front/main/index.js b/modules/travel/front/main/index.js
index 6a153f21a..37dcbb0dc 100644
--- a/modules/travel/front/main/index.js
+++ b/modules/travel/front/main/index.js
@@ -5,6 +5,10 @@ export default class Travel extends ModuleMain {
constructor() {
super();
}
+ async $onInit() {
+ this.$state.go('home');
+ window.location.href = await this.vnApp.getUrl(`travel/`);
+ }
}
ngModule.vnComponent('vnTravel', {
diff --git a/modules/travel/front/routes.json b/modules/travel/front/routes.json
index 5a63620d4..6891a46cf 100644
--- a/modules/travel/front/routes.json
+++ b/modules/travel/front/routes.json
@@ -3,7 +3,7 @@
"name": "Travels",
"icon": "local_airport",
"validations": true,
- "dependencies": ["worker"],
+ "dependencies": ["worker", "entry"],
"menus": {
"main": [
{"state": "travel.index", "icon": "local_airport"},
@@ -27,80 +27,6 @@
"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?q",
- "state": "travel.create",
- "component": "vn-travel-create",
- "description": "New travel"
- }, {
- "url": "/thermograph",
- "state": "travel.card.thermograph",
- "abstract": true,
- "component": "ui-view"
- }, {
- "url" : "/index",
- "state": "travel.card.thermograph.index",
- "component": "vn-travel-thermograph-index",
- "description": "Thermographs",
- "params": {
- "travel": "$ctrl.travel"
- },
- "acl": ["buyer"]
- }, {
- "url" : "/create",
- "state": "travel.card.thermograph.create",
- "component": "vn-travel-thermograph-create",
- "description": "Add thermograph",
- "params": {
- "travel": "$ctrl.travel"
- },
- "acl": ["buyer"]
- }, {
- "url" : "/:thermographId/edit",
- "state": "travel.card.thermograph.edit",
- "component": "vn-travel-thermograph-edit",
- "description": "Edit thermograph",
- "params": {
- "travel": "$ctrl.travel"
- },
- "acl": ["buyer"]
- },
- {
- "url": "/extra-community?q",
- "state": "travel.extraCommunity",
- "component": "vn-travel-extra-community",
- "description": "Extra community",
- "acl": ["buyer"],
- "params": {
- "travel": "$ctrl.travel"
- }
}
]
}
diff --git a/modules/travel/front/search-panel/index.html b/modules/travel/front/search-panel/index.html
deleted file mode 100644
index dd8d98af1..000000000
--- a/modules/travel/front/search-panel/index.html
+++ /dev/null
@@ -1,146 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Id/{{$ctrl.$t('Reference')}}: {{$ctrl.filter.search}}
-
-
- {{$ctrl.$t('Agency')}}: {{agency.selection.name}}
-
-
- {{$ctrl.$t('Warehouse Out')}}: {{warehouseOut.selection.name}}
-
-
- {{$ctrl.$t('Warehouse In')}}: {{warehouseIn.selection.name}}
-
-
- {{$ctrl.$t('Days onward')}}: {{$ctrl.filter.scopeDays}}
-
-
- {{$ctrl.$t('Landed from')}}: {{$ctrl.filter.landedFrom | date:'dd/MM/yyyy'}}
-
-
- {{$ctrl.$t('Landed to')}}: {{$ctrl.filter.landedTo | date:'dd/MM/yyyy'}}
-
-
- {{$ctrl.$t('Continent Out')}}: {{continent.selection.name}}
-
-
- {{$ctrl.$t('Total entries')}}: {{$ctrl.filter.totalEntries}}
-
-
-
diff --git a/modules/travel/front/search-panel/index.js b/modules/travel/front/search-panel/index.js
deleted file mode 100644
index 5969a8c3f..000000000
--- a/modules/travel/front/search-panel/index.js
+++ /dev/null
@@ -1,72 +0,0 @@
-import ngModule from '../module';
-import SearchPanel from 'core/components/searchbar/search-panel';
-import './style.scss';
-
-class Controller extends SearchPanel {
- constructor($, $element) {
- super($, $element);
- this.initFilter();
- this.fetchData();
- }
-
- $onChanges() {
- if (this.model)
- this.applyFilters();
- }
-
- fetchData() {
- this.$http.get('AgencyModes').then(res => {
- this.agencyModes = res.data;
- });
- this.$http.get('Warehouses').then(res => {
- this.warehouses = res.data;
- });
- this.$http.get('Continents').then(res => {
- this.continents = res.data;
- });
- }
-
- initFilter() {
- this.filter = {};
- if (this.$params.q) {
- this.filter = JSON.parse(this.$params.q);
- this.search = this.filter.search;
- this.totalEntries = this.filter.totalEntries;
- }
- if (!this.filter.scopeDays) this.filter.scopeDays = 7;
- }
-
- applyFilters(param) {
- if (this.filter?.search)
- delete this.filter.scopeDays;
-
- this.model.applyFilter({}, this.filter)
- .then(() => {
- if (param && this.model._orgData.length === 1)
- this.$state.go('travel.card.summary', {id: this.model._orgData[0].id});
- else
- this.$state.go(this.$state.current.name, {q: JSON.stringify(this.filter)}, {location: 'replace'});
- });
- }
-
- removeParamFilter(param) {
- if (this[param]) delete this[param];
- delete this.filter[param];
- this.applyFilters();
- }
-
- onKeyPress($event, param) {
- if ($event.key === 'Enter') {
- this.filter[param] = this[param];
- this.applyFilters(param === 'search');
- }
- }
-}
-
-ngModule.vnComponent('vnTravelSearchPanel', {
- template: require('./index.html'),
- controller: Controller,
- bindings: {
- model: '<'
- }
-});
diff --git a/modules/travel/front/search-panel/index.spec.js b/modules/travel/front/search-panel/index.spec.js
deleted file mode 100644
index 488143e80..000000000
--- a/modules/travel/front/search-panel/index.spec.js
+++ /dev/null
@@ -1,38 +0,0 @@
-import './index';
-
-describe('Travel Component vnTravelSearchPanel', () => {
- let controller;
-
- beforeEach(ngModule('travel'));
-
- beforeEach(inject($componentController => {
- controller = $componentController('vnTravelSearchPanel', {$element: null});
- controller.$t = () => {};
- }));
-
- describe('applyFilters()', () => {
- it('should apply filters', async() => {
- controller.filter = {foo: 'bar'};
- controller.model = {
- applyFilter: jest.fn().mockResolvedValue(),
- _orgData: [{id: 1}]
- };
- controller.$state = {
- current: {
- name: 'foo'
- },
- go: jest.fn()
- };
-
- await controller.applyFilters(true);
-
- expect(controller.model.applyFilter).toHaveBeenCalledWith({}, controller.filter);
- expect(controller.$state.go).toHaveBeenCalledWith('travel.card.summary', {id: 1});
-
- await controller.applyFilters(false);
-
- expect(controller.$state.go).toHaveBeenCalledWith(controller.$state.current.name,
- {q: JSON.stringify(controller.filter)}, {location: 'replace'});
- });
- });
-});
diff --git a/modules/travel/front/search-panel/locale/es.yml b/modules/travel/front/search-panel/locale/es.yml
deleted file mode 100644
index 1f892a742..000000000
--- a/modules/travel/front/search-panel/locale/es.yml
+++ /dev/null
@@ -1,7 +0,0 @@
-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/search-panel/style.scss b/modules/travel/front/search-panel/style.scss
deleted file mode 100644
index 0da52408a..000000000
--- a/modules/travel/front/search-panel/style.scss
+++ /dev/null
@@ -1,37 +0,0 @@
-@import "variables";
-
-vn-travel-search-panel vn-side-menu {
- .menu {
- min-width: $menu-width;
- }
- & > div {
- .input {
- padding-left: $spacing-md;
- padding-right: $spacing-md;
- border-color: $color-spacer;
- border-bottom: $border-thin;
- }
- .horizontal {
- padding-left: $spacing-md;
- padding-right: $spacing-md;
- grid-auto-flow: column;
- grid-column-gap: $spacing-sm;
- align-items: center;
- }
- .chips {
- display: flex;
- flex-wrap: wrap;
- padding: $spacing-md;
- overflow: hidden;
- max-width: 100%;
- border-color: $color-spacer;
- }
-
- .or {
- align-self: center;
- font-weight: bold;
- font-size: 26px;
- color: $color-font-secondary;
- }
- }
-}
diff --git a/modules/travel/front/summary/index.html b/modules/travel/front/summary/index.html
deleted file mode 100644
index d9dbb0f90..000000000
--- a/modules/travel/front/summary/index.html
+++ /dev/null
@@ -1,167 +0,0 @@
-
-
-
-
-
- {{$ctrl.travelData.id}} - {{$ctrl.travelData.ref}}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Entries
-
-
-
- Confirmed
- Entry Id
- Supplier
- Reference
- HB
- Freight
- Package
- CC
- Pallet
- m³
-
-
-
-
-
-
-
-
-
-
-
- {{entry.id}}
-
-
- {{entry.supplierName}}
- {{entry.reference}}
- {{entry.hb}}
- {{entry.freightValue | currency: 'EUR': 2}}
- {{entry.packageValue | currency: 'EUR': 2}}
- {{entry.cc}}
- {{entry.pallet}}
- {{entry.m3}}
-
-
-
-
-
-
-
-
-
-
-
-
- {{$ctrl.total('hb')}}
- {{$ctrl.total('freightValue') | currency: 'EUR': 2}}
- {{$ctrl.total('packageValue') | currency: 'EUR': 2}}
- {{$ctrl.total('cc') | number:2}}
- {{$ctrl.total('pallet') | number:2}}
- {{$ctrl.total('m3') | number:2}}
-
-
-
-
-
-
-
-
- Thermograph
-
-
-
-
- Code
- Temperature
- State
- Destination
- Created
-
-
-
-
- {{thermograph.thermographFk}}
- {{thermograph.temperatureFk}}
- {{thermograph.result}}
- {{thermograph.warehouse.name}}
- {{thermograph.created | date: 'dd/MM/yyyy'}}
-
-
-
-
-
-
-
-
diff --git a/modules/travel/front/summary/index.js b/modules/travel/front/summary/index.js
deleted file mode 100644
index 5144a0bb5..000000000
--- a/modules/travel/front/summary/index.js
+++ /dev/null
@@ -1,71 +0,0 @@
-import ngModule from '../module';
-import Summary from 'salix/components/summary';
-import './style.scss';
-
-class Controller extends Summary {
- $onInit() {
- this.entries = [];
- }
-
- get travel() {
- return this._travel;
- }
-
- set travel(value) {
- this._travel = value;
-
- if (value && value.id) {
- this.getTravel();
- this.getEntries();
- this.getThermographs();
- }
- }
-
- getTravel() {
- return this.$http.get(`Travels/${this.travel.id}/getTravel`)
- .then(res => this.travelData = res.data);
- }
-
- getEntries() {
- return this.$http.get(`Travels/${this.travel.id}/getEntries`)
- .then(res => this.entries = res.data);
- }
-
- getThermographs() {
- const filter = {
- include: {
- relation: 'warehouse',
- scope: {
- fields: ['id', 'name']
- }
- },
- where: {
- travelFk: this.travel.id
- }
- };
-
- return this.$http.get(`TravelThermographs`, {filter})
- .then(res => this.travelThermographs = res.data);
- }
-
- total(field) {
- let total = 0;
-
- for (let entry of this.entries)
- total += entry[field];
-
- return total;
- }
-
- get isBuyer() {
- return this.aclService.hasAny(['buyer']);
- }
-}
-
-ngModule.vnComponent('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
deleted file mode 100644
index b1b750689..000000000
--- a/modules/travel/front/summary/index.spec.js
+++ /dev/null
@@ -1,86 +0,0 @@
-import './index';
-
-describe('component vnTravelSummary', () => {
- let controller;
- let $httpBackend;
- let $scope;
- let $httpParamSerializer;
-
- beforeEach(angular.mock.module('travel', $translateProvider => {
- $translateProvider.translations('en', {});
- }));
-
- beforeEach(inject(($componentController, $rootScope, _$httpBackend_, _$httpParamSerializer_) => {
- $httpBackend = _$httpBackend_;
- $httpParamSerializer = _$httpParamSerializer_;
- $scope = $rootScope.$new();
- const $element = angular.element(` `);
- controller = $componentController('vnTravelSummary', {$element, $scope});
- }));
-
- describe('travel setter/getter', () => {
- it('should return the travel and then call both getTravel() and getEntries()', () => {
- jest.spyOn(controller, 'getTravel');
- jest.spyOn(controller, 'getEntries');
- jest.spyOn(controller, 'getThermographs');
- controller.travel = {id: 99};
-
- expect(controller._travel.id).toEqual(99);
- expect(controller.getTravel).toHaveBeenCalledWith();
- expect(controller.getEntries).toHaveBeenCalledWith();
- expect(controller.getThermographs).toHaveBeenCalledWith();
- });
- });
-
- describe('getTravel()', () => {
- it('should perform a get and then store data on the controller', () => {
- controller._travel = {id: 999};
-
- const query = `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 = `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');
- });
- });
-
- describe('getThermographs()', () => {
- it('should call the getThermographs method to get the thermographs', () => {
- controller._travel = {id: 2};
-
- $httpBackend.expectGET(`TravelThermographs`).respond('I am the thermographs');
- controller.getThermographs();
- $httpBackend.flush();
-
- expect(controller.travelThermographs).toEqual('I am the thermographs');
- });
- });
-
- describe('total()', () => {
- it('should calculate the total amount of a given property for every row', () => {
- controller.entries = [
- {id: 1, freightValue: 1, packageValue: 2, cc: 0.01},
- {id: 2, freightValue: 1, packageValue: 2, cc: 0.01},
- {id: 3, freightValue: 1, packageValue: 2, cc: 0.01}
- ];
-
- expect(controller.total('freightValue')).toEqual(3);
- expect(controller.total('packageValue')).toEqual(6);
- expect(controller.total('cc')).toEqual(0.03);
- });
- });
-});
diff --git a/modules/travel/front/summary/locale/es.yml b/modules/travel/front/summary/locale/es.yml
deleted file mode 100644
index aa6adc938..000000000
--- a/modules/travel/front/summary/locale/es.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-Reference: Referencia
-Warehouse In: Alm. entrada
-Warehouse Out: Alm. salida
-Shipped: F. envío
-Landed: F. entrega
-Total entries: Ent. totales
-Delivered: Enviada
-Received: Recibida
-Agency: Agencia
-Entries: Entradas
-Confirmed: Confirmada
-Entry Id: Id entrada
-Supplier: Proveedor
-Pallet: Pallet
-Freight: Porte
-Package: Embalaje
-Half box: Media caja
-Go to the travel: Ir al envío
diff --git a/modules/travel/front/summary/style.scss b/modules/travel/front/summary/style.scss
deleted file mode 100644
index dd4cfa72d..000000000
--- a/modules/travel/front/summary/style.scss
+++ /dev/null
@@ -1,6 +0,0 @@
-@import "variables";
-
-
-vn-travel-summary .summary {
- max-width: $width-lg;
-}
\ No newline at end of file
diff --git a/modules/travel/front/thermograph/create/index.html b/modules/travel/front/thermograph/create/index.html
deleted file mode 100644
index 41709e1fb..000000000
--- a/modules/travel/front/thermograph/create/index.html
+++ /dev/null
@@ -1,177 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Create
-
-
\ No newline at end of file
diff --git a/modules/travel/front/thermograph/create/index.js b/modules/travel/front/thermograph/create/index.js
deleted file mode 100644
index 9f0678807..000000000
--- a/modules/travel/front/thermograph/create/index.js
+++ /dev/null
@@ -1,122 +0,0 @@
-import ngModule from '../../module';
-import Section from 'salix/components/section';
-import UserError from 'core/lib/user-error';
-
-class Controller extends Section {
- constructor($element, $) {
- super($element, $);
- this.dms = {files: [], state: 'Ok'};
- }
-
- get travel() {
- return this._travel;
- }
-
- set travel(value) {
- this._travel = value;
-
- if (value) {
- this.setDefaultParams();
- this.getAllowedContentTypes();
- }
- }
-
- getAllowedContentTypes() {
- this.$http.get('DmsContainers/allowedContentTypes').then(res => {
- const contentTypes = res.data.join(', ');
- this.allowedContentTypes = contentTypes;
- });
- }
-
- get contentTypesInfo() {
- return this.$t('ContentTypesInfo', {
- allowedContentTypes: this.allowedContentTypes
- });
- }
-
- setDefaultParams() {
- const params = {filter: {
- where: {code: 'miscellaneous'}
- }};
- 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.travel.id,
- warehouseId: warehouseId,
- companyId: companyId,
- dmsTypeId: dmsTypeId,
- description: this.$t('TravelFileDescription', {
- travelId: this.travel.id
- }).toUpperCase()
- };
-
- this.dms = Object.assign(this.dms, defaultParams);
- });
- }
-
- onAddThermographClick(event) {
- const defaultTemperature = 'cool';
- const defaultModel = 'DISPOSABLE';
-
- event.preventDefault();
- this.newThermograph = {
- thermographId: this.thermographId,
- warehouseId: this.warehouseId,
- temperatureFk: defaultTemperature,
- model: defaultModel
- };
-
- this.$.modelsModel.refresh();
- this.$.newThermographDialog.show();
- }
-
- onNewThermographAccept() {
- const hasMissingField =
- !this.newThermograph.thermographId ||
- !this.newThermograph.warehouseId ||
- !this.newThermograph.temperatureFk ||
- !this.newThermograph.model;
-
- if (hasMissingField)
- throw new UserError(`Some fields are invalid`);
-
- return this.$http.post(`Thermographs/createThermograph`, this.newThermograph)
- .then(res => this.dms.thermographId = res.data.id);
- }
-
- onSubmit() {
- const query = `Travels/${this.travel.id}/saveThermograph`;
- 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 => {
- this.vnApp.showSuccess(this.$t('Data saved!'));
- this.$.watcher.updateOriginalData();
- this.$state.go('travel.card.thermograph.index');
- });
- }
-}
-
-ngModule.vnComponent('vnTravelThermographCreate', {
- template: require('./index.html'),
- controller: Controller,
- bindings: {
- travel: '<'
- }
-});
diff --git a/modules/travel/front/thermograph/create/index.spec.js b/modules/travel/front/thermograph/create/index.spec.js
deleted file mode 100644
index 1ad263d31..000000000
--- a/modules/travel/front/thermograph/create/index.spec.js
+++ /dev/null
@@ -1,108 +0,0 @@
-import './index';
-
-describe('Ticket', () => {
- describe('Component vnTravelThermographCreate', () => {
- let controller;
- let $httpBackend;
- let $httpParamSerializer;
- const travelId = 3;
- const dmsTypeId = 5;
-
- beforeEach(ngModule('travel'));
-
- beforeEach(inject(($componentController, _$httpBackend_, _$httpParamSerializer_) => {
- $httpBackend = _$httpBackend_;
- $httpParamSerializer = _$httpParamSerializer_;
- const $element = angular.element(' ');
- controller = $componentController('vnTravelThermographCreate', {$element});
- controller._travel = {
- id: travelId
- };
- }));
-
- describe('travel() setter', () => {
- it('should set the travel data and then call setDefaultParams() and getAllowedContentTypes()', () => {
- jest.spyOn(controller, 'setDefaultParams');
- jest.spyOn(controller, 'getAllowedContentTypes');
- controller.travel = {
- id: travelId
- };
-
- expect(controller.travel).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: 'miscellaneous'}
- }};
- let serializedParams = $httpParamSerializer(params);
- $httpBackend.expect('GET', `DmsTypes/findOne?${serializedParams}`).respond({id: dmsTypeId, code: 'miscellaneous'});
- controller.setDefaultParams();
- $httpBackend.flush();
-
- expect(controller.dms).toBeDefined();
- expect(controller.dms.reference).toEqual(travelId);
- expect(controller.dms.dmsTypeId).toEqual(dmsTypeId);
- });
- });
-
- describe('getAllowedContentTypes()', () => {
- it('should make an HTTP GET request to get the allowed content types', () => {
- const expectedResponse = ['application/pdf', 'image/png', 'image/jpg'];
- $httpBackend.expect('GET', `DmsContainers/allowedContentTypes`).respond(expectedResponse);
- controller.getAllowedContentTypes();
- $httpBackend.flush();
-
- expect(controller.allowedContentTypes).toBeDefined();
- expect(controller.allowedContentTypes).toEqual('application/pdf, image/png, image/jpg');
- });
- });
-
- describe('onAddThermographClick()', () => {
- it('should call the show() function of the create thermograph dialog', () => {
- controller.$.newThermographDialog = {show: jest.fn()};
- controller.$.modelsModel = {refresh: jest.fn()};
- controller.$.temperaturesModel = {refresh: jest.fn()};
-
- const event = new Event('click');
- jest.spyOn(event, 'preventDefault');
-
- controller.onAddThermographClick(event);
-
- expect(event.preventDefault).toHaveBeenCalledTimes(1);
- expect(controller.$.newThermographDialog.show).toHaveBeenCalledTimes(1);
- });
- });
-
- describe('onNewThermographAccept()', () => {
- it('should set the created thermograph data on to the controller for the autocomplete to use it', () => {
- const id = 'the created id';
- const warehouseId = 1;
- const temperatureId = 'cool';
- const model = 'my model';
-
- controller.newThermograph = {
- thermographId: id,
- warehouseId: warehouseId,
- temperatureFk: temperatureId,
- model: model
- };
- const response = {
- id: id,
- warehouseId: warehouseId,
- temperatureFk: temperatureId,
- model: model
- };
- $httpBackend.when('POST', `Thermographs/createThermograph`).respond(response);
- controller.onNewThermographAccept();
- $httpBackend.flush();
-
- expect(controller.dms.thermographId).toEqual(response.id);
- });
- });
- });
-});
diff --git a/modules/travel/front/thermograph/edit/index.html b/modules/travel/front/thermograph/edit/index.html
deleted file mode 100644
index 3fe448b56..000000000
--- a/modules/travel/front/thermograph/edit/index.html
+++ /dev/null
@@ -1,87 +0,0 @@
-
-
-
diff --git a/modules/travel/front/thermograph/edit/index.js b/modules/travel/front/thermograph/edit/index.js
deleted file mode 100644
index 17caf9ef2..000000000
--- a/modules/travel/front/thermograph/edit/index.js
+++ /dev/null
@@ -1,98 +0,0 @@
-import ngModule from '../../module';
-import Section from 'salix/components/section';
-import './style.scss';
-
-class Controller extends Section {
- get travel() {
- return this._travel;
- }
-
- set travel(value) {
- this._travel = value;
-
- if (value) {
- this.setDefaultParams();
- this.getAllowedContentTypes();
- }
- }
-
- getAllowedContentTypes() {
- this.$http.get('DmsContainers/allowedContentTypes').then(res => {
- const contentTypes = res.data.join(', ');
- this.allowedContentTypes = contentTypes;
- });
- }
-
- get contentTypesInfo() {
- return this.$t('ContentTypesInfo', {
- allowedContentTypes: this.allowedContentTypes
- });
- }
-
- setDefaultParams() {
- const filterObj = {include: {relation: 'dms'}};
- const filter = encodeURIComponent(JSON.stringify(filterObj));
- const path = `TravelThermographs/${this.$params.thermographId}?filter=${filter}`;
- this.$http.get(path).then(res => {
- const thermograph = res.data;
- this.thermograph = {
- thermographId: thermograph.thermographFk,
- state: thermograph.result,
- reference: thermograph.dms.reference,
- warehouseId: thermograph.dms.warehouseFk,
- companyId: thermograph.dms.companyFk,
- dmsTypeId: thermograph.dms.dmsTypeFk,
- description: thermograph.dms.description,
- hasFile: thermograph.dms.hasFile,
- hasFileAttached: false,
- files: []
- };
- });
- }
-
- onSubmit() {
- const query = `travels/${this.$params.id}/saveThermograph`;
- const options = {
- method: 'POST',
- url: query,
- params: this.thermograph,
- headers: {
- 'Content-Type': undefined
- },
- transformRequest: files => {
- const formData = new FormData();
-
- for (const element of files)
- formData.append(element.name, element);
-
- return formData;
- },
- data: this.thermograph.files
- };
- this.$http(options).then(res => {
- if (res) {
- this.vnApp.showSuccess(this.$t('Data saved!'));
- this.$.watcher.updateOriginalData();
- this.$state.go('travel.card.thermograph.index');
- }
- });
- }
-
- onFileChange(files) {
- let hasFileAttached = false;
- if (files.length > 0)
- hasFileAttached = true;
-
- this.$.$applyAsync(() => {
- this.thermograph.hasFileAttached = hasFileAttached;
- });
- }
-}
-
-ngModule.vnComponent('vnTravelThermographEdit', {
- template: require('./index.html'),
- controller: Controller,
- bindings: {
- travel: '<'
- }
-});
diff --git a/modules/travel/front/thermograph/edit/index.spec.js b/modules/travel/front/thermograph/edit/index.spec.js
deleted file mode 100644
index 0b3ef4fbe..000000000
--- a/modules/travel/front/thermograph/edit/index.spec.js
+++ /dev/null
@@ -1,120 +0,0 @@
-import './index';
-import watcher from 'core/mocks/watcher.js';
-
-describe('Worker', () => {
- describe('Component vnTravelThermographEdit', () => {
- let controller;
- let $scope;
- let $httpBackend;
- let $httpParamSerializer;
-
- beforeEach(ngModule('travel'));
-
- beforeEach(inject(($componentController, $rootScope, _$httpBackend_, _$httpParamSerializer_) => {
- $scope = $rootScope.$new();
- $httpBackend = _$httpBackend_;
- $httpParamSerializer = _$httpParamSerializer_;
- const $element = angular.element(` {
- it('should set the travel data and then call setDefaultParams() and getAllowedContentTypes()', () => {
- jest.spyOn(controller, 'setDefaultParams');
- jest.spyOn(controller, 'getAllowedContentTypes');
- controller._travel = undefined;
- controller.travel = {
- id: 3
- };
-
- expect(controller.setDefaultParams).toHaveBeenCalledWith();
- expect(controller.travel).toBeDefined();
- expect(controller.getAllowedContentTypes).toHaveBeenCalledWith();
- });
- });
-
- describe('setDefaultParams()', () => {
- it('should perform a GET query and define the dms property on controller', () => {
- const thermographId = 6;
- const expectedResponse = {
- thermographFk: 6,
- result: 'Ok',
- dms: {
- reference: '123456-01',
- warehouseFk: 1,
- companyFk: 442,
- dmsTypeFk: 3,
- description: 'Test'
- }
- };
-
- const filterObj = {include: {relation: 'dms'}};
- const filter = encodeURIComponent(JSON.stringify(filterObj));
- const query = `TravelThermographs/${thermographId}?filter=${filter}`;
- $httpBackend.expect('GET', query).respond(expectedResponse);
- controller.setDefaultParams();
- $httpBackend.flush();
-
- expect(controller.thermograph).toBeDefined();
- expect(controller.thermograph.reference).toEqual('123456-01');
- expect(controller.thermograph.dmsTypeId).toEqual(3);
- expect(controller.thermograph.state).toEqual('Ok');
- });
- });
-
- describe('onFileChange()', () => {
- it('should set dms hasFileAttached property to true if has any files', () => {
- const files = [{id: 1, name: 'MyFile'}];
- controller.thermograph = {hasFileAttached: false};
- controller.onFileChange(files);
- $scope.$apply();
-
- expect(controller.thermograph.hasFileAttached).toBeTruthy();
- });
- });
-
- describe('getAllowedContentTypes()', () => {
- it('should make an HTTP GET request to get the allowed content types', () => {
- const expectedResponse = ['image/png', 'image/jpg'];
- $httpBackend.expect('GET', `DmsContainers/allowedContentTypes`).respond(expectedResponse);
- controller.getAllowedContentTypes();
- $httpBackend.flush();
-
- expect(controller.allowedContentTypes).toBeDefined();
- expect(controller.allowedContentTypes).toEqual('image/png, image/jpg');
- });
- });
-
- describe('contentTypesInfo()', () => {
- it('should return a description with a list of allowed content types', () => {
- controller.allowedContentTypes = ['image/png', 'image/jpg'];
- const expectedTypes = controller.allowedContentTypes.join(', ');
-
- const expectedResult = `Allowed content types: ${expectedTypes}`;
- jest.spyOn(controller.$translate, 'instant').mockReturnValue(expectedResult);
-
- const result = controller.contentTypesInfo;
-
- expect(result).toEqual(expectedResult);
- });
- });
-
- describe('onSubmit()', () => {
- it('should make an HTTP POST request to save the form data', () => {
- jest.spyOn(controller.$.watcher, 'updateOriginalData');
-
- const files = [{id: 1, name: 'MyFile'}];
- controller.thermograph = {files};
- const serializedParams = $httpParamSerializer(controller.thermograph);
- const query = `travels/${controller.$params.id}/saveThermograph?${serializedParams}`;
-
- $httpBackend.expect('POST', query).respond({});
- controller.onSubmit();
- $httpBackend.flush();
- });
- });
- });
-});
diff --git a/modules/travel/front/thermograph/edit/style.scss b/modules/travel/front/thermograph/edit/style.scss
deleted file mode 100644
index 73f136fc1..000000000
--- a/modules/travel/front/thermograph/edit/style.scss
+++ /dev/null
@@ -1,7 +0,0 @@
-vn-ticket-request {
- .vn-textfield {
- margin: 0!important;
- max-width: 100px;
- }
-}
-
diff --git a/modules/travel/front/thermograph/index/index.html b/modules/travel/front/thermograph/index/index.html
deleted file mode 100644
index 4d711613d..000000000
--- a/modules/travel/front/thermograph/index/index.html
+++ /dev/null
@@ -1,70 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/modules/travel/front/thermograph/index/index.js b/modules/travel/front/thermograph/index/index.js
deleted file mode 100644
index f8b239cfe..000000000
--- a/modules/travel/front/thermograph/index/index.js
+++ /dev/null
@@ -1,51 +0,0 @@
-import ngModule from '../../module';
-import Section from 'salix/components/section';
-import './style.scss';
-
-class Controller extends Section {
- constructor($element, $, vnFile) {
- super($element, $);
- this.vnFile = vnFile;
- this.filter = {
- include:
- {relation: 'warehouse',
- scope: {
- fields: ['id', 'name']
- }
- }
- };
- }
-
- showDeleteConfirm(index) {
- this.thermographIndex = index;
- this.$.confirm.show();
- }
-
- deleteThermograph() {
- const data = this.travelThermographs;
- const thermographId = data[this.thermographIndex].id;
- const query = `Travels/deleteThermograph?id=${thermographId}`;
- this.$http.delete(query).then(() => {
- this.vnApp.showSuccess(this.$t('Thermograph deleted'));
- this.$.model.remove(this.thermographIndex);
- this.thermographIndex = null;
- });
- }
-
- downloadFile(dmsId) {
- this.vnFile.download(`api/dms/${dmsId}/downloadFile`);
- }
-}
-
-Controller.$inject = ['$element', '$scope', 'vnFile'];
-
-ngModule.vnComponent('vnTravelThermographIndex', {
- template: require('./index.html'),
- controller: Controller,
- require: {
- card: '^vnTravelCard'
- },
- bindings: {
- travel: '<'
- }
-});
diff --git a/modules/travel/front/thermograph/index/style.scss b/modules/travel/front/thermograph/index/style.scss
deleted file mode 100644
index 2c287ed9d..000000000
--- a/modules/travel/front/thermograph/index/style.scss
+++ /dev/null
@@ -1,6 +0,0 @@
-@import "variables";
-
-vn-route-tickets form{
- margin: 0 auto;
- max-width: $width-lg;
-}
\ No newline at end of file
diff --git a/modules/travel/front/thermograph/locale/es.yml b/modules/travel/front/thermograph/locale/es.yml
deleted file mode 100644
index 1fdb98c8e..000000000
--- a/modules/travel/front/thermograph/locale/es.yml
+++ /dev/null
@@ -1,20 +0,0 @@
-Code: Código
-Temperature: Temperatura
-State: Estado
-Destination: Destino
-Created: Creado
-Remove thermograph: Eliminar termógrafo
-Upload file: Subir fichero
-Edit file: Editar fichero
-Upload: Subir
-File: Fichero
-TravelFileDescription: Travel id {{travelId}}
-ContentTypesInfo: 'Tipos de archivo permitidos: {{allowedContentTypes}}'
-Are you sure you want to continue?: ¿Seguro que quieres continuar?
-Add thermograph: Añadir termógrafo
-Edit thermograph: Editar termógrafo
-Thermograph deleted: Termógrafo eliminado
-Thermograph: Termógrafo
-New thermograph: Nuevo termógrafo
-Are you sure you want to remove the thermograph?: ¿Seguro que quieres quitar el termógrafo?
-Identifier: Identificador
\ No newline at end of file
diff --git a/modules/worker/back/methods/device/handle-user.js b/modules/worker/back/methods/device/handle-user.js
index 55302c1cb..abafffd55 100644
--- a/modules/worker/back/methods/device/handle-user.js
+++ b/modules/worker/back/methods/device/handle-user.js
@@ -87,7 +87,7 @@ module.exports = Self => {
{
relation: 'sector',
scope: {
- fields: ['warehouseFk', 'description'],
+ fields: ['warehouseFk', 'description', 'isOnReservationMode'],
}
}, {
relation: 'printer',
diff --git a/modules/worker/back/methods/worker-dms/filter.js b/modules/worker/back/methods/worker-dms/filter.js
index 597084e60..240a905d2 100644
--- a/modules/worker/back/methods/worker-dms/filter.js
+++ b/modules/worker/back/methods/worker-dms/filter.js
@@ -86,30 +86,30 @@ module.exports = Self => {
'Tipo Documento': 'description',
'Stored on': 'created',
'Document ID': 'id',
- 'URL': 'download',
+ 'URL': 'url',
'Stored by': 'name',
'Estado': 'state'
};
workerDocuware =
- await models.Docuware.getById('hr', worker.lastName + ' ' + worker.firstName, docuwareParse) ?? [];
- const url = (await Self.app.models.Url.getUrl('docuware')) + 'WebClient';
+ await models.Docuware.getById('hr', worker?.lastName + ' ' + worker?.firstName, docuwareParse) ?? [];
+
for (document of workerDocuware) {
- const docuwareId = document.id;
+ const {id: documentId, dmsFk} = document;
const defaultData = {
- id: docuwareId,
+ id: documentId,
workerFk: id,
- dmsFk: docuwareId,
+ dmsFk: dmsFk,
dms: {
- id: docuwareId,
- file: docuwareId + '.pdf',
+ id: documentId,
+ file: dmsFk + '.pdf',
isDocuware: true,
hasFile: false,
- reference: worker.fi,
- dmsFk: docuwareId,
- url,
+ reference: worker?.fi,
+ dmsFk: dmsFk,
+ url: document.url,
+ download: `WorkerDms/${document.dmsFk}/docuwareDownload`,
description: document.description + ' - ' + document.state,
- download: document.download,
created: document.created,
dmsType: {name: 'Docuware'},
worker: {id: null, user: {name: document.name}},
diff --git a/modules/worker/back/methods/worker-time-control-mail/checkInbox.js b/modules/worker/back/methods/worker-time-control-mail/checkInbox.js
index 4d9f98cc3..688cbb634 100644
--- a/modules/worker/back/methods/worker-time-control-mail/checkInbox.js
+++ b/modules/worker/back/methods/worker-time-control-mail/checkInbox.js
@@ -16,7 +16,7 @@ module.exports = Self => {
});
Self.checkInbox = async() => {
- let imapConfig = await Self.app.models.WorkerTimeControlParams.findOne();
+ let imapConfig = await Self.app.models.WorkerTimeControlConfig.findOne();
let imap = new Imap({
user: imapConfig.mailUser,
password: imapConfig.mailPass,
diff --git a/modules/worker/back/methods/worker-time-control/specs/login.spec.js b/modules/worker/back/methods/worker-time-control/specs/login.spec.js
index e125a876d..eff0edaa7 100644
--- a/modules/worker/back/methods/worker-time-control/specs/login.spec.js
+++ b/modules/worker/back/methods/worker-time-control/specs/login.spec.js
@@ -1,5 +1,4 @@
const models = require('vn-loopback/server/server').models;
-const LoopBackContext = require('loopback-context');
const UserError = require('vn-loopback/util/user-error');
describe('workerTimeControl login()', () => {
diff --git a/modules/worker/back/methods/worker-time-control/specs/sendMail.spec.js b/modules/worker/back/methods/worker-time-control/specs/sendMail.spec.js
new file mode 100644
index 000000000..1395c7a46
--- /dev/null
+++ b/modules/worker/back/methods/worker-time-control/specs/sendMail.spec.js
@@ -0,0 +1,27 @@
+const models = require('vn-loopback/server/server').models;
+
+describe('sendMail', () => {
+ it('should insert in mail', async() => {
+ const tx = await models.Sale.beginTransaction({});
+ const options = {transaction: tx};
+ options.transaction = tx;
+ let mailCountBefore;
+ let mailCountAfter;
+ const ctx = {
+ req: {accessToken: {userId: 50}},
+ args: {workerFk: 1106, year: 2001, week: 1}
+ };
+
+ try {
+ mailCountBefore = await models.Mail.count(options);
+ await models.WorkerTimeControl.sendMail(ctx, options);
+ mailCountAfter = await models.Mail.count(options);
+ } catch (e) {
+ await tx.rollback();
+ throw e;
+ }
+
+ expect(mailCountAfter).toBeGreaterThan(mailCountBefore);
+ await tx.rollback();
+ });
+});
diff --git a/modules/worker/back/methods/worker/createAbsence.js b/modules/worker/back/methods/worker/createAbsence.js
index 0397886cf..93ca7fd89 100644
--- a/modules/worker/back/methods/worker/createAbsence.js
+++ b/modules/worker/back/methods/worker/createAbsence.js
@@ -58,18 +58,24 @@ module.exports = Self => {
if (!isSubordinate || (isSubordinate && userId == id && !isTeamBoss))
throw new UserError(`You don't have enough privileges`);
- const labour = await models.WorkerLabour.findById(args.businessFk, {
- include: {relation: 'department'}
- }, myOptions);
+ const canCreateAbsenceInPast =
+ await models.ACL.checkAccessAcl(ctx, 'Worker', 'canCreateAbsenceInPast', 'WRITE');
+ const now = Date.vnNew();
+ const newDate = new Date(args.dated).getTime();
+
+ if ((now.getTime() > newDate) && !canCreateAbsenceInPast)
+ throw new UserError(`Holidays to past days not available`);
+
+ const labour = await models.WorkerLabour.findById(args.businessFk,
+ {fields: ['started', 'ended', 'businessFk']}, myOptions);
if (args.dated < labour.started || (labour.ended != null && args.dated > labour.ended))
throw new UserError(`The contract was not active during the selected date`);
- query = `SELECT *
- FROM vn.workerTimeControl
- WHERE userFk = ? AND timed BETWEEN DATE(?) AND CONCAT(DATE(?), ' 23:59:59')
- LIMIT 1;`;
- const [hasHoursRecorded] = await Self.rawSql(query, [id, args.dated, args.dated]);
+ const [hasHoursRecorded] = await Self.rawSql(`SELECT *
+ FROM vn.workerTimeControl
+ WHERE userFk = ? AND timed BETWEEN DATE(?) AND CONCAT(DATE(?), ' 23:59:59')
+ LIMIT 1;`, [id, args.dated, args.dated]);
const absenceType = await models.AbsenceType.findById(args.absenceTypeId, null, myOptions);
@@ -81,13 +87,13 @@ module.exports = Self => {
throw new UserError(`The worker has hours recorded that day`);
const date = Date.vnNew();
- const now = Date.vnNew();
date.setHours(0, 0, 0, 0);
const [result] = await Self.rawSql(
`SELECT COUNT(*) halfHolidayCounter
FROM vn.calendar c
JOIN vn.business b ON b.id = c.businessFk
- WHERE c.dayOffTypeFk = 6
+ JOIN vn.absenceType at ON at.id = c.dayOffTypeFk
+ WHERE at.code = 'halfHoliday'
AND b.workerFk = ?
AND c.dated BETWEEN util.firstDayOfYear(?)
AND LAST_DAY(DATE_ADD(?, INTERVAL 12 - MONTH(?) MONTH))`, [id, date, now, now]);
@@ -119,25 +125,26 @@ module.exports = Self => {
dated: args.dated
}, myOptions);
- const department = labour.department();
- if (department && department.notificationEmail) {
- const absenceType = await models.AbsenceType.findById(args.absenceTypeId, null, myOptions);
- const account = await models.VnUser.findById(userId, null, myOptions);
- const subordinated = await models.VnUser.findById(id, null, myOptions);
- const url = await Self.app.models.Url.getUrl();
- const body = $t('Created absence', {
- author: account.nickname,
- employee: subordinated.nickname,
- absenceType: absenceType.name,
- dated: formatDate(args.dated),
- workerUrl: `${url}worker/${id}/calendar`
- });
- await models.Mail.create({
- subject: $t('Absence change notification on the labour calendar'),
- body: body,
- receiver: department.notificationEmail
- }, myOptions);
- }
+ const account = await models.VnUser.findById(userId, null, myOptions);
+ const subordinated = await models.VnUser.findById(id, null, myOptions);
+ const worker = await models.Worker.findById(subordinated.id, null, myOptions);
+ const receiver = await models.EmailUser.findOne({
+ fields: ['email'],
+ where: {userFk: worker.bossFk}
+ }, myOptions);
+ const url = await Self.app.models.Url.getUrl();
+ const body = $t('Created absence', {
+ author: account.nickname,
+ employee: subordinated.nickname,
+ absenceType: absenceType.name,
+ dated: formatDate(args.dated),
+ workerUrl: `${url}worker/${id}/calendar`
+ });
+ await models.Mail.create({
+ subject: $t('Absence change notification on the labour calendar'),
+ body: body,
+ receiver: receiver.email
+ }, myOptions);
if (tx) await tx.commit();
diff --git a/modules/worker/back/methods/worker/filter.js b/modules/worker/back/methods/worker/filter.js
index 2f328d28f..52c60572a 100644
--- a/modules/worker/back/methods/worker/filter.js
+++ b/modules/worker/back/methods/worker/filter.js
@@ -67,6 +67,12 @@ module.exports = Self => {
type: 'String',
description: 'The worker user name',
http: {source: 'query'}
+ },
+ {
+ arg: 'email',
+ type: 'String',
+ description: 'The user email',
+ http: {source: 'query'}
}
],
returns: {
@@ -99,6 +105,8 @@ module.exports = Self => {
return {'w.firstName': {like: `%${value}%`}};
case 'lastName':
return {'w.lastName': {like: `%${value}%`}};
+ case 'nickname':
+ return {'u.nickname': {like: `%${value}%`}};
case 'extension':
return {'p.extension': value};
case 'fi':
@@ -107,6 +115,8 @@ module.exports = Self => {
return {'d.id': value};
case 'userName':
return {'u.name': {like: `%${value}%`}};
+ case 'email':
+ return {'eu.email': {like: `%${value}%`}};
}
});
@@ -116,15 +126,23 @@ module.exports = Self => {
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
+ `SELECT w.id,
+ w.lastName,
+ w.firstName,
+ u.email,
+ u.nickname,
+ p.extension,
+ u.name as userName,
+ d.name AS department,
+ eu.email,
+ c.fi
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.id
LEFT JOIN account.user u ON u.id = w.id
LEFT JOIN pbx.sip p ON p.user_id = u.id
- LEFT JOIN account.emailUser mu ON mu.userFk = u.id`
+ LEFT JOIN account.emailUser eu ON eu.userFk = u.id`
);
stmt.merge(conn.makeSuffix(filter));
diff --git a/modules/worker/back/methods/worker/new.js b/modules/worker/back/methods/worker/new.js
index bb43fba99..7da8a8da2 100644
--- a/modules/worker/back/methods/worker/new.js
+++ b/modules/worker/back/methods/worker/new.js
@@ -217,6 +217,7 @@ module.exports = Self => {
const code = e.code;
const message = e.sqlMessage;
+ if (e.message && e.message.includes('Invalid email')) throw new UserError('Invalid email');
if (e.message && e.message.includes(`Email already exists`)) throw new UserError(`This personal mail already exists`);
if (code === 'ER_DUP_ENTRY' && message.includes(`CodigoTrabajador_UNIQUE`)) throw new UserError(`This worker code already exists`);
if (code === 'ER_DUP_ENTRY' && message.includes(`PRIMARY`)) throw new UserError(`This worker already exists`);
diff --git a/modules/worker/back/methods/worker/specs/createAbsence.spec.js b/modules/worker/back/methods/worker/specs/createAbsence.spec.js
index fcb1c1633..1c7efcd28 100644
--- a/modules/worker/back/methods/worker/specs/createAbsence.spec.js
+++ b/modules/worker/back/methods/worker/specs/createAbsence.spec.js
@@ -162,4 +162,33 @@ describe('Worker createAbsence()', () => {
expect(error.message).toEqual(`The worker has hours recorded that day`);
});
+
+ it(`Should throw an error when adding a "Vacation" absence on a past day`, async() => {
+ const ctx = {
+ req: {accessToken: {userId: 19}},
+ args: {
+ id: 1110,
+ businessFk: 1110,
+ absenceTypeId: 1,
+ dated: '2000-12-27T23:00:00.000Z',
+ }
+ };
+ const workerId = 19;
+
+ const tx = await app.models.Calendar.beginTransaction({});
+
+ let error;
+ try {
+ const options = {transaction: tx};
+
+ await app.models.Worker.createAbsence(ctx, workerId, options);
+
+ await tx.rollback();
+ } catch (e) {
+ await tx.rollback();
+ error = e;
+ }
+
+ expect(error.message).toEqual(`Holidays to past days not available`);
+ });
});
diff --git a/modules/worker/back/model-config.json b/modules/worker/back/model-config.json
index 7bfc667ac..10e55d956 100644
--- a/modules/worker/back/model-config.json
+++ b/modules/worker/back/model-config.json
@@ -113,9 +113,6 @@
"WorkerTimeControlConfig": {
"dataSource": "vn"
},
- "WorkerTimeControlParams": {
- "dataSource": "vn"
- },
"WorkerTimeControlMail": {
"dataSource": "vn"
},
@@ -125,6 +122,15 @@
"Locker": {
"dataSource": "vn"
},
+ "WorkerIrpf": {
+ "dataSource": "vn"
+ },
+ "DisabilityGrade": {
+ "dataSource": "vn"
+ },
+ "WorkerRelative": {
+ "dataSource": "vn"
+ },
"MedicalReview": {
"dataSource": "vn"
},
diff --git a/modules/worker/back/models/device-production-user.json b/modules/worker/back/models/device-production-user.json
index a024cc94c..31aaf92d4 100644
--- a/modules/worker/back/models/device-production-user.json
+++ b/modules/worker/back/models/device-production-user.json
@@ -25,7 +25,7 @@
"userFk": {
"type": "number"
},
- "simSerialNumber": {
+ "simFk": {
"type": "string"
},
"created": {
diff --git a/modules/worker/back/models/disability-grade.json b/modules/worker/back/models/disability-grade.json
new file mode 100644
index 000000000..506138225
--- /dev/null
+++ b/modules/worker/back/models/disability-grade.json
@@ -0,0 +1,18 @@
+{
+ "name": "DisabilityGrade",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "disabilityGrade"
+ }
+ },
+ "properties": {
+ "id": {
+ "id": true,
+ "type": "number"
+ },
+ "description": {
+ "type": "string"
+ }
+ }
+}
diff --git a/modules/worker/back/models/operator.json b/modules/worker/back/models/operator.json
index d4832bccf..b75bf6732 100644
--- a/modules/worker/back/models/operator.json
+++ b/modules/worker/back/models/operator.json
@@ -24,13 +24,28 @@
"warehouseFk": {
"type": "number"
},
+ "sectorFk": {
+ "type": "number"
+ },
"labelerFk": {
"type": "number"
},
"isOnReservationMode": {
"type": "boolean",
"required": true
- }
+ },
+ "machineFk": {
+ "type": "number"
+ },
+ "linesLimit": {
+ "type": "number"
+ },
+ "volumeLimit": {
+ "type": "number"
+ },
+ "sizeLimit": {
+ "type": "number"
+ }
},
"relations": {
"sector": {
@@ -53,6 +68,11 @@
"model": "ItemPackingType",
"foreignKey": "itemPackingTypeFk",
"primaryKey": "code"
- }
+ },
+ "machine": {
+ "type": "belongsTo",
+ "model": "Machine",
+ "foreignKey": "machineFk"
+ }
}
-}
\ No newline at end of file
+}
diff --git a/modules/worker/back/models/worker-irpf.json b/modules/worker/back/models/worker-irpf.json
new file mode 100644
index 000000000..eafda0596
--- /dev/null
+++ b/modules/worker/back/models/worker-irpf.json
@@ -0,0 +1,57 @@
+{
+ "name": "WorkerIrpf",
+ "description": "Model 145 IRPF",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "workerIrpf"
+ }
+ },
+ "properties": {
+ "workerFk": {
+ "type": "number",
+ "id": 1,
+ "description": "Identifier"
+ },
+ "spouseNif": {
+ "type": "string"
+ },
+ "geographicMobilityDate": {
+ "type": "date"
+ },
+ "disabilityGradeFk": {
+ "type" : "number"
+ },
+ "isDependend": {
+ "type" : "boolean"
+ },
+ "familySituation": {
+ "type" : "number"
+ },
+ "spousePension": {
+ "type" : "number"
+ },
+ "childPension": {
+ "type" : "number"
+ },
+ "hasHousingPaymentBefore": {
+ "type" : "boolean"
+ },
+ "hasHousingPaymentAfter": {
+ "type" : "boolean"
+ },
+ "updated": {
+ "type" : "date"
+ },
+ "hasExtendedWorking": {
+ "type" : "boolean"
+ }
+ },
+ "relations": {
+ "disabilityGrade": {
+ "type": "belongsTo",
+ "model": "disabilityGrade",
+ "foreignKey": "disabilityGradeFk"
+ }
+ }
+}
diff --git a/modules/worker/back/models/worker-relatives.json b/modules/worker/back/models/worker-relatives.json
new file mode 100644
index 000000000..532a9446c
--- /dev/null
+++ b/modules/worker/back/models/worker-relatives.json
@@ -0,0 +1,53 @@
+{
+ "name": "WorkerRelative",
+ "description": "Model 145 IRPF",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "workerRelatives"
+ }
+ },
+ "properties": {
+ "id": {
+ "type": "number",
+ "id": true,
+ "description": "Identifier"
+ },
+ "workerFk": {
+ "type": "number"
+ },
+ "isDescendant": {
+ "type": "number"
+ },
+ "disabilityGradeFk": {
+ "type" : "number"
+ },
+ "birthed": {
+ "type" : "number"
+ },
+ "adoptionYear": {
+ "type" : "number"
+ },
+ "isDependend": {
+ "type" : "boolean"
+ },
+ "isJointCustody": {
+ "type" : "boolean"
+ },
+ "updated": {
+ "type" : "date"
+ }
+ },
+ "relations": {
+ "disabilityGrade": {
+ "type": "belongsTo",
+ "model": "disabilityGrade",
+ "foreignKey": "disabilityGradeFk"
+ },
+ "worker": {
+ "type": "belongsTo",
+ "model": "VnUser",
+ "foreignKey": "workerFK"
+ }
+ }
+}
diff --git a/modules/worker/back/models/worker-time-control-config.json b/modules/worker/back/models/worker-time-control-config.json
index b96e2ae3b..53f1a14ea 100644
--- a/modules/worker/back/models/worker-time-control-config.json
+++ b/modules/worker/back/models/worker-time-control-config.json
@@ -11,6 +11,15 @@
"id": true,
"type": "number"
},
+ "mailPass": {
+ "type": "string"
+ },
+ "mailHost": {
+ "type": "string"
+ },
+ "mailUser": {
+ "type": "string"
+ },
"breakTime": {
"type": "number"
},
@@ -23,5 +32,13 @@
"teleworkingStartBreakTime": {
"type": "number"
}
- }
+ },
+ "acls": [
+ {
+ "accessType": "READ",
+ "principalType": "ROLE",
+ "principalId": "$everyone",
+ "permission": "ALLOW"
+ }
+ ]
}
diff --git a/modules/worker/back/models/worker-time-control-params.json b/modules/worker/back/models/worker-time-control-params.json
deleted file mode 100644
index 14cabbfb0..000000000
--- a/modules/worker/back/models/worker-time-control-params.json
+++ /dev/null
@@ -1,35 +0,0 @@
-{
- "name": "WorkerTimeControlParams",
- "description": "imap config",
- "base": "VnModel",
- "options": {
- "mysql": {
- "table": "workerTimeControlParams"
- }
- },
- "properties": {
- "mailHost": {
- "type": "string"
- },
- "mailUser": {
- "type": "string"
- },
- "mailPass": {
- "type": "string"
- },
- "mailSuccessFolder": {
- "type": "string"
- },
- "mailErrorFolder": {
- "type": "string"
- }
- },
- "acls": [
- {
- "accessType": "READ",
- "principalType": "ROLE",
- "principalId": "$everyone",
- "permission": "ALLOW"
- }
- ]
-}
diff --git a/modules/worker/back/models/worker.json b/modules/worker/back/models/worker.json
index b896e775b..705851963 100644
--- a/modules/worker/back/models/worker.json
+++ b/modules/worker/back/models/worker.json
@@ -132,6 +132,16 @@
"type": "hasMany",
"model": "WorkerTimeControlMail",
"foreignKey": "workerFk"
+ },
+ "irpf": {
+ "type": "hasMany",
+ "model": "WorkerIrpf",
+ "foreignKey": "workerFk"
+ },
+ "workerRelative": {
+ "type": "hasMany",
+ "model": "WorkerRelative",
+ "foreignKey": "workerFK"
}
},
"acls": [
@@ -204,6 +214,15 @@
]
},
"summary": {
+ "fields": [
+ "id",
+ "firstName",
+ "lastName",
+ "bossFk",
+ "sex",
+ "phone",
+ "mobileExtension"
+ ],
"include": [
{
"relation": "user",
@@ -247,13 +266,35 @@
}
},
{
- "relation": "boss"
+ "relation": "boss",
+ "scope": {
+ "fields": [
+ "id",
+ "name"
+ ]
+ }
},
{
- "relation": "client"
+ "relation": "client",
+ "scope": {
+ "fields": [
+ "id"
+ ]
+ }
},
{
- "relation": "sip"
+ "relation": "sip",
+ "scope": {
+ "include": {
+ "relation": "queueMember",
+ "scope": {
+ "fields": [
+ "queue",
+ "extension"
+ ]
+ }
+ }
+ }
}
]
},
@@ -261,15 +302,29 @@
"fields": [
"id",
"fiDueDate",
- "sex",
"seniority",
"fi",
"isFreelance",
"isSsDiscounted",
"hasMachineryAuthorized",
"isDisable",
- "birth"
+ "birth",
+ "educationLevelFk",
+ "originCountryFk",
+ "maritalStatus",
+ "SSN"
+ ],
+ "include": [
+ {
+ "relation": "client",
+ "scope": {
+ "fields": [
+ "id",
+ "phone"
+ ]
+ }
+ }
]
}
}
-}
\ No newline at end of file
+}
diff --git a/modules/zone/back/methods/zone/deleteZone.js b/modules/zone/back/methods/zone/deleteZone.js
index a75302703..a147ee588 100644
--- a/modules/zone/back/methods/zone/deleteZone.js
+++ b/modules/zone/back/methods/zone/deleteZone.js
@@ -1,3 +1,4 @@
+const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('deleteZone', {
description: 'Delete a zone',
@@ -39,8 +40,7 @@ module.exports = Self => {
try {
const filter = {
where: {
- zoneFk: id,
- shipped: {gte: today}
+ zoneFk: id
},
include: {
relation: 'ticketState',
@@ -49,26 +49,12 @@ module.exports = Self => {
}
}
};
- const promises = [];
const ticketList = await models.Ticket.find(filter, myOptions);
- const fixingState = await models.State.findOne({where: {code: 'FIXING'}}, myOptions);
- const worker = await models.Worker.findOne({
- where: {id: userId}
- }, myOptions);
+ const hasRefFk = ticketList.some(ticket => !ticket.refFk);
+ if (hasRefFk)
+ throw new UserError('There are tickets to be invoiced');
- await models.Ticket.rawSql('UPDATE ticket SET zoneFk = NULL WHERE zoneFk = ?', [id], myOptions);
-
- for (ticket of ticketList) {
- if (ticket.ticketState().alertLevel == 0) {
- promises.push(models.Ticket.state(ctx, {
- ticketFk: ticket.id,
- stateFk: fixingState.id,
- userFk: worker.id
- }, myOptions));
- }
- }
- await Promise.all(promises);
await models.Zone.destroyById(id, myOptions);
if (tx) await tx.commit();
diff --git a/modules/zone/back/methods/zone/specs/deleteZone.spec.js b/modules/zone/back/methods/zone/specs/deleteZone.spec.js
index 08dafd181..510713f9e 100644
--- a/modules/zone/back/methods/zone/specs/deleteZone.spec.js
+++ b/modules/zone/back/methods/zone/specs/deleteZone.spec.js
@@ -8,14 +8,14 @@ describe('zone deletezone()', () => {
__: value => value
};
const ctx = {req: activeCtx};
- const zoneId = 9;
let ticketIDs;
- let originalTicketStates;
beforeAll(async() => {
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
active: activeCtx
});
+
+ const zoneId = 4;
const originalTickets = await models.Ticket.find({
where: {
zoneFk: zoneId
@@ -29,24 +29,14 @@ describe('zone deletezone()', () => {
it('should delete a zone and update their tickets', async() => {
const tx = await models.Zone.beginTransaction({});
-
+ const zoneId = 4;
try {
const options = {transaction: tx};
await models.Zone.deleteZone(ctx, zoneId, options);
const updatedZone = await models.Zone.findById(zoneId, null, options);
- const anUpdatedTicket = await models.Ticket.findById(ticketIDs[0], null, options);
-
- const updatedTicketStates = await models.TicketState.find({
- where: {
- ticketFk: {inq: ticketIDs},
- code: 'FIXING'
- }
- }, options);
expect(updatedZone).toBeNull();
- expect(anUpdatedTicket.zoneFk).toBeNull();
- expect(updatedTicketStates.length).toBeGreaterThan(originalTicketStates.length);
await tx.rollback();
} catch (e) {
@@ -54,4 +44,21 @@ describe('zone deletezone()', () => {
throw e;
}
});
+
+ it('should not delete the zone if it has tickets', async() => {
+ const tx = await models.Zone.beginTransaction({});
+ const zoneId = 1;
+
+ let error;
+ try {
+ const options = {transaction: tx};
+ await models.Zone.deleteZone(ctx, zoneId, options);
+ await tx.rollback();
+ } catch (e) {
+ error = e.message;
+ await tx.rollback();
+ }
+
+ expect(error).toEqual('There are tickets to be invoiced');
+ });
});
diff --git a/modules/zone/back/model-config.json b/modules/zone/back/model-config.json
index 3bbbe0d1b..2cd3f9d01 100644
--- a/modules/zone/back/model-config.json
+++ b/modules/zone/back/model-config.json
@@ -17,6 +17,9 @@
"ZoneClosure": {
"dataSource": "vn"
},
+ "ZoneConfig": {
+ "dataSource": "vn"
+ },
"ZoneEvent": {
"dataSource": "vn"
},
diff --git a/modules/zone/back/models/zone-config.json b/modules/zone/back/models/zone-config.json
new file mode 100644
index 000000000..a5da7fe55
--- /dev/null
+++ b/modules/zone/back/models/zone-config.json
@@ -0,0 +1,28 @@
+{
+ "name": "ZoneConfig",
+ "options": {
+ "mysql": {
+ "table": "zoneConfig"
+ }
+ },
+ "properties": {
+ "id": {
+ "type": "number",
+ "id": true,
+ "description": "Identifier"
+ },
+ "scope": {
+ "type": "number"
+ },
+ "forwardDays": {
+ "type": "number"
+ }
+ },
+ "relations": {
+ "address": {
+ "type": "belongsTo",
+ "model": "Address",
+ "foreignKey": "defaultAddressFk"
+ }
+ }
+}
diff --git a/modules/zone/back/models/zone.js b/modules/zone/back/models/zone.js
index 6d5a6cdca..7b5cb4301 100644
--- a/modules/zone/back/models/zone.js
+++ b/modules/zone/back/models/zone.js
@@ -14,4 +14,18 @@ module.exports = Self => {
Self.validatesPresenceOf('agencyModeFk', {
message: `Agency cannot be blank`
});
+
+ Self.validatesPresenceOf('price', {
+ message: 'Price cannot be blank'
+ });
+ Self.validateAsync('price', priceIsValid, {
+ message: 'Price must be greater than 0'
+ });
+
+ async function priceIsValid(err, done) {
+ if (this.price <= 0)
+ err();
+
+ done();
+ }
};
diff --git a/modules/zone/back/models/zone.json b/modules/zone/back/models/zone.json
index 5b25e40d1..141b28750 100644
--- a/modules/zone/back/models/zone.json
+++ b/modules/zone/back/models/zone.json
@@ -1,9 +1,9 @@
{
"name": "Zone",
"base": "VnModel",
- "mixins": {
- "Loggable": true
- },
+ "mixins": {
+ "Loggable": true
+ },
"options": {
"mysql": {
"table": "zone"
@@ -48,30 +48,35 @@
}
},
"relations": {
- "agencyMode": {
- "type": "belongsTo",
- "model": "AgencyMode",
- "foreignKey": "agencyModeFk"
+ "agencyMode": {
+ "type": "belongsTo",
+ "model": "AgencyMode",
+ "foreignKey": "agencyModeFk"
},
"events": {
- "type": "hasMany",
- "model": "ZoneEvent",
- "foreignKey": "zoneFk"
- },
+ "type": "hasMany",
+ "model": "ZoneEvent",
+ "foreignKey": "zoneFk"
+ },
"exclusions": {
- "type": "hasMany",
- "model": "ZoneExclusion",
+ "type": "hasMany",
+ "model": "ZoneExclusion",
"foreignKey": "zoneFk"
},
"warehouses": {
"type": "hasMany",
"model": "ZoneWarehouse",
"foreignKey": "zoneFk"
- },
+ },
"closures": {
"type": "hasMany",
"model": "ZoneClosure",
"foreignKey": "zoneFk"
- }
- }
+ },
+ "address": {
+ "type": "belongsTo",
+ "model": "Address",
+ "foreignKey": "addressFk"
+ }
+ }
}
diff --git a/myt.config.yml b/myt.config.yml
index 663b1aec2..a947405b3 100755
--- a/myt.config.yml
+++ b/myt.config.yml
@@ -69,7 +69,9 @@ fixtures:
- siiTypeInvoiceOut
- state
- ticketUpdateAction
+ - ticketCanAdvanceConfig
- volumeConfig
+ - workerActivityType
- workCenter
- workerTimeControlError
cache:
@@ -257,7 +259,6 @@ localFixtures:
- itemFamily
- itemLog
- itemShelving
- - itemShelvingLog
- itemShelvingSale
- itemTag
- itemTaxCountry
@@ -384,7 +385,6 @@ localFixtures:
- workerTimeControl
- workerTimeControlConfig
- workerTimeControlMail
- - workerTimeControlParams
- zone
- zoneAgencyMode
- zoneClosure
diff --git a/package.json b/package.json
index 8f9670903..a843ac9c5 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "salix-back",
- "version": "24.42.0",
+ "version": "25.02.0",
"author": "Verdnatura Levante SL",
"description": "Salix backend",
"license": "GPL-3.0",
@@ -60,7 +60,7 @@
"@babel/register": "^7.7.7",
"@commitlint/cli": "^19.2.1",
"@commitlint/config-conventional": "^19.1.0",
- "@verdnatura/myt": "^1.6.11",
+ "@verdnatura/myt": "^1.6.12",
"angular-mocks": "^1.7.9",
"babel-jest": "^26.0.1",
"babel-loader": "^8.2.4",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e2480cf4a..042b91fe0 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -143,8 +143,8 @@ devDependencies:
specifier: ^19.1.0
version: 19.1.0
'@verdnatura/myt':
- specifier: ^1.6.11
- version: 1.6.11
+ specifier: ^1.6.12
+ version: 1.6.12
angular-mocks:
specifier: ^1.7.9
version: 1.8.3
@@ -2846,8 +2846,8 @@ packages:
dev: false
optional: true
- /@verdnatura/myt@1.6.11:
- resolution: {integrity: sha512-uqdbSJSznBBzAoRkvBt600nUMEPL1PJ2v73eWMZbaoGUMiZiNAehYjs4gIrObP1cxC85JOx97XoLpG0BzPsaig==}
+ /@verdnatura/myt@1.6.12:
+ resolution: {integrity: sha512-t/SiDuQW9KJkcjhwQ9AkrcoTwghxQ7IyQ56e+88eYdoMi24l6bQGF0wHzMaIPRfQAoR8hqgfMOief4OAqW4Iqw==}
hasBin: true
dependencies:
'@sqltools/formatter': 1.2.5
@@ -6548,7 +6548,7 @@ packages:
resolution: {integrity: sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw==}
engines: {node: '>= 4.0'}
os: [darwin]
- deprecated: The v1 package contains DANGEROUS / INSECURE binaries. Upgrade to safe fsevents v2
+ deprecated: Upgrade to fsevents v2 to mitigate potential security issues
requiresBuild: true
dependencies:
bindings: 1.5.0
@@ -10485,7 +10485,7 @@ packages:
engines: {node: '>=10'}
requiresBuild: true
dependencies:
- semver: 7.5.4
+ semver: 7.6.0
dev: false
optional: true
@@ -12501,6 +12501,7 @@ packages:
hasBin: true
dependencies:
lru-cache: 6.0.0
+ dev: true
/semver@7.6.0:
resolution: {integrity: sha512-EnwXhrlwXMk9gKu5/flx5sv/an57AkRplG3hTK68W7FRDN+k+OWBj65M7719OkA82XLBxrcX0KSHj+X5COhOVg==}
@@ -12508,7 +12509,6 @@ packages:
hasBin: true
dependencies:
lru-cache: 6.0.0
- dev: true
/send@0.18.0(supports-color@6.1.0):
resolution: {integrity: sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==}
diff --git a/print/templates/email/incoterms-authorization/locale/en.yml b/print/templates/email/incoterms-authorization/locale/en.yml
new file mode 100644
index 000000000..7e1402575
--- /dev/null
+++ b/print/templates/email/incoterms-authorization/locale/en.yml
@@ -0,0 +1,6 @@
+subject: Incoterms Authorization
+title: Incoterms Authorization
+description:
+ dear: Dear customer
+ instructions: Please find attached the Incoterms authorization form, which you must complete and sign.
+ conclusion: Thank you for your attention!
diff --git a/print/templates/reports/balance-compensation/locale/en.yml b/print/templates/reports/balance-compensation/locale/en.yml
new file mode 100644
index 000000000..824127482
--- /dev/null
+++ b/print/templates/reports/balance-compensation/locale/en.yml
@@ -0,0 +1,16 @@
+reportName: balance-compensation
+Place: Algemesí, on
+Compensation: Compensation of debtor and creditor balances
+In one hand: On one hand
+CIF: with CIF
+NIF: with NIF
+Home: and address located at
+In other hand: On the other hand
+Sr: Mr./Ms.
+Agree: Agree
+Date: On the date of
+Compensate: the balance of has been compensated
+From client: from the client/supplier
+Against the balance of: against the balance of
+Reception: Please confirm receipt of this compensation at the email
+Greetings: Best regards,
diff --git a/print/templates/reports/buy-label/assets/css/import.js b/print/templates/reports/buy-label-barcode/assets/css/import.js
similarity index 100%
rename from print/templates/reports/buy-label/assets/css/import.js
rename to print/templates/reports/buy-label-barcode/assets/css/import.js
diff --git a/print/templates/reports/buy-label-barcode/assets/css/style.css b/print/templates/reports/buy-label-barcode/assets/css/style.css
new file mode 100644
index 000000000..ce1924878
--- /dev/null
+++ b/print/templates/reports/buy-label-barcode/assets/css/style.css
@@ -0,0 +1,89 @@
+html {
+ font-family: "Roboto", "Helvetica", "Arial", sans-serif;
+ margin-top: -9px;
+ margin-left: -3px;
+}
+table {
+ width: 100%;
+ font-size: 14px;
+}
+td {
+ border: 6px solid white;
+}
+.center {
+ text-align: center;
+}
+.right {
+ text-align: right;
+}
+.cursive {
+ font-style: italic;
+}
+.bold {
+ font-weight: bold;
+}
+.black-bg {
+ background-color: black;
+ color: white;
+}
+.xs-txt {
+ font-size: 18px;
+}
+.md-txt {
+ font-size: 26px;
+}
+.lg-txt {
+ font-size: 40px;
+ padding: 0px;
+ line-height: 1;
+}
+.xl-txt {
+ font-size: 50px;
+}
+.cell {
+ border: 2px solid black;
+ box-sizing: content-box;
+ width: 100%;
+ height: 30px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+}
+.padding {
+ padding: 7px;
+}
+.xs-height {
+ height: 50px;
+ max-height: 50px;
+}
+.md-height {
+ height: 70px;
+ max-height: 70px;
+}
+.sm-width {
+ width: 60px;
+ max-width: 60px;
+}
+.md-width {
+ width: 125px;
+ max-width: 125px;
+}
+.lg-width {
+ width: 380px;
+ max-width: 380px;
+}
+.overflow-multiline {
+ max-height: inherit;
+ display: -webkit-box;
+ overflow: hidden;
+ word-wrap: break-word;
+ line-clamp: 2;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+}
+.overflow-line {
+ width: inherit;
+ max-width: inherit;
+ overflow: hidden;
+ white-space: nowrap;
+}
\ No newline at end of file
diff --git a/print/templates/reports/buy-label-barcode/buy-label-barcode.html b/print/templates/reports/buy-label-barcode/buy-label-barcode.html
new file mode 100644
index 000000000..ebddb60ec
--- /dev/null
+++ b/print/templates/reports/buy-label-barcode/buy-label-barcode.html
@@ -0,0 +1,94 @@
+
+
+
+
+
+
+
+ {{buy.item}}
+
+
+
+
+ {{buy.size}}
+
+
+
+
+
+
+ {{
+ (buy.longName && buy.size && buy.subName)
+ ? `${buy.longName} ${buy.size} ${buy.subName}`
+ : buy.comment
+ }}
+
+
+
+
+ {{buy.producerName || buy.producerFk}}
+
+
+
+
+ {{buy.inkFk}}
+
+
+
+
+
+
+ {{formatNumber(buy.itemFk)}}
+
+
+
+
+ {{`${(packing || buy.packing)} x ${buy.stems || ''}`}}
+
+
+
+
+
+
+
+
+
+ {{'LAID'}}
+
+
+ {{formatNumber(buy.entryFk)}}
+
+
+
+
+
+
+ {{buy.buyerName}}
+
+
+
+
+ {{buy.origin}}
+
+
+
+
+
+
+ {{formatNumber(buy.buyFk)}}
+
+
+
+
+ {{date}}
+
+
+
+
+ {{`${buy.labelNum}/${buy.quantity / (packing || buy.packing)}`}}
+
+
+
+
+
+
\ No newline at end of file
diff --git a/print/templates/reports/buy-label-barcode/buy-label-barcode.js b/print/templates/reports/buy-label-barcode/buy-label-barcode.js
new file mode 100755
index 000000000..37b618f09
--- /dev/null
+++ b/print/templates/reports/buy-label-barcode/buy-label-barcode.js
@@ -0,0 +1,52 @@
+const UserError = require('vn-loopback/util/user-error');
+const {DOMImplementation, XMLSerializer} = require('xmldom');
+const moment = require('moment');
+const jsbarcode = require('jsbarcode');
+
+module.exports = {
+ name: 'buy-label-barcode',
+ async serverPrefetch() {
+ this.date = Date.vnNew();
+ this.buys = await this.rawSqlFromDef('buy', [this.copies || 1, this.id]);
+ if (!this.buys.length) throw new UserError(`Empty data source`);
+ this.date = moment(this.date).format('WW/DD');
+ },
+ methods: {
+ getBarcode(data) {
+ const document = new DOMImplementation().createDocument('http://www.w3.org/1999/xhtml', 'html', null);
+ const svgNode = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+
+ jsbarcode(svgNode, data, {
+ xmlDocument: document,
+ format: 'code128',
+ displayValue: false,
+ width: 3.5,
+ height: 75,
+ margin: 0
+ });
+ return new XMLSerializer().serializeToString(svgNode);
+ },
+ formatNumber(number) {
+ return new Intl.NumberFormat('es-ES', {maximumFractionDigits: 0}).format(number);
+ }
+ },
+ props: {
+ id: {
+ type: Number,
+ required: true,
+ description: 'The item id'
+ },
+ warehouseId: {
+ type: Number
+ },
+ packing: {
+ type: Number
+ },
+ copies: {
+ type: Number
+ },
+ typeId: {
+ type: String
+ }
+ }
+};
diff --git a/print/templates/reports/buy-label-barcode/locale/es.yml b/print/templates/reports/buy-label-barcode/locale/es.yml
new file mode 100644
index 000000000..3cf8d2ce8
--- /dev/null
+++ b/print/templates/reports/buy-label-barcode/locale/es.yml
@@ -0,0 +1 @@
+reportName: Etiqueta de artículo barcode
\ No newline at end of file
diff --git a/print/templates/reports/buy-label-barcode/options.json b/print/templates/reports/buy-label-barcode/options.json
new file mode 100644
index 000000000..17c43e69f
--- /dev/null
+++ b/print/templates/reports/buy-label-barcode/options.json
@@ -0,0 +1,11 @@
+{
+ "width": "10.4cm",
+ "height": "4.9cm",
+ "margin": {
+ "top": "0.17cm",
+ "right": "0.37cm",
+ "bottom": "0cm",
+ "left": "0cm"
+ },
+ "printBackground": true
+}
\ No newline at end of file
diff --git a/print/templates/reports/buy-label-barcode/sql/buy.sql b/print/templates/reports/buy-label-barcode/sql/buy.sql
new file mode 100644
index 000000000..739f8449f
--- /dev/null
+++ b/print/templates/reports/buy-label-barcode/sql/buy.sql
@@ -0,0 +1,38 @@
+WITH RECURSIVE numbers AS (
+ SELECT 1 n
+ UNION ALL
+ SELECT n + 1
+ FROM numbers
+ WHERE n < ?
+)
+SELECT ROW_NUMBER() OVER() labelNum,
+ b.itemFk,
+ i.name item,
+ b.id buyFk,
+ b.quantity,
+ b.packing,
+ b.entryFk,
+ o.code origin,
+ p.`name` producerName,
+ p.id producerFk,
+ i.`size`,
+ i.category,
+ i.stems,
+ i.inkFk,
+ ig.longName,
+ ig.subName,
+ i.comment,
+ w.code buyerName,
+ i.isLaid,
+ c.code company
+ FROM vn.buy b
+ JOIN vn.item i ON i.id = b.itemFk
+ LEFT JOIN vn.item ig ON ig.id = b.itemOriginalFk
+ JOIN vn.origin o ON o.id = i.originFk
+ LEFT JOIN vn.producer p ON p.id = i.producerFk
+ JOIN vn.itemType it ON it.id = i.typeFk
+ JOIN vn.worker w ON w.id = it.workerFk
+ JOIN vn.entry e ON e.id = b.entryFk
+ JOIN vn.company c ON c.id = e.companyFk
+ JOIN numbers num
+ WHERE b.id = ?
\ No newline at end of file
diff --git a/print/templates/reports/item-label/assets/css/import.js b/print/templates/reports/buy-label-qr/assets/css/import.js
similarity index 100%
rename from print/templates/reports/item-label/assets/css/import.js
rename to print/templates/reports/buy-label-qr/assets/css/import.js
diff --git a/print/templates/reports/buy-label-qr/assets/css/style.css b/print/templates/reports/buy-label-qr/assets/css/style.css
new file mode 100644
index 000000000..36db0fdef
--- /dev/null
+++ b/print/templates/reports/buy-label-qr/assets/css/style.css
@@ -0,0 +1,92 @@
+html {
+ font-family: "Roboto", "Helvetica", "Arial", sans-serif;
+ margin-top: -7px;
+ margin-left: -3px;
+}
+.leftTable {
+ width: 47%;
+ font-size: 12px;
+ float: left;
+ text-align: center;
+}
+.leftTable img {
+ margin-top: 3px;
+ width: 110px;
+}
+.rightTable {
+ width: 53%;
+ font-size: 14px;
+ float: right;
+}
+.rightTable td {
+ border: 3px solid white;
+}
+.center {
+ text-align: center;
+}
+.cursive {
+ font-style: italic;
+}
+.bold {
+ font-weight: bold;
+}
+.black-bg {
+ background-color: black;
+ color: white;
+}
+.sm-txt {
+ font-size: 18px;
+}
+.md-txt {
+ font-size: 20px;
+}
+.xl-txt {
+ font-size: 36px;
+}
+.cell {
+ border: 2px solid black;
+ box-sizing: content-box;
+ width: 100%;
+ height: 30px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+}
+.padding {
+ padding: 7px;
+}
+.md-height {
+ height: 68px;
+ max-height: 68px;
+}
+.xs-width {
+ width: 60px;
+ max-width: 60px;
+}
+.sm-width {
+ width: 130px;
+ max-width: 130px;
+}
+.md-width {
+ width: 190px;
+ max-width: 190px;
+}
+.lg-width {
+ width: 240px;
+ max-width: 240px;
+}
+.overflow-multiline {
+ max-height: inherit;
+ display: -webkit-box;
+ overflow: hidden;
+ word-wrap: break-word;
+ line-clamp: 2;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+}
+.overflow-line {
+ width: inherit;
+ max-width: inherit;
+ overflow: hidden;
+ white-space: nowrap;
+}
\ No newline at end of file
diff --git a/print/templates/reports/buy-label-qr/buy-label-qr.html b/print/templates/reports/buy-label-qr/buy-label-qr.html
new file mode 100644
index 000000000..00ede5488
--- /dev/null
+++ b/print/templates/reports/buy-label-qr/buy-label-qr.html
@@ -0,0 +1,122 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{formatNumber(buy.buyFk)}}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{formatNumber(buy.itemFk)}}
+
+
+
+
+
+
+ {{buy.item}}
+
+
+
+
+ {{buy.size}}
+
+
+
+
+
+
+ Color: {{buy.inkFk}}
+
+
+
+
+ {{packing || buy.packing}}
+
+
+
+
+ {{buy.stems}}
+
+
+
+
+
+
+ Origen: {{buy.origin}}
+
+
+
+
+
+
+ Productor: {{buy.producerName || buy.producerFk}}
+
+
+
+
+ {{'LAID'}}
+
+
+
+
+
+
+
+
+ Comprador: {{buy.buyerName}}
+
+
+
+
+ F: {{date}}
+
+
+
+
+ {{`${buy.labelNum}/${buy.quantity / (packing || buy.packing)}`}}
+
+
+
+
+
+
+ Entrada: {{formatNumber(buy.entryFk)}}
+
+
+
+
+
+
+ {{
+ (buy.longName && buy.size && buy.subName)
+ ? `${buy.longName} ${buy.size} ${buy.subName}`
+ : buy.comment
+ }}
+
+
+
+
+
+
\ No newline at end of file
diff --git a/print/templates/reports/buy-label-qr/buy-label-qr.js b/print/templates/reports/buy-label-qr/buy-label-qr.js
new file mode 100755
index 000000000..614e40816
--- /dev/null
+++ b/print/templates/reports/buy-label-qr/buy-label-qr.js
@@ -0,0 +1,54 @@
+const UserError = require('vn-loopback/util/user-error');
+const moment = require('moment');
+const qrcode = require('qrcode');
+
+module.exports = {
+ name: 'buy-label-qr',
+ async serverPrefetch() {
+ this.date = Date.vnNew();
+ this.buys = await this.rawSqlFromDef('buy', [this.copies || 1, this.id]);
+ if (!this.buys.length) throw new UserError(`Empty data source`);
+ this.qr = await this.getQr(this.buys[0].buyFk);
+ this.date = moment(this.date).format('WW/DD');
+ },
+ methods: {
+ getQr(data) {
+ data = {
+ company: this.buys.company,
+ user: this.userId,
+ created: this.date,
+ table: 'buy',
+ id: data
+ };
+ return qrcode.toDataURL(JSON.stringify(data), {
+ margin: 0,
+ errorCorrectionLevel: 'L'
+ });
+ },
+ formatNumber(number) {
+ return new Intl.NumberFormat('es-ES', {maximumFractionDigits: 0}).format(number);
+ }
+ },
+ props: {
+ id: {
+ type: Number,
+ required: true,
+ description: 'The item id'
+ },
+ warehouseId: {
+ type: Number
+ },
+ packing: {
+ type: Number
+ },
+ copies: {
+ type: Number
+ },
+ userId: {
+ type: Number
+ },
+ typeId: {
+ type: String
+ }
+ }
+};
diff --git a/print/templates/reports/buy-label-qr/locale/es.yml b/print/templates/reports/buy-label-qr/locale/es.yml
new file mode 100644
index 000000000..81dbc1877
--- /dev/null
+++ b/print/templates/reports/buy-label-qr/locale/es.yml
@@ -0,0 +1 @@
+reportName: Etiqueta de artículo QR
\ No newline at end of file
diff --git a/print/templates/reports/item-label/options.json b/print/templates/reports/buy-label-qr/options.json
similarity index 62%
rename from print/templates/reports/item-label/options.json
rename to print/templates/reports/buy-label-qr/options.json
index 98c5788b1..c6ffaddea 100644
--- a/print/templates/reports/item-label/options.json
+++ b/print/templates/reports/buy-label-qr/options.json
@@ -1,9 +1,9 @@
{
"width": "10.4cm",
- "height": "4.8cm",
+ "height": "4.9cm",
"margin": {
- "top": "0cm",
- "right": "0cm",
+ "top": "0.17cm",
+ "right": "0.3cm",
"bottom": "0cm",
"left": "0cm"
},
diff --git a/print/templates/reports/buy-label-qr/sql/buy.sql b/print/templates/reports/buy-label-qr/sql/buy.sql
new file mode 100644
index 000000000..739f8449f
--- /dev/null
+++ b/print/templates/reports/buy-label-qr/sql/buy.sql
@@ -0,0 +1,38 @@
+WITH RECURSIVE numbers AS (
+ SELECT 1 n
+ UNION ALL
+ SELECT n + 1
+ FROM numbers
+ WHERE n < ?
+)
+SELECT ROW_NUMBER() OVER() labelNum,
+ b.itemFk,
+ i.name item,
+ b.id buyFk,
+ b.quantity,
+ b.packing,
+ b.entryFk,
+ o.code origin,
+ p.`name` producerName,
+ p.id producerFk,
+ i.`size`,
+ i.category,
+ i.stems,
+ i.inkFk,
+ ig.longName,
+ ig.subName,
+ i.comment,
+ w.code buyerName,
+ i.isLaid,
+ c.code company
+ FROM vn.buy b
+ JOIN vn.item i ON i.id = b.itemFk
+ LEFT JOIN vn.item ig ON ig.id = b.itemOriginalFk
+ JOIN vn.origin o ON o.id = i.originFk
+ LEFT JOIN vn.producer p ON p.id = i.producerFk
+ JOIN vn.itemType it ON it.id = i.typeFk
+ JOIN vn.worker w ON w.id = it.workerFk
+ JOIN vn.entry e ON e.id = b.entryFk
+ JOIN vn.company c ON c.id = e.companyFk
+ JOIN numbers num
+ WHERE b.id = ?
\ No newline at end of file
diff --git a/print/templates/reports/buy-label-supplier/assets/css/import.js b/print/templates/reports/buy-label-supplier/assets/css/import.js
new file mode 100644
index 000000000..37a98dfdd
--- /dev/null
+++ b/print/templates/reports/buy-label-supplier/assets/css/import.js
@@ -0,0 +1,12 @@
+const Stylesheet = require(`vn-print/core/stylesheet`);
+
+const path = require('path');
+const vnPrintPath = path.resolve('print');
+
+module.exports = new Stylesheet([
+ `${vnPrintPath}/common/css/spacing.css`,
+ `${vnPrintPath}/common/css/misc.css`,
+ `${vnPrintPath}/common/css/layout.css`,
+ `${vnPrintPath}/common/css/report.css`,
+ `${__dirname}/style.css`])
+ .mergeStyles();
diff --git a/print/templates/reports/buy-label/assets/css/style.css b/print/templates/reports/buy-label-supplier/assets/css/style.css
similarity index 100%
rename from print/templates/reports/buy-label/assets/css/style.css
rename to print/templates/reports/buy-label-supplier/assets/css/style.css
diff --git a/print/templates/reports/buy-label/buy-label.html b/print/templates/reports/buy-label-supplier/buy-label-supplier.html
similarity index 97%
rename from print/templates/reports/buy-label/buy-label.html
rename to print/templates/reports/buy-label-supplier/buy-label-supplier.html
index 5777d34de..31fef38f7 100644
--- a/print/templates/reports/buy-label/buy-label.html
+++ b/print/templates/reports/buy-label-supplier/buy-label-supplier.html
@@ -86,7 +86,7 @@
{{$t('boxNum')}}
- {{`${buy.labelNum} / ${buy.maxLabelNum}`}}
+ {{getTotal(buy)}}
diff --git a/print/templates/reports/buy-label/buy-label.js b/print/templates/reports/buy-label-supplier/buy-label-supplier.js
similarity index 77%
rename from print/templates/reports/buy-label/buy-label.js
rename to print/templates/reports/buy-label-supplier/buy-label-supplier.js
index 289483051..5e59472eb 100755
--- a/print/templates/reports/buy-label/buy-label.js
+++ b/print/templates/reports/buy-label-supplier/buy-label-supplier.js
@@ -5,11 +5,11 @@ const jsBarcode = require('jsbarcode');
const moment = require('moment');
module.exports = {
- name: 'buy-label',
+ name: 'buy-label-supplier',
mixins: [vnReport],
async serverPrefetch() {
const buy = await models.Buy.findById(this.id, null);
- this.buys = await this.rawSqlFromDef('buy', [buy.entryFk, buy.entryFk, buy.entryFk, this.id]);
+ this.buys = await this.rawSqlFromDef('buy', [buy.entryFk, buy.entryFk, buy.entryFk, this.id, this.id]);
const date = new Date();
this.weekNum = moment(date).isoWeek();
this.dayNum = moment(date).day();
@@ -27,6 +27,11 @@ module.exports = {
height: 115,
});
return new XMLSerializer().serializeToString(svgNode);
+ },
+ getTotal(buy) {
+ return (this.showEntryLines) ?
+ `${buy.entryLabelNum} / ${buy.entryLabels}` :
+ `${buy.buyLabelNum} / ${buy.buyLabels}`;
}
},
props: {
@@ -34,6 +39,10 @@ module.exports = {
type: Number,
required: true,
description: 'The entry id'
+ },
+ showEntryLines: {
+ type: Boolean,
+ required: false
}
}
};
diff --git a/print/templates/reports/buy-label/locale/en.yml b/print/templates/reports/buy-label-supplier/locale/en.yml
similarity index 100%
rename from print/templates/reports/buy-label/locale/en.yml
rename to print/templates/reports/buy-label-supplier/locale/en.yml
diff --git a/print/templates/reports/buy-label/locale/es.yml b/print/templates/reports/buy-label-supplier/locale/es.yml
similarity index 100%
rename from print/templates/reports/buy-label/locale/es.yml
rename to print/templates/reports/buy-label-supplier/locale/es.yml
diff --git a/print/templates/reports/buy-label/options.json b/print/templates/reports/buy-label-supplier/options.json
similarity index 100%
rename from print/templates/reports/buy-label/options.json
rename to print/templates/reports/buy-label-supplier/options.json
diff --git a/print/templates/reports/buy-label/sql/buy.sql b/print/templates/reports/buy-label-supplier/sql/buy.sql
similarity index 72%
rename from print/templates/reports/buy-label/sql/buy.sql
rename to print/templates/reports/buy-label-supplier/sql/buy.sql
index 26efeb06e..fe001ff10 100644
--- a/print/templates/reports/buy-label/sql/buy.sql
+++ b/print/templates/reports/buy-label-supplier/sql/buy.sql
@@ -10,7 +10,7 @@ WITH RECURSIVE numbers AS (
)
),
labels AS (
- SELECT ROW_NUMBER() OVER(ORDER BY b.id, num.n) labelNum,
+ SELECT ROW_NUMBER() OVER(ORDER BY b.id, num.n) entryLabelNum,
i.name,
i.`size`,
i.category,
@@ -33,6 +33,9 @@ labels AS (
WHERE b.entryFk = ?
AND num.n <= b.stickers
)
-SELECT *, (SELECT SUM(stickers) FROM buy WHERE entryFk = ?) maxLabelNum
+SELECT *,
+ ROW_NUMBER() OVER(ORDER BY entryLabelNum) buyLabelNum,
+ (SELECT SUM(stickers) FROM buy WHERE entryFk = ?) entryLabels,
+ (SELECT stickers FROM buy WHERE id = ?) buyLabels
FROM labels
WHERE id = ?
\ 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
index c1701e084..89bc07488 100644
--- a/print/templates/reports/delivery-note/delivery-note.html
+++ b/print/templates/reports/delivery-note/delivery-note.html
@@ -58,6 +58,7 @@
{{$t('reference')}}
{{$t('quantity')}}
{{$t('concept')}}
+ {{$t('producer')}}
{{$t('price')}}
{{$t('discount')}}
{{$t('vat')}}
@@ -69,6 +70,7 @@
{{sale.itemFk}}
{{sale.quantity}}
{{sale.concept}}
+ {{sale.subName}}
{{sale.price | currency('EUR', $i18n.locale)}}
{{(sale.discount / 100) | percentage}}
{{sale.vatType}}
@@ -81,7 +83,6 @@
{{sale.tag5}} {{sale.value5}}
{{sale.tag6}} {{sale.value6}}
{{sale.tag7}} {{sale.value7}}
- {{$t('producer')}} {{ sale.subName }}
diff --git a/print/templates/reports/driver-route/driver-route.html b/print/templates/reports/driver-route/driver-route.html
index 109afd2f5..e3a206656 100644
--- a/print/templates/reports/driver-route/driver-route.html
+++ b/print/templates/reports/driver-route/driver-route.html
@@ -16,7 +16,7 @@
{{$t('date')}}
- {{formatDate(route.created, '%d-%m-%Y')}}
+ {{formatDate(route.dated, '%d-%m-%Y')}}
{{$t('vehicle')}}
{{route.vehicleTradeMark}} {{route.vehicleModel}}
diff --git a/print/templates/reports/driver-route/sql/routes.sql b/print/templates/reports/driver-route/sql/routes.sql
index 9d2dd5c13..334f2337d 100644
--- a/print/templates/reports/driver-route/sql/routes.sql
+++ b/print/templates/reports/driver-route/sql/routes.sql
@@ -1,6 +1,6 @@
SELECT r.id,
r.m3,
- r.created,
+ r.dated,
r.time,
u.nickName userNickName,
v.tradeMark vehicleTradeMark,
diff --git a/print/templates/reports/entry-order/assets/css/style.css b/print/templates/reports/entry-order/assets/css/style.css
index 767b1185a..858ae704e 100644
--- a/print/templates/reports/entry-order/assets/css/style.css
+++ b/print/templates/reports/entry-order/assets/css/style.css
@@ -17,4 +17,14 @@ h3 {
.tags {
font-size: 10px;
margin: 0;
+}
+
+.column-oriented th,
+.column-oriented td{
+ padding: 5px
+}
+
+[row] {
+ display: flex;
+ column-gap: 5px;
}
\ No newline at end of file
diff --git a/print/templates/reports/entry-order/entry-order.html b/print/templates/reports/entry-order/entry-order.html
index e5d3bfb6d..d3f909d4d 100644
--- a/print/templates/reports/entry-order/entry-order.html
+++ b/print/templates/reports/entry-order/entry-order.html
@@ -41,42 +41,50 @@
+ {{$t('code')}}
{{$t('boxes')}}
-
+
{{$t('packing')}}
- {{$t('concept')}}
- {{$t('reference')}}
- {{$t('tags')}}
- {{$t('quantity')}}
-
- {{$t('price')}}
-
- {{$t('amount')}}
+ {{$t('concept')}}
+ {{$t('reference')}}
+ {{$t('tags')}}
+ {{$t('quantity')}}
+
+ {{$t('price')}}
+
+ {{$t('amount')}}
+ {{buy.itemFk}}
{{buy.stickers}}
- x
- {{buy.packing}}
- {{buy.name}}
- {{buy.comment}}
-
- {{buy.tag5}} → {{buy.value5}}
- {{buy.tag6}} → {{buy.value6}}
- {{buy.tag7}} → {{buy.value7}}
+ x
+ {{buy.packing}}
+ {{buy.name}}
+ {{buy.comment}}
+
+
+
{{buy.tag5}}→ {{buy.value5}}
+
{{buy.tag6}}→ {{buy.value6}}
+
+
+
{{buy.tag7}}→ {{buy.value7}}
+
{{buy.tag8}}→ {{buy.value8}}
+
- {{buy.quantity | number($i18n.locale)}}
- x
- {{buy.buyingValue | currency('EUR', $i18n.locale)}}
- =
-
+ {{buy.quantity | number($i18n.locale)}}
+ x
+ {{buy.buyingValue | currency('EUR', $i18n.locale)}}
+ =
+
{{buy.buyingValue * buy.quantity | currency('EUR', $i18n.locale)}}
+
{{getTotalBy('stickers')}}
diff --git a/print/templates/reports/entry-order/locale/es.yml b/print/templates/reports/entry-order/locale/es.yml
index 5a6716ba1..9ec357802 100644
--- a/print/templates/reports/entry-order/locale/es.yml
+++ b/print/templates/reports/entry-order/locale/es.yml
@@ -16,4 +16,5 @@ entry: Entrada {0}
supplierData: Datos del proveedor
notes: Notas
reference: Referencia
-tags: Tags
\ No newline at end of file
+tags: Etiquetas
+code: Código
\ No newline at end of file
diff --git a/print/templates/reports/entry-order/sql/buys.sql b/print/templates/reports/entry-order/sql/buys.sql
index 92c055483..545849908 100644
--- a/print/templates/reports/entry-order/sql/buys.sql
+++ b/print/templates/reports/entry-order/sql/buys.sql
@@ -10,7 +10,9 @@ SELECT b.itemFk,
i.tag6,
i.value6,
i.tag7,
- i.value7
+ i.value7,
+ i.tag8,
+ i.value8
FROM buy b
JOIN item i ON i.id = b.itemFk
LEFT JOIN item i2 ON i2.id = b.itemOriginalFk
diff --git a/print/templates/reports/expedition-pallet-label/sql/labelData.sql b/print/templates/reports/expedition-pallet-label/sql/labelData.sql
index 49a4031ae..5ddf8eb6e 100644
--- a/print/templates/reports/expedition-pallet-label/sql/labelData.sql
+++ b/print/templates/reports/expedition-pallet-label/sql/labelData.sql
@@ -4,7 +4,7 @@ SELECT ep.id palletFk,
r.description `zone`,
COUNT(es.id) labels,
t.warehouseFk warehouseFk,
- dayname(r.created) `dayName`,
+ dayname(r.dated) `dayName`,
rs.id <=> rm.roadmapStopFk isMatch
FROM vn.roadmapStop rs
JOIN vn.expeditionPallet ep ON ep.truckFk = rs.id
diff --git a/print/templates/reports/incoterms-authorization/locale/en.yml b/print/templates/reports/incoterms-authorization/locale/en.yml
new file mode 100644
index 000000000..eb6a8a513
--- /dev/null
+++ b/print/templates/reports/incoterms-authorization/locale/en.yml
@@ -0,0 +1,39 @@
+reportName: autorization-incoterms
+description: '{socialName} a duly constituted and responsible company limited
+and registered under corporate law {country} and here represented by {socialName}, with address in {address},
+CIF {fiscalID} . Hereinafter referred to as {name}.'
+issued: 'In {0}, on {1} of {2} of {3}'
+client: 'Customer {0}'
+declaration: '{socialName} hereby declares that:'
+declarations:
+ - 'All purchases made by {socialName} with {companyName} They are delivered according to the conditions defined in the Incoterm.'
+ - '{socialName} recognizes that it is important for {companyName} have
+proof of intra-community delivery of the goods to {destinationCountry} to
+be able to invoice with 0% VAT.'
+ - 'Therefore, by signing this agreement, {socialName} declares that all goods
+purchased from {companyName} will be delivered to {destinationCountry}.'
+ - 'Besides, {socialName} shall, at the first request of {companyName},
+provide proof that all products purchased from {companyName} have
+been delivered in {destinationCountry}.'
+ - 'In addition to the above, {companyName} will provide to {socialName}
+a monthly summary that includes all bills (and corresponding deliveries).
+{socialName} will sign and return the monthly summary to {companyName},
+S.L. within 5 days of receiving the summary.'
+signer:
+ representative: Representative
+ representativeRole: Position of the representative
+ signed: Date of signature
+manager: Manager
+months:
+ - 'January'
+ - 'February'
+ - 'March'
+ - 'April'
+ - 'May'
+ - 'June'
+ - 'July'
+ - 'August'
+ - 'September'
+ - 'October'
+ - 'November'
+ - 'December'
diff --git a/print/templates/reports/item-label/assets/css/style.css b/print/templates/reports/item-label/assets/css/style.css
deleted file mode 100644
index 1101604b9..000000000
--- a/print/templates/reports/item-label/assets/css/style.css
+++ /dev/null
@@ -1,88 +0,0 @@
-* {
- 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
deleted file mode 100644
index 66509ab38..000000000
--- a/print/templates/reports/item-label/item-label.html
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
-
-
-
-
-
{{item.id}}
-
-
-
-
-
-
-
{{tags.color}}
-
{{tags.producer}}
-
-
-
{{packing()}}
-
{{formatDate(new Date(), '%W/%d')}}
-
{{labelPage}}
-
-
{{item.size}}
-
-
-
-
-
-
-
diff --git a/print/templates/reports/item-label/item-label.js b/print/templates/reports/item-label/item-label.js
deleted file mode 100755
index c5b9cdfd7..000000000
--- a/print/templates/reports/item-label/item-label.js
+++ /dev/null
@@ -1,58 +0,0 @@
-const vnReport = require('../../../core/mixins/vn-report.js');
-const qrcode = require('qrcode');
-
-module.exports = {
- name: 'item-label',
- mixins: [vnReport],
- async serverPrefetch() {
- this.item = await this.findOneFromDef('item', [this.id, this.warehouseId]);
- this.checkMainEntity(this.item);
- this.tags = await this.fetchItemTags(this.id);
- this.barcode = await this.getBarcodeBase64(this.id);
- },
-
- computed: {
- labelPage() {
- const labelNumber = this.labelNumber ? this.labelNumber : 1;
- const totalLabels = this.totalLabels ? this.totalLabels : 1;
-
- return `${labelNumber}/${totalLabels}`;
- }
- },
- methods: {
- fetchItemTags(id) {
- return this.rawSqlFromDef('itemTags', [id]).then(rows => {
- const tags = {};
- rows.forEach(row => tags[row.code] = row.value);
-
- return tags;
- });
- },
- getBarcodeBase64(id) {
- const data = String(id);
-
- return qrcode.toDataURL(data, {margin: 0});
- },
- packing() {
- const stems = this.item.stems ? this.item.stems : 1;
- return `${this.item.packing}x${stems}`;
- }
- },
- props: {
- id: {
- type: Number,
- required: true,
- description: 'The item id'
- },
- warehouseId: {
- type: Number,
- required: true
- },
- labelNumber: {
- type: Number
- },
- totalLabels: {
- type: Number
- }
- }
-};
diff --git a/print/templates/reports/item-label/locale/es.yml b/print/templates/reports/item-label/locale/es.yml
deleted file mode 100644
index 278946f3e..000000000
--- a/print/templates/reports/item-label/locale/es.yml
+++ /dev/null
@@ -1 +0,0 @@
-reportName: Etiqueta
\ No newline at end of file
diff --git a/print/templates/reports/item-label/sql/item.sql b/print/templates/reports/item-label/sql/item.sql
deleted file mode 100644
index 46aacc2fa..000000000
--- a/print/templates/reports/item-label/sql/item.sql
+++ /dev/null
@@ -1,14 +0,0 @@
-SELECT
- i.id,
- i.name,
- i.stems,
- i.size,
- b.packing,
- p.name as 'producer'
-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
- JOIN vn.producer p ON p.id = i.producerFk
-
-WHERE i.id = ? AND clb.warehouse_id = ?
\ No newline at end of file
diff --git a/print/templates/reports/item-label/sql/itemTags.sql b/print/templates/reports/item-label/sql/itemTags.sql
deleted file mode 100644
index 3c20098a6..000000000
--- a/print/templates/reports/item-label/sql/itemTags.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-SELECT t.code, t.name, it.value
-FROM vn.itemTag it
- JOIN vn.tag t ON t.id = it.tagFk
-WHERE it.itemFk = ?
\ No newline at end of file