diff --git a/Jenkinsfile b/Jenkinsfile index d411ddb22f..03ac84de3f 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -40,7 +40,7 @@ pipeline { NODE_ENV = "" } steps { - nodejs('node-v12') { + nodejs('node-v14') { sh 'npm install --no-audit --prefer-offline' sh 'gulp install --ci' } @@ -57,14 +57,14 @@ pipeline { parallel { stage('Frontend') { steps { - nodejs('node-v12') { + nodejs('node-v14') { sh 'jest --ci --reporters=default --reporters=jest-junit --maxWorkers=2' } } } // stage('Backend') { // steps { - // nodejs('node-v12') { + // nodejs('node-v14') { // sh 'gulp launchBackTest --ci' // } // } @@ -80,7 +80,7 @@ pipeline { CREDENTIALS = credentials('docker-registry') } steps { - nodejs('node-v12') { + nodejs('node-v14') { sh 'gulp build' } diff --git a/back/methods/chat/spec/sendCheckingPresence.spec.js b/back/methods/chat/spec/sendCheckingPresence.spec.js index aa4a80801e..e9c61fd21f 100644 --- a/back/methods/chat/spec/sendCheckingPresence.spec.js +++ b/back/methods/chat/spec/sendCheckingPresence.spec.js @@ -6,7 +6,7 @@ describe('Chat sendCheckingPresence()', () => { const ctx = {req: {accessToken: {userId: 1}}}; const chatModel = app.models.Chat; const departmentId = 23; - const workerId = 107; + const workerId = 1107; it(`should call send() method with the worker name if he's currently working then return a response`, async() => { spyOn(chatModel, 'send').and.callThrough(); diff --git a/back/methods/collection/getCollection.js b/back/methods/collection/getCollection.js index caf9cc5210..e02d2c5c77 100644 --- a/back/methods/collection/getCollection.js +++ b/back/methods/collection/getCollection.js @@ -3,7 +3,7 @@ module.exports = Self => { description: 'Get pending collections from a worker', accessType: 'READ', returns: { - type: 'Object', + type: 'object', root: true }, http: { diff --git a/back/methods/collection/spec/getCollection.spec.js b/back/methods/collection/spec/getCollection.spec.js index 44c7af62f7..5ea042f9d7 100644 --- a/back/methods/collection/spec/getCollection.spec.js +++ b/back/methods/collection/spec/getCollection.spec.js @@ -1,9 +1,9 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; -describe('getCollection()', () => { - it('return list of collection', async() => { - let ctx = {req: {accessToken: {userId: 106}}}; - let response = await app.models.Collection.getCollection(ctx); +describe('ticket getCollection()', () => { + it('should return a list of collections', async() => { + let ctx = {req: {accessToken: {userId: 1106}}}; + let response = await models.Collection.getCollection(ctx); expect(response.length).toBeGreaterThan(0); expect(response[0].collectionFk).toEqual(1); diff --git a/back/methods/collection/spec/newCollection.spec.js b/back/methods/collection/spec/newCollection.spec.js index bd574db0f4..6fbf9af8ca 100644 --- a/back/methods/collection/spec/newCollection.spec.js +++ b/back/methods/collection/spec/newCollection.spec.js @@ -2,10 +2,10 @@ const app = require('vn-loopback/server/server'); describe('newCollection()', () => { it('return a new collection', async() => { - let ctx = {req: {accessToken: {userId: 106}}}; + let ctx = {req: {accessToken: {userId: 1106}}}; let response = await app.models.Collection.newCollection(ctx, 1, 1, 1); expect(response.length).toBeGreaterThan(0); - expect(response[0].ticketFk).toEqual(1); + expect(response[0].ticketFk).toEqual(2); }); }); diff --git a/back/methods/collection/spec/updateCollectionSale.spec.js b/back/methods/collection/spec/updateCollectionSale.spec.js index 83b161a733..951115e545 100644 --- a/back/methods/collection/spec/updateCollectionSale.spec.js +++ b/back/methods/collection/spec/updateCollectionSale.spec.js @@ -3,7 +3,7 @@ const app = require('vn-loopback/server/server'); describe('updateCollectionSale()', () => { it('should return a new collection', async() => { const sectorOneWarehouseID = 1; - let ctx = {req: {accessToken: {userId: 106}}}; + let ctx = {req: {accessToken: {userId: 1106}}}; ctx.args = { sale: 1, originalQuantity: 5, diff --git a/back/methods/dms/removeFile.js b/back/methods/dms/removeFile.js index 1c50137a0f..a9ff368834 100644 --- a/back/methods/dms/removeFile.js +++ b/back/methods/dms/removeFile.js @@ -21,8 +21,9 @@ module.exports = Self => { }); Self.removeFile = async(ctx, id, options) => { + const models = Self.app.models; let tx; - let myOptions = {}; + const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); @@ -33,7 +34,6 @@ module.exports = Self => { } try { - const models = Self.app.models; const dms = await models.Dms.findById(id, null, myOptions); const trashDmsType = await models.DmsType.findOne({ where: {code: 'trash'} diff --git a/back/methods/dms/specs/downloadFile.spec.js b/back/methods/dms/specs/downloadFile.spec.js index 701a484dff..763c2a0c1e 100644 --- a/back/methods/dms/specs/downloadFile.spec.js +++ b/back/methods/dms/specs/downloadFile.spec.js @@ -4,7 +4,7 @@ describe('dms downloadFile()', () => { let dmsId = 1; it('should return a response for an employee with text content-type', async() => { - let workerId = 107; + let workerId = 1107; let ctx = {req: {accessToken: {userId: workerId}}}; const result = await app.models.Dms.downloadFile(ctx, dmsId); @@ -12,7 +12,7 @@ describe('dms downloadFile()', () => { }); it('should return an error for a user without enough privileges', async() => { - let clientId = 101; + let clientId = 1101; let ctx = {req: {accessToken: {userId: clientId}}}; let error; diff --git a/back/methods/dms/specs/removeFile.spec.js b/back/methods/dms/specs/removeFile.spec.js index 1006d13295..28ce5d0fd2 100644 --- a/back/methods/dms/specs/removeFile.spec.js +++ b/back/methods/dms/specs/removeFile.spec.js @@ -4,7 +4,7 @@ describe('dms removeFile()', () => { let dmsId = 1; it(`should return an error for a user without enough privileges`, async() => { - let clientId = 101; + let clientId = 1101; let ctx = {req: {accessToken: {userId: clientId}}}; let error; diff --git a/back/methods/dms/specs/updateFile.spec.js b/back/methods/dms/specs/updateFile.spec.js index 2945b1ac9e..87ee372ec4 100644 --- a/back/methods/dms/specs/updateFile.spec.js +++ b/back/methods/dms/specs/updateFile.spec.js @@ -2,7 +2,7 @@ const app = require('vn-loopback/server/server'); describe('dms updateFile()', () => { it(`should return an error for a user without enough privileges`, async() => { - let clientId = 101; + let clientId = 1101; let companyId = 442; let warehouseId = 1; let dmsTypeId = 14; diff --git a/back/methods/dms/specs/uploadFile.spec.js b/back/methods/dms/specs/uploadFile.spec.js index afd70d068c..fda911bade 100644 --- a/back/methods/dms/specs/uploadFile.spec.js +++ b/back/methods/dms/specs/uploadFile.spec.js @@ -2,7 +2,7 @@ const app = require('vn-loopback/server/server'); describe('dms uploadFile()', () => { it(`should return an error for a user without enough privileges`, async() => { - let clientId = 101; + let clientId = 1101; let ticketDmsTypeId = 14; let ctx = {req: {accessToken: {userId: clientId}}, args: {dmsTypeId: ticketDmsTypeId}}; diff --git a/back/methods/image/specs/download.spec.js b/back/methods/image/specs/download.spec.js index 328d932a12..758f884aef 100644 --- a/back/methods/image/specs/download.spec.js +++ b/back/methods/image/specs/download.spec.js @@ -15,7 +15,7 @@ describe('image download()', () => { }); it(`should return false if the user doesn't have image`, async() => { - const userId = 110; + const userId = 1110; const image = await app.models.Image.download(ctx, collection, size, userId); expect(image).toBeFalse(); diff --git a/back/methods/image/specs/upload.spec.js b/back/methods/image/specs/upload.spec.js index 86b598b49f..7cb2ae6f92 100644 --- a/back/methods/image/specs/upload.spec.js +++ b/back/methods/image/specs/upload.spec.js @@ -3,7 +3,7 @@ const app = require('vn-loopback/server/server'); describe('image upload()', () => { describe('as buyer', () => { const buyerId = 35; - const workerId = 106; + const workerId = 1106; const itemId = 4; it('should try to upload a file for the collection "catalog" and throw a privileges error', async() => { @@ -45,7 +45,7 @@ describe('image upload()', () => { describe('as marketing', () => { const marketingId = 51; - const workerId = 106; + const workerId = 1106; const itemId = 4; it('should be able to call to the TempContainer upload method for the collection "user"', async() => { @@ -87,7 +87,7 @@ describe('image upload()', () => { describe('as hhrr', () => { const hhrrId = 37; - const workerId = 106; + const workerId = 1106; const itemId = 4; it('should upload a file for the collection "user" and call to the TempContainer upload method', async() => { diff --git a/back/methods/user-config/getUserConfig.js b/back/methods/user-config/getUserConfig.js index 663ef71b41..4de8049e77 100644 --- a/back/methods/user-config/getUserConfig.js +++ b/back/methods/user-config/getUserConfig.js @@ -12,18 +12,22 @@ module.exports = function(Self) { } }); - Self.getUserConfig = async ctx => { + Self.getUserConfig = async(ctx, options) => { const models = Self.app.models; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); let userConfig = await models.UserConfig.findOne({ where: {userFk: ctx.req.accessToken.userId} - }); + }, myOptions); const companyFilter = {where: {code: 'VNL'}}; - const company = await models.Company.findOne(companyFilter); + const company = await models.Company.findOne(companyFilter, myOptions); const warehouseFilter = {where: {code: 'ALG'}}; - const warehouse = await models.Warehouse.findOne(warehouseFilter); + const warehouse = await models.Warehouse.findOne(warehouseFilter, myOptions); if (!userConfig) { let newConfig = { @@ -32,7 +36,7 @@ module.exports = function(Self) { userFk: ctx.req.accessToken.userId }; - userConfig = await models.UserConfig.create(newConfig); + userConfig = await models.UserConfig.create(newConfig, myOptions); } return userConfig; }; diff --git a/back/methods/user-config/specs/getUserConfig.spec.js b/back/methods/user-config/specs/getUserConfig.spec.js index c86f3e0f28..8b510a7062 100644 --- a/back/methods/user-config/specs/getUserConfig.spec.js +++ b/back/methods/user-config/specs/getUserConfig.spec.js @@ -1,10 +1,21 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('userConfig getUserConfig()', () => { it(`should return the configuration data of a given user`, async() => { - const result = await app.models.UserConfig.getUserConfig({req: {accessToken: {userId: 9}}}); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result.warehouseFk).toEqual(1); - expect(result.companyFk).toEqual(442); + try { + const ctx = {req: {accessToken: {userId: 9}}}; + const result = await models.UserConfig.getUserConfig(ctx, options); + + expect(result.warehouseFk).toEqual(1); + expect(result.companyFk).toEqual(442); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/back/model-config.json b/back/model-config.json index bf473d7bc9..18bf4cf98d 100644 --- a/back/model-config.json +++ b/back/model-config.json @@ -65,6 +65,9 @@ "Province": { "dataSource": "vn" }, + "Autonomy": { + "dataSource": "vn" + }, "Payment": { "dataSource": "vn" }, diff --git a/back/models/account.json b/back/models/account.json index 9cac20bc00..b59cf39c22 100644 --- a/back/models/account.json +++ b/back/models/account.json @@ -80,13 +80,15 @@ "principalType": "ROLE", "principalId": "$everyone", "permission": "ALLOW" - }, { + }, + { "property": "logout", "accessType": "EXECUTE", "principalType": "ROLE", "principalId": "$authenticated", "permission": "ALLOW" - }, { + }, + { "property": "validateToken", "accessType": "EXECUTE", "principalType": "ROLE", diff --git a/back/models/autonomy.json b/back/models/autonomy.json new file mode 100644 index 0000000000..ce9ac0bc67 --- /dev/null +++ b/back/models/autonomy.json @@ -0,0 +1,43 @@ +{ + "name": "Autonomy", + "description": "Autonomies of every country", + "base": "VnModel", + "options": { + "mysql": { + "table": "autonomy" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "name": { + "type": "string", + "required": true + } + }, + "relations": { + "country": { + "type": "belongsTo", + "model": "Country", + "foreignKey": "countryFk" + } + }, + "scopes": { + "location": { + "include": { + "relation": "country" + } + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} \ No newline at end of file diff --git a/back/models/province.json b/back/models/province.json index 2e2ace5eda..77e0b24a6c 100644 --- a/back/models/province.json +++ b/back/models/province.json @@ -9,7 +9,7 @@ }, "properties": { "id": { - "type": "Number", + "type": "number", "id": true, "description": "Identifier" }, @@ -24,6 +24,11 @@ "model": "Country", "foreignKey": "countryFk" }, + "autonomy": { + "type": "belongsTo", + "model": "Autonomy", + "foreignKey": "autonomyFk" + }, "warehouse": { "type": "belongsTo", "model": "Warehouse", diff --git a/back/models/sage-withholding.json b/back/models/sage-withholding.json index 8d93daeae6..dddbcfd747 100644 --- a/back/models/sage-withholding.json +++ b/back/models/sage-withholding.json @@ -6,6 +6,9 @@ "table": "sage.TiposRetencion" } }, + "log": { + "showField": "withholding" + }, "properties": { "id": { "type": "Number", diff --git a/back/models/specs/dms.spec.js b/back/models/specs/dms.spec.js index 8e76a4956a..93ae1d1e05 100644 --- a/back/models/specs/dms.spec.js +++ b/back/models/specs/dms.spec.js @@ -36,14 +36,14 @@ describe('Dms', () => { describe('checkRole()', () => { const dmsId = 1; it('should return a true for an employee with permission', async() => { - let ctx = {req: {accessToken: {userId: 107}}}; + let ctx = {req: {accessToken: {userId: 1107}}}; const result = await Dms.checkRole(ctx, dmsId); expect(result).toBeTruthy(); }); it('should return false for an employee without permission', async() => { - let ctx = {req: {accessToken: {userId: 101}}}; + let ctx = {req: {accessToken: {userId: 1101}}}; const result = await Dms.checkRole(ctx, dmsId); expect(result).toBeFalsy(); diff --git a/db/changes/10310-mothersDay/00-ACL.sql b/db/changes/10310-mothersDay/00-ACL.sql deleted file mode 100644 index 1067c02f74..0000000000 --- a/db/changes/10310-mothersDay/00-ACL.sql +++ /dev/null @@ -1,4 +0,0 @@ -INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) -VALUES - ('SupplierAddress', '*', '*', 'ALLOW', 'ROLE', 'employee'), - ('SalesMonitor', '*', '*', 'ALLOW', 'ROLE', 'employee'); diff --git a/db/changes/10310-mothersDay/00-module.sql b/db/changes/10310-mothersDay/00-module.sql deleted file mode 100644 index 18067529b6..0000000000 --- a/db/changes/10310-mothersDay/00-module.sql +++ /dev/null @@ -1 +0,0 @@ -INSERT INTO salix.module (code) VALUES ('Monitors'); diff --git a/db/changes/10310-mothersDay/00-receiptAcl.sql b/db/changes/10310-mothersDay/00-receiptAcl.sql deleted file mode 100644 index d3450cc9d1..0000000000 --- a/db/changes/10310-mothersDay/00-receiptAcl.sql +++ /dev/null @@ -1,3 +0,0 @@ -UPDATE salix.ACL - SET principalId = "salesAssistant" - WHERE model = 'Client' AND property = 'createReceipt'; \ No newline at end of file diff --git a/db/changes/10310-mothersDay/00-supplierAddress.sql b/db/changes/10310-mothersDay/00-supplierAddress.sql deleted file mode 100644 index e15a25a817..0000000000 --- a/db/changes/10310-mothersDay/00-supplierAddress.sql +++ /dev/null @@ -1,18 +0,0 @@ -CREATE TABLE `vn`.`supplierAddress` -( - id INT NULL AUTO_INCREMENT, - supplierFk INT NULL, - nickname VARCHAR(40) NULL, - street VARCHAR(255) NULL, - provinceFk SMALLINT(6) UNSIGNED NULL, - postalCode VARCHAR(10) NULL, - city VARCHAR(50) NULL, - phone VARCHAR(15) NULL, - mobile VARCHAR(15) NULL, - CONSTRAINT supplierAddress_pk - PRIMARY KEY (id), - CONSTRAINT supplierAddress_province_fk - FOREIGN KEY (provinceFk) REFERENCES province (id) - ON UPDATE CASCADE -); - diff --git a/db/changes/10320-monitors/00-sale_getProblemsByTicket.sql b/db/changes/10320-monitors/00-sale_getProblemsByTicket.sql deleted file mode 100644 index 1f30014d4b..0000000000 --- a/db/changes/10320-monitors/00-sale_getProblemsByTicket.sql +++ /dev/null @@ -1,30 +0,0 @@ -DROP PROCEDURE IF EXISTS `vn`.`sale_getProblemsByTicket`; - -DELIMITER $$ -$$ -CREATE - DEFINER = root@`%` PROCEDURE `vn`.`sale_getProblemsByTicket`(IN vTicketFk INT, IN vIsTodayRelative TINYINT(1)) -BEGIN -/** - * Calcula los problemas de cada venta - * para un conjunto de tickets. - * - * @return Problems result - */ - DROP TEMPORARY TABLE IF EXISTS tmp.sale_getProblems; - CREATE TEMPORARY TABLE tmp.sale_getProblems - (INDEX (ticketFk)) - ENGINE = MEMORY - SELECT t.id ticketFk, t.clientFk, t.warehouseFk, t.shipped - FROM ticket t - WHERE t.id = vTicketFk; - - CALL sale_getProblems(vIsTodayRelative); - - SELECT * FROM tmp.sale_problems; - - DROP TEMPORARY TABLE - tmp.sale_getProblems, - tmp.sale_problems; -END;;$$ -DELIMITER ; diff --git a/db/changes/10320-monitors/00-ticketGetProblems.sql b/db/changes/10320-monitors/00-ticketGetProblems.sql deleted file mode 100644 index 06d0275b31..0000000000 --- a/db/changes/10320-monitors/00-ticketGetProblems.sql +++ /dev/null @@ -1,187 +0,0 @@ -DROP PROCEDURE IF EXISTS `vn`.`ticketGetProblems`; - -DELIMITER $$ -$$ -CREATE - DEFINER = root@`%` PROCEDURE `vn`.`ticketGetProblems`(IN vIsTodayRelative TINYINT(1)) -BEGIN -/** - * @deprecated Use ticket_getProblems() instead - * - */ - DECLARE vWarehouse INT; - DECLARE vDate DATE; - DECLARE vAvailableCache INT; - DECLARE vDone INT DEFAULT 0; - DECLARE vComponentCount INT; - - DECLARE vCursor CURSOR FOR - SELECT DISTINCT tt.warehouseFk, IF(vIsTodayRelative, CURDATE(), date(tt.shipped)) - FROM tmp.ticketGetProblems tt - WHERE DATE(tt.shipped) BETWEEN CURDATE() - AND TIMESTAMPADD(DAY, IF(vIsTodayRelative, 9.9, 1.9), CURDATE()); - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketProblems; - CREATE TEMPORARY TABLE tmp.ticketProblems ( - ticketFk INT(11) PRIMARY KEY, - isFreezed INTEGER(1) DEFAULT 0, - risk DECIMAL(10,2) DEFAULT 0, - hasTicketRequest INTEGER(1) DEFAULT 0, - isAvailable INTEGER(1) DEFAULT 1, - itemShortage VARCHAR(250), - isTaxDataChecked INTEGER(1) DEFAULT 1, - itemDelay VARCHAR(250), - componentLack INTEGER(1) - ) ENGINE = MEMORY; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketList; - CREATE TEMPORARY TABLE tmp.ticketList - (PRIMARY KEY (ticketFk)) - ENGINE = MEMORY - SELECT tp.ticketFk, c.id clientFk - FROM tmp.ticketGetProblems tp - JOIN vn.client c ON c.id = tp.clientFk; - - SELECT COUNT(*) INTO vComponentCount - FROM vn.component c - WHERE c.isRequired; - - INSERT INTO tmp.ticketProblems(ticketFk, componentLack) - SELECT tl.ticketFk, (COUNT(DISTINCT s.id) * vComponentCount > COUNT(c.id)) - FROM tmp.ticketList tl - JOIN vn.sale s ON s.ticketFk = tl.ticketFk - LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id - LEFT JOIN vn.component c ON c.id = sc.componentFk AND c.isRequired - GROUP BY tl.ticketFk; - - INSERT INTO tmp.ticketProblems(ticketFk, isFreezed) - SELECT DISTINCT tl.ticketFk, 1 - FROM tmp.ticketList tl - JOIN vn.client c ON c.id = tl.clientFk - WHERE c.isFreezed - ON DUPLICATE KEY UPDATE - isFreezed = c.isFreezed; - - DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; - CREATE TEMPORARY TABLE tmp.clientGetDebt - (PRIMARY KEY (clientFk)) - ENGINE = MEMORY - SELECT DISTINCT clientFk - FROM tmp.ticketList; - - CALL clientGetDebt(CURDATE()); - - INSERT INTO tmp.ticketProblems(ticketFk, risk) - SELECT DISTINCT tl.ticketFk, r.risk - FROM tmp.ticketList tl - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.agencyMode a ON t.agencyModeFk = a.id - JOIN tmp.risk r ON r.clientFk = t.clientFk - JOIN vn.client c ON c.id = t.clientFk - JOIN vn.clientConfig cc - WHERE r.risk - cc.riskTolerance > c.credit + 10 - AND a.isRiskFree = FALSE - ON DUPLICATE KEY UPDATE - risk = r.risk; - - INSERT INTO tmp.ticketProblems(ticketFk, hasTicketRequest) - SELECT DISTINCT tl.ticketFk, 1 - FROM tmp.ticketList tl - JOIN vn.ticketRequest tr ON tr.ticketFk = tl.ticketFk - WHERE tr.isOK IS NULL AND tr.saleFk IS NOT NULL - ON DUPLICATE KEY UPDATE - hasTicketRequest = 1; - - OPEN vCursor; - - WHILE NOT vDone - DO - FETCH vCursor INTO vWarehouse, vDate; - - CALL cache.available_refresh(vAvailableCache, FALSE, vWarehouse, vDate); - - INSERT INTO tmp.ticketProblems(ticketFk, isAvailable) - SELECT tl.ticketFk, 0 - FROM tmp.ticketList tl - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it on it.id = i.typeFk - LEFT JOIN cache.available av ON av.item_id = i.id - AND av.calc_id = vAvailableCache - WHERE date(t.shipped) = vDate - AND it.categoryFk != 6 - AND IFNULL(av.available, 0) < 0 - AND s.isPicked = FALSE - AND NOT i.generic - AND vWarehouse = t.warehouseFk - GROUP BY tl.ticketFk - ON DUPLICATE KEY UPDATE - isAvailable = 0; - - INSERT INTO tmp.ticketProblems(ticketFk, itemShortage) - SELECT ticketFk, problem - FROM ( - SELECT tl.ticketFk, CONCAT('F: ',GROUP_CONCAT(i.id, ' ', i.longName, ' ')) problem - FROM tmp.ticketList tl - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it on it.id = i.typeFk - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk - LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - WHERE IFNULL(av.available, 0) < 0 - AND s.quantity > IFNULL(issw.visible, 0) - AND s.quantity > 0 - AND s.isPicked = FALSE - AND s.reserved = FALSE - AND it.categoryFk != 6 - AND IF(vIsTodayRelative, TRUE, date(t.shipped) = vDate) - AND NOT i.generic - AND CURDATE() = vDate - AND t.warehouseFk = vWarehouse - GROUP BY tl.ticketFk) sub - ON DUPLICATE KEY UPDATE - itemShortage = sub.problem; - - INSERT INTO tmp.ticketProblems(ticketFk, itemDelay) - SELECT ticketFk, problem - FROM ( - SELECT tl.ticketFk, GROUP_CONCAT('I: ',i.id, ' ', i.longName, ' ') problem - FROM tmp.ticketList tl - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it on it.id = i.typeFk - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk - WHERE s.quantity > IFNULL(issw.visible, 0) - AND s.quantity > 0 - AND s.isPicked = FALSE - AND s.reserved = FALSE - AND it.categoryFk != 6 - AND IF(vIsTodayRelative, TRUE, date(t.shipped) = vDate) - AND NOT i.generic - AND CURDATE() = vDate - AND t.warehouseFk = vWarehouse - GROUP BY tl.ticketFk) sub - ON DUPLICATE KEY UPDATE - itemDelay = sub.problem; - END WHILE; - - CLOSE vCursor; - - INSERT INTO tmp.ticketProblems(ticketFk, isTaxDataChecked) - SELECT DISTINCT tl.ticketFk, FALSE - FROM tmp.ticketList tl - JOIN vn.client c ON c.id = tl.clientFk - WHERE c.isTaxDataChecked= FALSE - ON DUPLICATE KEY UPDATE - isTaxDataChecked = FALSE; - - DROP TEMPORARY TABLE - tmp.clientGetDebt, - tmp.ticketList; -END;;$$ -DELIMITER ; diff --git a/db/changes/10320-monitors/00-ticket_componentMakeUpdate.sql b/db/changes/10320-monitors/00-ticket_componentMakeUpdate.sql deleted file mode 100644 index 242b09d34c..0000000000 --- a/db/changes/10320-monitors/00-ticket_componentMakeUpdate.sql +++ /dev/null @@ -1,92 +0,0 @@ -DROP PROCEDURE `vn`.`ticket_componentMakeUpdate`; - -DELIMITER $$ -$$ -CREATE - DEFINER = root@`%` PROCEDURE `vn`.`ticket_componentMakeUpdate`(IN vTicketFk INT, IN vClientFk INT, IN vAgencyModeFk INT, - IN vAddressFk INT, IN vZoneFk INT, IN vWarehouseFk TINYINT, - IN vCompanyFk SMALLINT, IN vShipped DATETIME, - IN vLanded DATE, IN vIsDeleted TINYINT(1), - IN vHasToBeUnrouted TINYINT(1), IN vOption INT) -BEGIN -/** - * Modifica en el ticket los campos que se le pasan por parámetro - * y cambia sus componentes. - * Este procedimiento es transacionado en Salix - * - * @param vTicketFk Id del ticket a modificar - * @param vClientFk nuevo cliente - * @param vAgencyModeFk nueva agencia - * @param vAddressFk nuevo consignatario - * @param vZoneFk nueva zona - * @param vWarehouseFk nuevo almacen - * @param vCompanyFk nueva empresa - * @param vShipped nueva fecha del envio de mercancia - * @param vLanded nueva fecha de recepcion de mercancia - * @param vIsDeleted si se borra el ticket - * @param vHasToBeUnrouted si se le elimina la ruta al ticket - * @param vOption opcion para el case del proc ticketComponentUpdateSale - */ - DECLARE vPrice DECIMAL(10,2); - DECLARE vBonus DECIMAL(10,2); - - CALL ticket_componentPreview (vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk); - - IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN - - UPDATE ticket t - JOIN address a ON a.id = vAddressFk - SET t.nickname = a.nickname - WHERE t.id = vTicketFk; - - END IF; - - CALL zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); - - SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus - FROM tmp.zoneGetShipped - WHERE shipped BETWEEN DATE(vShipped) AND util.dayEnd(vShipped) AND warehouseFk = vWarehouseFk LIMIT 1; - - UPDATE ticket t - SET - t.clientFk = vClientFk, - t.agencyModeFk = vAgencyModeFk, - t.addressFk = vAddressFk, - t.zoneFk = vZoneFk, - t.zonePrice = vPrice, - t.zoneBonus = vBonus, - t.warehouseFk = vWarehouseFk, - t.companyFk = vCompanyFk, - t.landed = vLanded, - t.shipped = vShipped, - t.isDeleted = vIsDeleted - WHERE - t.id = vTicketFk; - - IF vHasToBeUnrouted THEN - UPDATE ticket t SET t.routeFk = NULL - WHERE t.id = vTicketFk; - END IF; - - IF vOption <> 8 THEN - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale - (PRIMARY KEY (saleFk)) - ENGINE = MEMORY - SELECT id AS saleFk, vWarehouseFk warehouseFk - FROM sale s WHERE s.ticketFk = vTicketFk; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; - CREATE TEMPORARY TABLE tmp.ticketComponent - SELECT * FROM tmp.ticketComponentPreview; - - CALL ticketComponentUpdateSale (vOption); - - DROP TEMPORARY TABLE tmp.sale; - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; - END IF; - - DROP TEMPORARY TABLE tmp.zoneGetShipped, tmp.ticketComponentPreview; -END;;$$ -DELIMITER ; - diff --git a/db/changes/10320-monitors/01-warehouse.sql b/db/changes/10320-monitors/01-warehouse.sql deleted file mode 100644 index 45e1c0c561..0000000000 --- a/db/changes/10320-monitors/01-warehouse.sql +++ /dev/null @@ -1,4 +0,0 @@ -ALTER TABLE `vn`.`warehouse` - ADD `code` VARCHAR(3) NULL AFTER name; - -UPDATE `vn`.`warehouse` SET `code` = 'ALG' WHERE `id` = 60; \ No newline at end of file diff --git a/db/changes/10320-monitors/02-starredModule.sql b/db/changes/10320-monitors/02-starredModule.sql deleted file mode 100644 index ee00a80bde..0000000000 --- a/db/changes/10320-monitors/02-starredModule.sql +++ /dev/null @@ -1,9 +0,0 @@ -ALTER TABLE `vn`.`starredModule` - ADD `position` INT NOT NULL AFTER `moduleFk`; - -SET @count:=0; -UPDATE `vn`.`starredModule` sm - JOIN ( - SELECT sm.id, IF(@workerFk = sm.workerFk, @count:=@count+1, @count:=1) AS position, @workerFk:=sm.workerFk - FROM `vn`.`starredModule` sm ORDER BY workerFk, moduleFk ASC) AS smt ON smt.id = sm.id - SET sm.position = smt.position; \ No newline at end of file diff --git a/db/changes/10330-jun2021/00-invoiceInLog.sql b/db/changes/10330-jun2021/00-invoiceLog.sql similarity index 100% rename from db/changes/10330-jun2021/00-invoiceInLog.sql rename to db/changes/10330-jun2021/00-invoiceLog.sql diff --git a/db/changes/10340-summer/00-ACL.sql b/db/changes/10340-summer/00-ACL.sql new file mode 100644 index 0000000000..dff946e4b5 --- /dev/null +++ b/db/changes/10340-summer/00-ACL.sql @@ -0,0 +1,15 @@ +DELETE FROM `salix`.`ACL` WHERE id = 189; +DELETE FROM `salix`.`ACL` WHERE id = 188; +UPDATE `salix`.`ACL` tdms SET tdms.accessType = '*' + WHERE tdms.id = 165; + +INSERT INTO `salix`.`ACL` (model, principalId, property, accessType) + VALUES + ('InvoiceInTax','administrative', '*', '*'), + ('InvoiceInLog','administrative', '*', 'READ'); + +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES + ('InvoiceOut', 'createManualInvoice', 'WRITE', 'ALLOW', 'ROLE', 'invoicing'), + ('InvoiceOut', 'globalInvoicing', 'WRITE', 'ALLOW', 'ROLE', 'invoicing'); + diff --git a/db/changes/10340-summer/00-buy_importReference.sql b/db/changes/10340-summer/00-buy_importReference.sql new file mode 100644 index 0000000000..f6bdc059c8 --- /dev/null +++ b/db/changes/10340-summer/00-buy_importReference.sql @@ -0,0 +1,14 @@ +create table `vn`.`itemMatchProperties` +( + itemFk int not null, + name varchar(80) not null, + producer varchar(80) not null, + size int not null, + constraint itemMatchProperties_pk + primary key (itemFk, name, producer, size), + constraint itemFk___fk + foreign key (itemFk) references item (id) + on update cascade on delete cascade +) +comment 'Propiedades para encontrar articulos equivalentes en verdnatura'; + diff --git a/db/changes/10340-summer/00-invoiceFromClient.sql b/db/changes/10340-summer/00-invoiceFromClient.sql new file mode 100644 index 0000000000..d198e873d5 --- /dev/null +++ b/db/changes/10340-summer/00-invoiceFromClient.sql @@ -0,0 +1,21 @@ +drop procedure `vn`.`invoiceFromClient`; + +DELIMITER $$ +$$ +create + definer = root@`%` procedure `vn`.`invoiceFromClient`(IN vMaxTicketDate datetime, IN vClientFk INT, IN vCompanyFk INT) +BEGIN + DECLARE vMinTicketDate DATE DEFAULT TIMESTAMPADD(YEAR, -3, CURDATE()); + SET vMaxTicketDate = util.dayend(vMaxTicketDate); + + DROP TEMPORARY TABLE IF EXISTS `ticketToInvoice`; + CREATE TEMPORARY TABLE `ticketToInvoice` + (PRIMARY KEY (`id`)) + ENGINE = MEMORY + SELECT id FROM ticket t + WHERE t.clientFk = vClientFk + AND t.refFk IS NULL + AND t.companyFk = vCompanyFk + AND (t.shipped BETWEEN vMinTicketDate AND vMaxTicketDate); +END;;$$ +DELIMITER ; diff --git a/db/changes/10340-summer/00-invoiceOut_newFromClient.sql b/db/changes/10340-summer/00-invoiceOut_newFromClient.sql new file mode 100644 index 0000000000..b4d4f916b7 --- /dev/null +++ b/db/changes/10340-summer/00-invoiceOut_newFromClient.sql @@ -0,0 +1,45 @@ +drop procedure `vn`.`invoiceOut_newFromClient`; + +DELIMITER $$ +$$ +create + definer = root@`%` procedure `vn`.`invoiceOut_newFromClient`(IN vClientFk 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 cliente hasta una fecha dada + * @param vClientFk Id del cliente a facturar + * @param vSerial Serie de factura + * @param vMaxShipped Fecha hasta la cual cogera tickets para facturar + * @param vCompanyFk Id de la empresa desde la que se factura + * @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 THEN + SELECT isRefEditable INTO vIsRefEditable + FROM invoiceOutSerial + WHERE code = vSerial; + + IF NOT vIsRefEditable THEN + CALL util.throw('serial non editable'); + END IF; + END IF; + + CALL invoiceFromClient(vMaxShipped, vClientFk, vCompanyFk); + CALL invoiceOut_new(vSerial, 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/changes/10340-summer/00-invoiceOut_newFromTicket.sql b/db/changes/10340-summer/00-invoiceOut_newFromTicket.sql new file mode 100644 index 0000000000..15be3d83ce --- /dev/null +++ b/db/changes/10340-summer/00-invoiceOut_newFromTicket.sql @@ -0,0 +1,38 @@ +drop procedure `vn`.`invoiceOut_newFromTicket`; + +DELIMITER $$ +$$ +create + definer = root@`%` procedure `vn`.`invoiceOut_newFromTicket`(IN vTicketFk int, IN vSerial char(2), IN vTaxArea varchar(25), + IN vRef varchar(25), OUT vInvoiceId int) +BEGIN +/** + * Factura un ticket + * @param vTicketFk Id del ticket + * @param vSerial Serie de factura + * @param vTaxArea Area de la factura en caso de querer forzarlo, + * en la mayoria de los casos poner NULL + * @return vInvoiceId + */ + DECLARE vIsRefEditable BOOLEAN; + CALL invoiceFromTicket(vTicketFk); + CALL invoiceOut_new(vSerial, CURDATE(), vTaxArea, vInvoiceId); + + IF vRef 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; + + UPDATE invoiceOut + SET `ref` = vRef + WHERE id = vInvoiceId; + END IF; + + IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN + CALL invoiceOutBooking(vInvoiceId); + END IF; +END;;$$ +DELIMITER ; diff --git a/db/changes/10340-summer/00-sample.sql b/db/changes/10340-summer/00-sample.sql new file mode 100644 index 0000000000..d4858ac72b --- /dev/null +++ b/db/changes/10340-summer/00-sample.sql @@ -0,0 +1,7 @@ +ALTER TABLE `vn`.`sample` ADD COLUMN + (`datepickerEnabled` TINYINT(1) NOT NULL DEFAULT 0); + +ALTER TABLE `vn`.`sample` MODIFY code VARCHAR(25) charset utf8 NOT NULL; + +INSERT INTO `vn`.`sample` (code, description, isVisible, hasCompany, hasPreview, datepickerEnabled) + VALUES ('client-debt-statement', 'Extracto del cliente', 1, 0, 1, 1); \ No newline at end of file diff --git a/db/changes/10340-summer/00-ticket_close.sql b/db/changes/10340-summer/00-ticket_close.sql new file mode 100644 index 0000000000..a8086549c0 --- /dev/null +++ b/db/changes/10340-summer/00-ticket_close.sql @@ -0,0 +1,109 @@ +drop procedure `vn`.`ticket_close`; + +DELIMITER $$ +$$ +create + definer = root@`%` procedure `vn`.`ticket_close`() +BEGIN +/** + * Realiza el cierre de todos los + * tickets de la tabla tmp.ticket_close. + * + * @table tmp.ticket_close(ticketFk) Identificadores de los tickets a cerrar + */ + DECLARE vDone BOOL; + DECLARE vClientFk INT; + DECLARE vCurTicketFk INT; + DECLARE vIsTaxDataChecked BOOL; + DECLARE vCompanyFk INT; + DECLARE vShipped DATE; + DECLARE vNewInvoiceId INT; + DECLARE vHasDailyInvoice BOOL; + DECLARE vWithPackage BOOL; + DECLARE vHasToInvoice BOOL; + + DECLARE cur CURSOR FOR + SELECT ticketFk FROM tmp.ticket_close; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + RESIGNAL; + END; + + OPEN cur; + + proc: LOOP + SET vDone = FALSE; + + FETCH cur INTO vCurTicketFk; + + IF vDone THEN + LEAVE proc; + END IF; + + -- Fetch ticket data + SELECT + c.id, + c.isTaxDataChecked, + t.companyFk, + t.shipped, + co.hasDailyInvoice, + w.isManaged, + c.hasToInvoice + INTO vClientFk, + vIsTaxDataChecked, + vCompanyFk, + vShipped, + vHasDailyInvoice, + vWithPackage, + vHasToInvoice + FROM ticket t + JOIN `client` c ON c.id = t.clientFk + JOIN province p ON p.id = c.provinceFk + JOIN country co ON co.id = p.countryFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.id = vCurTicketFk; + + INSERT INTO ticketPackaging (ticketFk, packagingFk, quantity) + (SELECT vCurTicketFk, p.id, COUNT(*) + FROM expedition e + JOIN packaging p ON p.itemFk = e.itemFk + WHERE e.ticketFk = vCurTicketFk AND p.isPackageReturnable + AND vWithPackage + GROUP BY p.itemFk); + + -- No retornables o no catalogados + INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, isPriceFixed) + (SELECT e.itemFk, vCurTicketFk, i.name, COUNT(*) AS amount, getSpecialPrice(e.itemFk, vClientFk), 1 + FROM expedition e + JOIN item i ON i.id = e.itemFk + LEFT JOIN packaging p ON p.itemFk = i.id + WHERE e.ticketFk = vCurTicketFk AND IFNULL(p.isPackageReturnable, 0) = 0 + AND getSpecialPrice(e.itemFk, vClientFk) > 0 + GROUP BY e.itemFk); + + CALL vn.zonePromo_Make(); + + IF(vHasDailyInvoice) AND vHasToInvoice THEN + + -- Facturacion rapida + CALL ticketTrackingAdd(vCurTicketFk, 'DELIVERED', NULL); + -- Facturar si está contabilizado + IF vIsTaxDataChecked THEN + CALL invoiceOut_newFromClient( + vClientFk, + (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), + vShipped, + vCompanyFk, + NULL, + NULL, + vNewInvoiceId); + END IF; + ELSE + CALL ticketTrackingAdd(vCurTicketFk, (SELECT vn.getAlert3State(vCurTicketFk)), NULL); + END IF; + END LOOP; + + CLOSE cur; +END;;$$ +DELIMITER ; diff --git a/db/changes/10340-summer/00-ticket_closeAll.sql b/db/changes/10340-summer/00-ticket_closeAll.sql new file mode 100644 index 0000000000..6441f2c1a7 --- /dev/null +++ b/db/changes/10340-summer/00-ticket_closeAll.sql @@ -0,0 +1,118 @@ +drop procedure `vn`.`ticket_closeAll`; + +DELIMITER $$ +$$ +create definer = root@`%` procedure `vn`.`ticket_closeAll__`() +BEGIN +/** + * Realiza el cierre de todos los + * tickets de la tabla tmp.ticketClosure. + * + * @param vTicketFk Id del ticket + */ + DECLARE vDone BOOL; + DECLARE vClientFk INT; + DECLARE vCurTicketFk INT; + DECLARE vIsTaxDataChecked BOOL; + DECLARE vCompanyFk INT; + DECLARE vShipped DATE; + DECLARE vNewInvoiceId INT; + DECLARE vHasDailyInvoice BOOL; + DECLARE vWithPackage BOOL; + DECLARE vHasToInvoice BOOL; + + DECLARE cur CURSOR FOR + SELECT ticketFk FROM tmp.ticketClosure; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + RESIGNAL; + END; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure2; + CREATE TEMPORARY TABLE tmp.ticketClosure2 + SELECT ticketFk FROM tmp.ticketClosure; + + INSERT INTO tmp.ticketClosure + SELECT id FROM stowaway s + JOIN tmp.ticketClosure2 tc ON s.shipFk = tc.ticketFk; + OPEN cur; + + proc: LOOP + SET vDone = FALSE; + + FETCH cur INTO vCurTicketFk; + + IF vDone THEN + LEAVE proc; + END IF; + + -- ticketClosure start + SELECT + c.id, + c.isTaxDataChecked, + t.companyFk, + t.shipped, + co.hasDailyInvoice, + w.isManaged, + c.hasToInvoice + INTO vClientFk, + vIsTaxDataChecked, + vCompanyFk, + vShipped, + vHasDailyInvoice, + vWithPackage, + vHasToInvoice + FROM ticket t + JOIN `client` c ON c.id = t.clientFk + JOIN province p ON p.id = c.provinceFk + JOIN country co ON co.id = p.countryFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.id = vCurTicketFk; + + INSERT INTO ticketPackaging (ticketFk, packagingFk, quantity) + (SELECT vCurTicketFk, p.id, COUNT(*) + FROM expedition e + JOIN packaging p ON p.itemFk = e.itemFk + WHERE e.ticketFk = vCurTicketFk AND p.isPackageReturnable + AND vWithPackage + GROUP BY p.itemFk); + + -- No retornables o no catalogados + INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, isPriceFixed) + (SELECT e.itemFk, vCurTicketFk, i.name, COUNT(*) AS amount, getSpecialPrice(e.itemFk, vClientFk), 1 + FROM expedition e + JOIN item i ON i.id = e.itemFk + LEFT JOIN packaging p ON p.itemFk = i.id + WHERE e.ticketFk = vCurTicketFk AND IFNULL(p.isPackageReturnable, 0) = 0 + AND getSpecialPrice(e.itemFk, vClientFk) > 0 + GROUP BY e.itemFk); + + CALL vn.zonePromo_Make(); + + IF(vHasDailyInvoice) AND vHasToInvoice THEN + + -- Facturacion rapida + CALL ticketTrackingAdd(vCurTicketFk, 'DELIVERED', NULL); + -- Facturar si está contabilizado + IF vIsTaxDataChecked THEN + CALL invoiceOut_newFromClient( + vClientFk, + (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), + vShipped, + vCompanyFk, + NULL, + NULL, + vNewInvoiceId); + END IF; + ELSE + CALL ticketTrackingAdd(vCurTicketFk, (SELECT vn.getAlert3State(vCurTicketFk)), NULL); + END IF; + END LOOP; + + CLOSE cur; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure; +END;;$$ +DELIMITER ; + diff --git a/db/changes/10340-summer/00-ticket_closeByTicket.sql b/db/changes/10340-summer/00-ticket_closeByTicket.sql new file mode 100644 index 0000000000..a24ea5ad9e --- /dev/null +++ b/db/changes/10340-summer/00-ticket_closeByTicket.sql @@ -0,0 +1,34 @@ +drop procedure `vn`.`ticket_closeByTicket`; + +DELIMITER $$ +$$ +create + definer = root@`%` procedure `vn`.`ticket_closeByTicket`(IN vTicketFk int) +BEGIN + +/** + * Inserta el ticket en la tabla temporal + * para ser cerrado. + * + * @param vTicketFk Id del ticket + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket_close; + CREATE TEMPORARY TABLE tmp.ticket_close ENGINE = MEMORY ( + SELECT + t.id AS ticketFk + FROM expedition e + INNER JOIN ticket t ON t.id = e.ticketFk + LEFT JOIN ticketState ts ON ts.ticketFk = t.id + JOIN alertLevel al ON al.id = ts.alertLevel + WHERE + al.code = 'PACKED' + AND t.id = vTicketFk + AND t.refFk IS NULL + GROUP BY e.ticketFk); + + CALL ticket_close(); + + DROP TEMPORARY TABLE tmp.ticket_close; +END;;$$ +DELIMITER ; diff --git a/db/changes/10340-summer/01-credit_request.sql b/db/changes/10340-summer/01-credit_request.sql new file mode 100644 index 0000000000..8216233269 --- /dev/null +++ b/db/changes/10340-summer/01-credit_request.sql @@ -0,0 +1,2 @@ +INSERT INTO `vn`.`sample` (`code`, `description`, `isVisible`, `hasCompany`, `hasPreview`) + VALUES ('credit-request', 'Solicitud de crédito', 1, 1, 1); \ No newline at end of file diff --git a/db/changes/10350-august/00-supplierAccountTrigger.sql b/db/changes/10350-august/00-supplierAccountTrigger.sql new file mode 100644 index 0000000000..a71b011262 --- /dev/null +++ b/db/changes/10350-august/00-supplierAccountTrigger.sql @@ -0,0 +1 @@ +DROP TRIGGER vn.supplierAccount_AfterInsert; diff --git a/db/changes/10350-august/00-ticket_afterUpdate.sql b/db/changes/10350-august/00-ticket_afterUpdate.sql new file mode 100644 index 0000000000..7f579d7b6f --- /dev/null +++ b/db/changes/10350-august/00-ticket_afterUpdate.sql @@ -0,0 +1,33 @@ +DROP TRIGGER IF EXISTS vn.ticket_afterUpdate; + +DELIMITER $$ +$$ +CREATE DEFINER=`root`@`%` TRIGGER vn.`ticket_afterUpdate` + AFTER UPDATE ON `ticket` + FOR EACH ROW +BEGIN + + IF !(NEW.id <=> OLD.id) + OR !(NEW.warehouseFk <=> OLD.warehouseFk) + OR !(NEW.shipped <=> OLD.shipped) THEN + CALL stock.log_add('ticket', NEW.id, OLD.id); + END IF; + + IF !(NEW.clientFk <=> OLD.clientFk) + OR !(NEW.addressFk <=> OLD.addressFk) + OR !(NEW.companyFk <=> OLD.companyFk) THEN + CALL ticket_requestRecalc(NEW.id); + END IF; + + IF NEW.clientFk = 2067 AND !(NEW.clientFk <=> OLD.clientFk) THEN + -- Fallo que se insertan no se sabe como tickets en este cliente + INSERT INTO vn.mail SET + `sender` = 'jgallego@verdnatura.es', + `replyTo` = 'jgallego@verdnatura.es', + `subject` = 'Modificado ticket al cliente 2067', + `body` = CONCAT(account.myUserGetName(), ' ha modificado el ticket ', + NEW.id); + END IF; + +END$$ +DELIMITER ; diff --git a/db/changes/10360-september/00-ACL.sql b/db/changes/10360-september/00-ACL.sql new file mode 100644 index 0000000000..6a3fcf708e --- /dev/null +++ b/db/changes/10360-september/00-ACL.sql @@ -0,0 +1,4 @@ +DELETE FROM `salix`.`ACL` WHERE id = 48; +DELETE FROM `salix`.`ACL` WHERE id = 49; +DELETE FROM `salix`.`ACL` WHERE id = 50; +DELETE FROM `salix`.`ACL` WHERE id = 107; \ No newline at end of file diff --git a/db/changes/10320-monitors/00-sale_getProblems.sql b/db/changes/10360-september/00-sale_problems.sql similarity index 90% rename from db/changes/10320-monitors/00-sale_getProblems.sql rename to db/changes/10360-september/00-sale_problems.sql index 290dcddb29..2702b524ce 100644 --- a/db/changes/10320-monitors/00-sale_getProblems.sql +++ b/db/changes/10360-september/00-sale_problems.sql @@ -1,9 +1,9 @@ -DROP PROCEDURE IF EXISTS `vn`.`sale_getProblems`; +drop procedure `vn`.`sale_getProblems`; DELIMITER $$ $$ -CREATE - DEFINER = root@`%` PROCEDURE `vn`.`sale_getProblems`(IN vIsTodayRelative TINYINT(1)) +create + definer = root@`%` procedure `vn`.`sale_getProblems`(IN vIsTodayRelative tinyint(1)) BEGIN /** * Calcula los problemas de cada venta @@ -32,6 +32,7 @@ BEGIN saleFk INT(11), isFreezed INTEGER(1) DEFAULT 0, risk DECIMAL(10,2) DEFAULT 0, + hasHighRisk TINYINT(1) DEFAULT 0, hasTicketRequest INTEGER(1) DEFAULT 0, isAvailable INTEGER(1) DEFAULT 1, itemShortage VARCHAR(250), @@ -59,6 +60,10 @@ BEGIN JOIN vn.sale s ON s.ticketFk = tl.ticketFk LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id LEFT JOIN vn.component c ON c.id = sc.componentFk AND c.isRequired + JOIN vn.ticket t ON t.id = tl.ticketFk + JOIN vn.agencyMode am ON am.id = t.agencyModeFk + JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk + WHERE dm.code IN('AGENCY','DELIVERY','PICKUP') GROUP BY tl.ticketFk, s.id; INSERT INTO tmp.sale_problems(ticketFk, isFreezed) @@ -78,18 +83,18 @@ BEGIN CALL clientGetDebt(CURDATE()); - INSERT INTO tmp.sale_problems(ticketFk, risk) - SELECT DISTINCT tl.ticketFk, r.risk + INSERT INTO tmp.sale_problems(ticketFk, risk, hasHighRisk) + SELECT DISTINCT tl.ticketFk, r.risk, ((r.risk - cc.riskTolerance) > c.credit + 10) FROM tmp.ticket_list tl JOIN vn.ticket t ON t.id = tl.ticketFk JOIN vn.agencyMode a ON t.agencyModeFk = a.id JOIN tmp.risk r ON r.clientFk = t.clientFk JOIN vn.client c ON c.id = t.clientFk JOIN vn.clientConfig cc - WHERE r.risk - cc.riskTolerance > c.credit + 10 + WHERE r.risk > c.credit + 10 AND a.isRiskFree = FALSE ON DUPLICATE KEY UPDATE - risk = r.risk; + risk = r.risk, hasHighRisk = ((r.risk - cc.riskTolerance) > c.credit + 10); INSERT INTO tmp.sale_problems(ticketFk, hasTicketRequest) SELECT DISTINCT tl.ticketFk, TRUE @@ -124,7 +129,7 @@ BEGIN AND vWarehouse = t.warehouseFk GROUP BY tl.ticketFk ON DUPLICATE KEY UPDATE - isAvailable = FALSE, saleFk = VALUE(saleFk); + isAvailable = FALSE, saleFk = VALUES(saleFk); INSERT INTO tmp.sale_problems(ticketFk, itemShortage, saleFk) SELECT ticketFk, problem, saleFk @@ -190,4 +195,3 @@ BEGIN tmp.ticket_list; END;;$$ DELIMITER ; - diff --git a/db/changes/10320-monitors/00-ticket_getProblems.sql b/db/changes/10360-september/00-ticket_getProblems.sql similarity index 61% rename from db/changes/10320-monitors/00-ticket_getProblems.sql rename to db/changes/10360-september/00-ticket_getProblems.sql index 290a083dfd..dacba7e090 100644 --- a/db/changes/10320-monitors/00-ticket_getProblems.sql +++ b/db/changes/10360-september/00-ticket_getProblems.sql @@ -1,9 +1,9 @@ -DROP PROCEDURE IF EXISTS `vn`.`ticket_getProblems`; +drop procedure `vn`.`ticket_getProblems`; DELIMITER $$ $$ -CREATE - DEFINER = root@`%` PROCEDURE `vn`.`ticket_getProblems`(IN vIsTodayRelative TINYINT(1)) +create + definer = root@`%` procedure `vn`.`ticket_getProblems`(IN vIsTodayRelative tinyint(1)) BEGIN /** * Calcula los problemas para un conjunto de tickets. @@ -22,14 +22,26 @@ BEGIN ticketFk, MAX(p.isFreezed) AS isFreezed, MAX(p.risk) AS risk, + MAX(p.hasHighRisk) AS hasHighRisk, MAX(p.hasTicketRequest) AS hasTicketRequest, MIN(p.isAvailable) AS isAvailable, MAX(p.itemShortage) AS itemShortage, MIN(p.isTaxDataChecked) AS isTaxDataChecked, - MAX(p.hasComponentLack) AS hasComponentLack + MAX(p.hasComponentLack) AS hasComponentLack, + 0 AS totalProblems FROM tmp.sale_problems p GROUP BY ticketFk; + UPDATE tmp.ticket_problems tp + SET tp.totalProblems = ( + (tp.isFreezed) + + IF(tp.risk, TRUE, FALSE) + + (tp.hasTicketRequest) + + (tp.isAvailable = 0) + + (tp.isTaxDataChecked = 0) + + (tp.hasComponentLack) + ); + DROP TEMPORARY TABLE tmp.sale_problems; END;;$$ diff --git a/db/changes/10360-september/01-travelThermograph.sql b/db/changes/10360-september/01-travelThermograph.sql new file mode 100644 index 0000000000..dec86d1020 --- /dev/null +++ b/db/changes/10360-september/01-travelThermograph.sql @@ -0,0 +1 @@ +alter table `vn`.`travelThermograph` modify `temperature` enum('COOL', 'WARM') null; \ No newline at end of file diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index b8f17d6edb..9cb7e9a0cb 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -1,6 +1,6 @@ USE `util`; --- MariaDB dump 10.19 Distrib 10.5.9-MariaDB, for debian-linux-gnu (x86_64) +-- MariaDB dump 10.19 Distrib 10.6.4-MariaDB, for Linux (x86_64) -- -- Host: db.verdnatura.es Database: util -- ------------------------------------------------------ @@ -22,7 +22,7 @@ USE `util`; LOCK TABLES `config` WRITE; /*!40000 ALTER TABLE `config` DISABLE KEYS */; -INSERT INTO `config` VALUES (1,'10300',0,'production',NULL); +INSERT INTO `config` VALUES (1,'10330',0,'production',NULL); /*!40000 ALTER TABLE `config` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; @@ -34,9 +34,9 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2021-05-25 11:53:07 +-- Dump completed on 2021-08-31 14:42:28 USE `account`; --- MariaDB dump 10.19 Distrib 10.5.9-MariaDB, for debian-linux-gnu (x86_64) +-- MariaDB dump 10.19 Distrib 10.6.4-MariaDB, for Linux (x86_64) -- -- Host: db.verdnatura.es Database: account -- ------------------------------------------------------ @@ -58,7 +58,7 @@ USE `account`; LOCK TABLES `role` WRITE; /*!40000 ALTER TABLE `role` DISABLE KEYS */; -INSERT INTO `role` VALUES (1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2017-11-29 10:06:31'),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35'),(13,'teamBoss','Jefe de departamento',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10'),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27'),(20,'manager','Departamento de gerencia',1,'2017-06-01 14:57:02','2017-06-01 14:57:51'),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52'),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12'),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36'),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27'),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20'),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34'),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53'),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42'),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08'),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53'),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09'),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41'),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12'),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26'),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59'),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16'),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12'),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23'),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18'),(48,'coolerBoss','Jefe del departamento de cámara',1,'2018-02-23 13:12:01','2018-02-23 13:12:01'),(49,'production','Empleado de producción',1,'2018-02-26 15:28:23','2021-02-12 09:42:35'),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12'),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39'),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57'),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57'),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17'),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31'),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02'),(57,'deliveryBoss','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19'),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45'),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10'),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01'),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07'),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05'),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08'),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26'),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56'),(67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 08:09:23','2020-01-03 08:09:23'),(69,'coolerAssist','Empleado cámara con permiso compras',1,'2020-02-05 12:36:09','2020-02-05 12:36:09'),(70,'trainee','Alumno de prácticas',1,'2020-03-04 11:00:25','2020-03-04 11:00:25'),(71,'checker','Rol de revisor con privilegios de itemPicker',1,'2020-10-02 10:50:07','2020-10-02 10:50:07'),(72,'claimManager','Personal de reclamaciones',1,'2020-10-13 10:01:32','2020-10-26 07:29:46'),(73,'financial','Departamento de finanzas',1,'2020-11-16 09:30:27','2020-11-16 09:30:27'),(74,'userPhotos','Privilegios para subir fotos de usuario',1,'2021-02-03 10:24:27','2021-02-03 10:24:27'),(75,'catalogPhotos','Privilegios para subir fotos del catálogo',1,'2021-02-03 10:24:27','2021-02-03 10:24:27'),(76,'chat','Rol para utilizar el rocket chat',1,'2020-11-27 13:06:50','2020-12-17 07:49:41'),(100,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2020-11-12 06:50:07'); +INSERT INTO `role` VALUES (1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2017-11-29 10:06:31'),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35'),(13,'teamBoss','Jefe de equipo/departamento',1,'2017-05-19 07:04:58','2021-06-30 13:29:30'),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10'),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27'),(20,'manager','Departamento de gerencia',1,'2017-06-01 14:57:02','2017-06-01 14:57:51'),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52'),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12'),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36'),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27'),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20'),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34'),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53'),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42'),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08'),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53'),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09'),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41'),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12'),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26'),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59'),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16'),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12'),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23'),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18'),(48,'coolerBoss','Jefe del departamento de cámara',1,'2018-02-23 13:12:01','2018-02-23 13:12:01'),(49,'production','Empleado de producción',1,'2018-02-26 15:28:23','2021-02-12 09:42:35'),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12'),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39'),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57'),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57'),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17'),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31'),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02'),(57,'deliveryBoss','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19'),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45'),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10'),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01'),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07'),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05'),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08'),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26'),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56'),(67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 08:09:23','2020-01-03 08:09:23'),(69,'coolerAssist','Empleado cámara con permiso compras',1,'2020-02-05 12:36:09','2020-02-05 12:36:09'),(70,'trainee','Alumno de prácticas',1,'2020-03-04 11:00:25','2020-03-04 11:00:25'),(71,'checker','Rol de revisor con privilegios de itemPicker',1,'2020-10-02 10:50:07','2020-10-02 10:50:07'),(72,'claimManager','Personal de reclamaciones',1,'2020-10-13 10:01:32','2020-10-26 07:29:46'),(73,'financial','Departamento de finanzas',1,'2020-11-16 09:30:27','2020-11-16 09:30:27'),(74,'userPhotos','Privilegios para subir fotos de usuario',1,'2021-02-03 10:24:27','2021-02-03 10:24:27'),(75,'catalogPhotos','Privilegios para subir fotos del catálogo',1,'2021-02-03 10:24:27','2021-02-03 10:24:27'),(76,'chat','Rol para utilizar el rocket chat',1,'2020-11-27 13:06:50','2020-12-17 07:49:41'),(100,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2020-11-12 06:50:07'),(101,'buyerBoss','Jefe del departamento de compras',1,'2021-06-16 09:53:17','2021-06-16 09:53:17'); /*!40000 ALTER TABLE `role` ENABLE KEYS */; UNLOCK TABLES; @@ -68,7 +68,7 @@ UNLOCK TABLES; LOCK TABLES `roleInherit` WRITE; /*!40000 ALTER TABLE `roleInherit` DISABLE KEYS */; -INSERT INTO `roleInherit` VALUES (1,1,2),(2,1,3),(3,1,70),(4,2,11),(5,3,11),(6,5,1),(7,5,21),(8,5,33),(124,5,76),(123,9,76),(9,9,100),(10,11,6),(11,13,1),(12,15,35),(143,15,49),(13,15,57),(114,15,76),(14,16,13),(15,16,15),(127,16,76),(16,17,20),(17,17,37),(18,17,39),(19,17,64),(145,17,67),(136,17,76),(20,18,1),(132,18,76),(21,19,21),(22,20,13),(23,20,16),(24,20,65),(134,20,76),(25,21,13),(26,21,18),(27,21,53),(131,21,76),(28,22,13),(29,22,21),(30,30,5),(31,30,20),(32,30,22),(33,30,53),(34,30,64),(118,30,76),(35,31,1),(36,32,1),(37,34,1),(38,34,13),(39,34,33),(40,35,1),(142,35,75),(129,35,76),(41,36,44),(42,36,47),(43,37,1),(139,37,74),(125,37,76),(44,38,37),(45,38,64),(126,38,76),(46,39,5),(47,39,21),(48,39,57),(115,39,76),(49,40,1),(50,40,49),(51,41,13),(52,41,35),(53,41,40),(135,41,76),(54,42,35),(55,42,49),(128,42,76),(56,43,13),(57,43,42),(58,44,1),(59,45,13),(60,45,44),(61,47,1),(62,48,13),(63,48,47),(64,49,36),(65,49,58),(66,50,13),(67,50,21),(68,50,35),(69,50,49),(70,50,57),(71,50,59),(133,50,76),(72,51,1),(140,51,74),(141,51,75),(73,52,13),(74,52,19),(75,52,35),(76,52,51),(137,52,76),(77,53,1),(78,54,1),(79,55,13),(80,55,54),(81,56,1),(82,57,13),(83,57,56),(138,57,76),(84,58,1),(85,59,13),(109,59,50),(87,60,5),(88,60,37),(89,60,50),(90,60,57),(130,60,76),(91,61,13),(92,61,36),(93,65,19),(94,65,35),(95,65,50),(117,65,76),(122,66,76),(96,66,100),(97,67,5),(98,67,37),(99,69,35),(100,69,47),(101,70,11),(144,70,76),(102,71,1),(103,71,58),(104,72,13),(105,72,18),(106,73,5),(108,73,19),(107,73,64); +INSERT INTO `roleInherit` VALUES (1,1,2),(2,1,3),(3,1,70),(4,2,11),(5,3,11),(6,5,1),(7,5,21),(8,5,33),(124,5,76),(123,9,76),(9,9,100),(10,11,6),(11,13,1),(12,15,35),(143,15,49),(150,15,56),(114,15,76),(14,16,13),(15,16,15),(127,16,76),(16,17,20),(17,17,37),(18,17,39),(19,17,64),(145,17,67),(136,17,76),(20,18,1),(132,18,76),(21,19,21),(22,20,13),(23,20,16),(24,20,65),(134,20,76),(25,21,13),(26,21,18),(27,21,53),(131,21,76),(28,22,13),(29,22,21),(30,30,5),(31,30,20),(32,30,22),(33,30,53),(34,30,64),(118,30,76),(35,31,1),(36,32,1),(37,34,1),(38,34,13),(39,34,33),(40,35,1),(142,35,75),(129,35,76),(41,36,44),(42,36,47),(43,37,1),(139,37,74),(125,37,76),(146,38,13),(44,38,37),(45,38,64),(126,38,76),(46,39,5),(47,39,21),(48,39,57),(115,39,76),(49,40,1),(50,40,49),(51,41,13),(52,41,35),(53,41,40),(135,41,76),(54,42,35),(55,42,49),(128,42,76),(56,43,13),(57,43,42),(58,44,1),(59,45,13),(60,45,44),(61,47,1),(62,48,13),(153,48,35),(63,48,47),(64,49,36),(65,49,58),(66,50,13),(67,50,21),(68,50,35),(69,50,49),(70,50,57),(71,50,59),(133,50,76),(72,51,1),(140,51,74),(141,51,75),(73,52,13),(74,52,19),(75,52,35),(76,52,51),(137,52,76),(77,53,1),(78,54,1),(79,55,13),(80,55,54),(81,56,1),(82,57,13),(83,57,56),(138,57,76),(84,58,1),(85,59,13),(109,59,50),(87,60,5),(88,60,37),(89,60,50),(90,60,57),(130,60,76),(91,61,13),(92,61,36),(93,65,19),(94,65,35),(95,65,50),(117,65,76),(122,66,76),(96,66,100),(97,67,5),(98,67,37),(99,69,35),(152,69,47),(101,70,11),(144,70,76),(102,71,1),(103,71,58),(104,72,13),(105,72,18),(106,73,5),(108,73,19),(107,73,64),(148,101,13),(147,101,35); /*!40000 ALTER TABLE `roleInherit` ENABLE KEYS */; UNLOCK TABLES; @@ -78,7 +78,7 @@ UNLOCK TABLES; LOCK TABLES `roleRole` WRITE; /*!40000 ALTER TABLE `roleRole` DISABLE KEYS */; -INSERT INTO `roleRole` VALUES (37416,1,1),(37417,1,2),(37418,1,3),(37422,1,6),(37421,1,11),(37419,1,70),(37420,1,76),(37334,2,2),(37336,2,6),(37335,2,11),(37229,3,3),(37231,3,6),(37230,3,11),(37201,5,1),(37208,5,2),(37207,5,3),(37200,5,5),(37212,5,6),(37211,5,11),(37205,5,13),(37209,5,18),(37202,5,21),(37203,5,33),(37210,5,53),(37206,5,70),(37204,5,76),(37487,6,6),(37380,9,1),(37377,9,2),(37365,9,3),(37363,9,5),(37385,9,6),(37355,9,9),(37360,9,11),(37412,9,13),(37394,9,15),(37395,9,16),(37362,9,17),(37410,9,18),(37409,9,19),(37396,9,20),(37408,9,21),(37413,9,22),(37383,9,30),(37384,9,31),(37381,9,32),(37391,9,33),(37366,9,34),(37370,9,35),(37406,9,36),(37388,9,37),(37389,9,38),(37361,9,39),(37386,9,40),(37387,9,41),(37367,9,42),(37368,9,43),(37358,9,44),(37359,9,45),(37374,9,47),(37376,9,48),(37403,9,49),(37405,9,50),(37397,9,51),(37398,9,52),(37390,9,53),(37392,9,54),(37393,9,55),(37378,9,56),(37379,9,57),(37401,9,58),(37402,9,59),(37404,9,60),(37407,9,61),(37399,9,62),(37369,9,64),(37400,9,65),(37411,9,66),(37364,9,67),(37375,9,69),(37414,9,70),(37372,9,71),(37373,9,72),(37382,9,73),(37415,9,74),(37371,9,75),(37356,9,76),(37357,9,100),(37148,11,6),(37147,11,11),(37948,13,1),(37949,13,2),(37950,13,3),(37954,13,6),(37953,13,11),(37947,13,13),(37951,13,70),(37952,13,76),(37573,15,1),(37580,15,2),(37579,15,3),(37582,15,6),(37581,15,11),(37574,15,13),(37565,15,15),(37566,15,35),(37571,15,36),(37577,15,44),(37576,15,47),(37567,15,49),(37575,15,56),(37568,15,57),(37570,15,58),(37578,15,70),(37572,15,75),(37569,15,76),(37589,16,1),(37594,16,2),(37593,16,3),(37601,16,6),(37600,16,11),(37584,16,13),(37585,16,15),(37583,16,16),(37588,16,35),(37595,16,36),(37599,16,44),(37598,16,47),(37587,16,49),(37597,16,56),(37590,16,57),(37596,16,58),(37592,16,70),(37591,16,75),(37586,16,76),(37174,17,1),(37183,17,2),(37182,17,3),(37172,17,5),(37195,17,6),(37191,17,11),(37177,17,13),(37187,17,15),(37176,17,16),(37165,17,17),(37188,17,18),(37186,17,19),(37166,17,20),(37178,17,21),(37180,17,33),(37185,17,35),(37197,17,36),(37167,17,37),(37168,17,39),(37199,17,44),(37198,17,47),(37194,17,49),(37184,17,50),(37189,17,53),(37190,17,56),(37179,17,57),(37196,17,58),(37192,17,59),(37169,17,64),(37175,17,65),(37170,17,67),(37181,17,70),(37173,17,74),(37193,17,75),(37171,17,76),(37879,18,1),(37882,18,2),(37881,18,3),(37885,18,6),(37884,18,11),(37878,18,18),(37883,18,70),(37880,18,76),(37872,19,1),(37875,19,2),(37874,19,3),(37877,19,6),(37876,19,11),(37868,19,13),(37869,19,18),(37866,19,19),(37867,19,21),(37870,19,53),(37873,19,70),(37871,19,76),(37610,20,1),(37616,20,2),(37615,20,3),(37628,20,6),(37625,20,11),(37603,20,13),(37609,20,15),(37604,20,16),(37621,20,18),(37608,20,19),(37602,20,20),(37617,20,21),(37607,20,35),(37624,20,36),(37627,20,44),(37626,20,47),(37613,20,49),(37611,20,50),(37620,20,53),(37622,20,56),(37612,20,57),(37623,20,58),(37619,20,59),(37605,20,65),(37614,20,70),(37618,20,75),(37606,20,76),(37860,21,1),(37863,21,2),(37862,21,3),(37865,21,6),(37864,21,11),(37856,21,13),(37857,21,18),(37855,21,21),(37858,21,53),(37861,21,70),(37859,21,76),(37959,22,1),(37964,22,2),(37963,22,3),(37966,22,6),(37965,22,11),(37956,22,13),(37958,22,18),(37957,22,21),(37955,22,22),(37960,22,53),(37962,22,70),(37961,22,76),(37459,30,1),(37465,30,2),(37464,30,3),(37448,30,5),(37476,30,6),(37472,30,11),(37456,30,13),(37461,30,15),(37455,30,16),(37462,30,18),(37460,30,19),(37449,30,20),(37458,30,21),(37450,30,22),(37447,30,30),(37457,30,33),(37466,30,35),(37475,30,36),(37478,30,44),(37477,30,47),(37471,30,49),(37467,30,50),(37451,30,53),(37473,30,56),(37470,30,57),(37474,30,58),(37468,30,59),(37452,30,64),(37454,30,65),(37463,30,70),(37469,30,75),(37453,30,76),(37480,31,1),(37481,31,2),(37482,31,3),(37486,31,6),(37485,31,11),(37479,31,31),(37483,31,70),(37484,31,76),(37424,32,1),(37425,32,2),(37426,32,3),(37430,32,6),(37429,32,11),(37423,32,32),(37427,32,70),(37428,32,76),(37546,33,33),(37233,34,1),(37238,34,2),(37237,34,3),(37241,34,6),(37240,34,11),(37234,34,13),(37235,34,33),(37232,34,34),(37236,34,70),(37239,34,76),(37276,35,1),(37281,35,2),(37280,35,3),(37283,35,6),(37282,35,11),(37275,35,35),(37279,35,70),(37277,35,75),(37278,35,76),(37775,36,1),(37777,36,2),(37776,36,3),(37781,36,6),(37780,36,11),(37772,36,36),(37773,36,44),(37774,36,47),(37778,36,70),(37779,36,76),(37519,37,1),(37524,37,2),(37523,37,3),(37526,37,6),(37525,37,11),(37518,37,37),(37522,37,70),(37520,37,74),(37521,37,76),(37532,38,1),(37535,38,2),(37534,38,3),(37537,38,6),(37536,38,11),(37528,38,37),(37527,38,38),(37529,38,64),(37533,38,70),(37531,38,74),(37530,38,76),(37157,39,1),(37162,39,2),(37161,39,3),(37150,39,5),(37164,39,6),(37163,39,11),(37155,39,13),(37154,39,18),(37151,39,21),(37156,39,33),(37149,39,39),(37158,39,53),(37159,39,56),(37152,39,57),(37160,39,70),(37153,39,76),(37489,40,1),(37492,40,2),(37491,40,3),(37500,40,6),(37499,40,11),(37494,40,36),(37488,40,40),(37497,40,44),(37496,40,47),(37490,40,49),(37495,40,58),(37493,40,70),(37498,40,76),(37508,41,1),(37512,41,2),(37511,41,3),(37517,41,6),(37516,41,11),(37502,41,13),(37503,41,35),(37509,41,36),(37504,41,40),(37501,41,41),(37515,41,44),(37514,41,47),(37506,41,49),(37513,41,58),(37510,41,70),(37507,41,75),(37505,41,76),(37248,42,1),(37253,42,2),(37252,42,3),(37256,42,6),(37255,42,11),(37243,42,35),(37246,42,36),(37242,42,42),(37250,42,44),(37254,42,47),(37244,42,49),(37249,42,58),(37251,42,70),(37247,42,75),(37245,42,76),(37261,43,1),(37267,43,2),(37266,43,3),(37273,43,6),(37272,43,11),(37258,43,13),(37260,43,35),(37268,43,36),(37259,43,42),(37257,43,43),(37271,43,44),(37270,43,47),(37262,43,49),(37269,43,58),(37265,43,70),(37264,43,75),(37263,43,76),(37130,44,1),(37131,44,2),(37132,44,3),(37136,44,6),(37135,44,11),(37129,44,44),(37133,44,70),(37134,44,76),(37140,45,1),(37142,45,2),(37141,45,3),(37146,45,6),(37145,45,11),(37138,45,13),(37139,45,44),(37137,45,45),(37143,45,70),(37144,45,76),(37306,47,1),(37307,47,2),(37308,47,3),(37312,47,6),(37311,47,11),(37305,47,47),(37309,47,70),(37310,47,76),(37327,48,1),(37329,48,2),(37328,48,3),(37333,48,6),(37332,48,11),(37325,48,13),(37326,48,47),(37324,48,48),(37330,48,70),(37331,48,76),(37716,49,1),(37719,49,2),(37718,49,3),(37722,49,6),(37721,49,11),(37712,49,36),(37715,49,44),(37714,49,47),(37711,49,49),(37713,49,58),(37717,49,70),(37720,49,76),(37764,50,1),(37769,50,2),(37768,50,3),(37771,50,6),(37770,50,11),(37751,50,13),(37763,50,18),(37752,50,21),(37753,50,35),(37760,50,36),(37766,50,44),(37765,50,47),(37754,50,49),(37750,50,50),(37762,50,53),(37758,50,56),(37755,50,57),(37759,50,58),(37756,50,59),(37767,50,70),(37761,50,75),(37757,50,76),(37630,51,1),(37635,51,2),(37634,51,3),(37638,51,6),(37637,51,11),(37629,51,51),(37633,51,70),(37631,51,74),(37632,51,75),(37636,51,76),(37648,52,1),(37653,52,2),(37652,52,3),(37655,52,6),(37654,52,11),(37640,52,13),(37650,52,18),(37641,52,19),(37647,52,21),(37642,52,35),(37643,52,51),(37639,52,52),(37649,52,53),(37651,52,70),(37645,52,74),(37646,52,75),(37644,52,76),(37539,53,1),(37540,53,2),(37541,53,3),(37545,53,6),(37544,53,11),(37538,53,53),(37542,53,70),(37543,53,76),(37548,54,1),(37549,54,2),(37550,54,3),(37554,54,6),(37553,54,11),(37547,54,54),(37551,54,70),(37552,54,76),(37558,55,1),(37560,55,2),(37559,55,3),(37564,55,6),(37563,55,11),(37556,55,13),(37557,55,54),(37555,55,55),(37561,55,70),(37562,55,76),(37338,56,1),(37339,56,2),(37340,56,3),(37344,56,6),(37343,56,11),(37337,56,56),(37341,56,70),(37342,56,76),(37349,57,1),(37352,57,2),(37351,57,3),(37354,57,6),(37353,57,11),(37346,57,13),(37347,57,56),(37345,57,57),(37350,57,70),(37348,57,76),(37682,58,1),(37683,58,2),(37684,58,3),(37688,58,6),(37687,58,11),(37681,58,58),(37685,58,70),(37686,58,76),(37693,59,1),(37703,59,2),(37702,59,3),(37710,59,6),(37709,59,11),(37690,59,13),(37700,59,18),(37692,59,21),(37694,59,35),(37704,59,36),(37708,59,44),(37707,59,47),(37695,59,49),(37691,59,50),(37699,59,53),(37706,59,56),(37696,59,57),(37705,59,58),(37689,59,59),(37701,59,70),(37698,59,75),(37697,59,76),(37733,60,1),(37745,60,2),(37744,60,3),(37724,60,5),(37749,60,6),(37748,60,11),(37729,60,13),(37742,60,18),(37732,60,21),(37731,60,33),(37734,60,35),(37739,60,36),(37725,60,37),(37747,60,44),(37746,60,47),(37735,60,49),(37726,60,50),(37741,60,53),(37737,60,56),(37727,60,57),(37738,60,58),(37736,60,59),(37723,60,60),(37743,60,70),(37730,60,74),(37740,60,75),(37728,60,76),(37786,61,1),(37790,61,2),(37789,61,3),(37793,61,6),(37792,61,11),(37783,61,13),(37784,61,36),(37785,61,44),(37787,61,47),(37782,61,61),(37788,61,70),(37791,61,76),(37656,62,62),(37274,64,64),(37664,65,1),(37673,65,2),(37672,65,3),(37680,65,6),(37679,65,11),(37662,65,13),(37675,65,18),(37658,65,19),(37665,65,21),(37659,65,35),(37670,65,36),(37678,65,44),(37677,65,47),(37666,65,49),(37660,65,50),(37674,65,53),(37676,65,56),(37667,65,57),(37669,65,58),(37668,65,59),(37657,65,65),(37671,65,70),(37663,65,75),(37661,65,76),(37912,66,1),(37908,66,2),(37896,66,3),(37894,66,5),(37917,66,6),(37911,66,9),(37891,66,11),(37943,66,13),(37926,66,15),(37927,66,16),(37893,66,17),(37942,66,18),(37941,66,19),(37928,66,20),(37940,66,21),(37944,66,22),(37915,66,30),(37916,66,31),(37913,66,32),(37923,66,33),(37897,66,34),(37901,66,35),(37938,66,36),(37920,66,37),(37921,66,38),(37892,66,39),(37918,66,40),(37919,66,41),(37898,66,42),(37899,66,43),(37889,66,44),(37890,66,45),(37905,66,47),(37907,66,48),(37935,66,49),(37937,66,50),(37929,66,51),(37930,66,52),(37922,66,53),(37924,66,54),(37925,66,55),(37909,66,56),(37910,66,57),(37933,66,58),(37934,66,59),(37936,66,60),(37939,66,61),(37931,66,62),(37900,66,64),(37932,66,65),(37886,66,66),(37895,66,67),(37906,66,69),(37945,66,70),(37903,66,71),(37904,66,72),(37914,66,73),(37946,66,74),(37902,66,75),(37887,66,76),(37888,66,100),(37217,67,1),(37225,67,2),(37224,67,3),(37214,67,5),(37228,67,6),(37227,67,11),(37222,67,13),(37221,67,18),(37216,67,21),(37218,67,33),(37215,67,37),(37226,67,53),(37213,67,67),(37223,67,70),(37220,67,74),(37219,67,76),(37317,69,1),(37321,69,2),(37320,69,3),(37323,69,6),(37322,69,11),(37314,69,35),(37315,69,47),(37313,69,69),(37319,69,70),(37316,69,75),(37318,69,76),(37970,70,6),(37968,70,11),(37967,70,70),(37969,70,76),(37287,71,1),(37290,71,2),(37289,71,3),(37294,71,6),(37293,71,11),(37288,71,58),(37291,71,70),(37286,71,71),(37292,71,76),(37299,72,1),(37301,72,2),(37300,72,3),(37304,72,6),(37303,72,11),(37296,72,13),(37297,72,18),(37302,72,70),(37295,72,72),(37298,72,76),(37437,73,1),(37442,73,2),(37441,73,3),(37432,73,5),(37446,73,6),(37445,73,11),(37439,73,13),(37443,73,18),(37433,73,19),(37436,73,21),(37435,73,33),(37444,73,53),(37434,73,64),(37440,73,70),(37431,73,73),(37438,73,76),(37971,74,74),(37284,75,75),(37285,76,76),(37819,100,1),(37815,100,2),(37802,100,3),(37800,100,5),(37824,100,6),(37818,100,9),(37797,100,11),(37851,100,13),(37833,100,15),(37834,100,16),(37799,100,17),(37849,100,18),(37848,100,19),(37835,100,20),(37847,100,21),(37852,100,22),(37822,100,30),(37823,100,31),(37820,100,32),(37830,100,33),(37803,100,34),(37807,100,35),(37845,100,36),(37827,100,37),(37828,100,38),(37798,100,39),(37825,100,40),(37826,100,41),(37804,100,42),(37805,100,43),(37795,100,44),(37796,100,45),(37812,100,47),(37814,100,48),(37842,100,49),(37844,100,50),(37836,100,51),(37837,100,52),(37829,100,53),(37831,100,54),(37832,100,55),(37816,100,56),(37817,100,57),(37840,100,58),(37841,100,59),(37843,100,60),(37846,100,61),(37838,100,62),(37806,100,64),(37839,100,65),(37850,100,66),(37801,100,67),(37813,100,69),(37853,100,70),(37810,100,71),(37811,100,72),(37821,100,73),(37854,100,74),(37808,100,75),(37809,100,76),(37794,100,100); +INSERT INTO `roleRole` VALUES (44924,1,1),(44925,1,2),(44926,1,3),(44930,1,6),(44929,1,11),(44927,1,70),(44928,1,76),(44841,2,2),(44843,2,6),(44842,2,11),(44723,3,3),(44725,3,6),(44724,3,11),(44695,5,1),(44702,5,2),(44701,5,3),(44694,5,5),(44706,5,6),(44705,5,11),(44699,5,13),(44703,5,18),(44696,5,21),(44697,5,33),(44704,5,53),(44700,5,70),(44698,5,76),(44995,6,6),(44888,9,1),(44885,9,2),(44872,9,3),(44870,9,5),(44893,9,6),(44862,9,9),(44867,9,11),(44920,9,13),(44902,9,15),(44903,9,16),(44869,9,17),(44918,9,18),(44917,9,19),(44904,9,20),(44916,9,21),(44921,9,22),(44891,9,30),(44892,9,31),(44889,9,32),(44899,9,33),(44873,9,34),(44877,9,35),(44914,9,36),(44896,9,37),(44897,9,38),(44868,9,39),(44894,9,40),(44895,9,41),(44874,9,42),(44875,9,43),(44865,9,44),(44866,9,45),(44882,9,47),(44884,9,48),(44911,9,49),(44913,9,50),(44905,9,51),(44906,9,52),(44898,9,53),(44900,9,54),(44901,9,55),(44886,9,56),(44887,9,57),(44909,9,58),(44910,9,59),(44912,9,60),(44915,9,61),(44907,9,62),(44876,9,64),(44908,9,65),(44919,9,66),(44871,9,67),(44883,9,69),(44922,9,70),(44880,9,71),(44881,9,72),(44890,9,73),(44923,9,74),(44879,9,75),(44863,9,76),(44864,9,100),(44878,9,101),(44642,11,6),(44641,11,11),(45456,13,1),(45457,13,2),(45458,13,3),(45462,13,6),(45461,13,11),(45455,13,13),(45459,13,70),(45460,13,76),(45082,15,1),(45086,15,2),(45085,15,3),(45089,15,6),(45088,15,11),(45074,15,15),(45075,15,35),(45080,15,36),(45083,15,44),(45087,15,47),(45076,15,49),(45077,15,56),(45079,15,58),(45084,15,70),(45081,15,75),(45078,15,76),(45096,16,1),(45101,16,2),(45100,16,3),(45107,16,6),(45106,16,11),(45091,16,13),(45092,16,15),(45090,16,16),(45095,16,35),(45102,16,36),(45105,16,44),(45104,16,47),(45094,16,49),(45097,16,56),(45103,16,58),(45099,16,70),(45098,16,75),(45093,16,76),(44668,17,1),(44677,17,2),(44676,17,3),(44666,17,5),(44689,17,6),(44685,17,11),(44671,17,13),(44681,17,15),(44670,17,16),(44659,17,17),(44682,17,18),(44680,17,19),(44660,17,20),(44672,17,21),(44674,17,33),(44679,17,35),(44691,17,36),(44661,17,37),(44662,17,39),(44693,17,44),(44692,17,47),(44688,17,49),(44678,17,50),(44683,17,53),(44684,17,56),(44673,17,57),(44690,17,58),(44686,17,59),(44663,17,64),(44669,17,65),(44664,17,67),(44675,17,70),(44667,17,74),(44687,17,75),(44665,17,76),(45386,18,1),(45389,18,2),(45388,18,3),(45392,18,6),(45391,18,11),(45385,18,18),(45390,18,70),(45387,18,76),(45379,19,1),(45382,19,2),(45381,19,3),(45384,19,6),(45383,19,11),(45375,19,13),(45376,19,18),(45373,19,19),(45374,19,21),(45377,19,53),(45380,19,70),(45378,19,76),(45116,20,1),(45122,20,2),(45121,20,3),(45134,20,6),(45131,20,11),(45109,20,13),(45115,20,15),(45110,20,16),(45128,20,18),(45114,20,19),(45108,20,20),(45123,20,21),(45113,20,35),(45130,20,36),(45133,20,44),(45132,20,47),(45119,20,49),(45117,20,50),(45127,20,53),(45118,20,56),(45125,20,57),(45129,20,58),(45126,20,59),(45111,20,65),(45120,20,70),(45124,20,75),(45112,20,76),(45367,21,1),(45370,21,2),(45369,21,3),(45372,21,6),(45371,21,11),(45363,21,13),(45364,21,18),(45362,21,21),(45365,21,53),(45368,21,70),(45366,21,76),(45467,22,1),(45472,22,2),(45471,22,3),(45474,22,6),(45473,22,11),(45464,22,13),(45466,22,18),(45465,22,21),(45463,22,22),(45468,22,53),(45470,22,70),(45469,22,76),(44967,30,1),(44973,30,2),(44972,30,3),(44956,30,5),(44984,30,6),(44981,30,11),(44964,30,13),(44969,30,15),(44963,30,16),(44970,30,18),(44968,30,19),(44957,30,20),(44966,30,21),(44958,30,22),(44955,30,30),(44965,30,33),(44974,30,35),(44983,30,36),(44986,30,44),(44985,30,47),(44980,30,49),(44975,30,50),(44959,30,53),(44979,30,56),(44977,30,57),(44982,30,58),(44976,30,59),(44960,30,64),(44962,30,65),(44971,30,70),(44978,30,75),(44961,30,76),(44988,31,1),(44989,31,2),(44990,31,3),(44994,31,6),(44993,31,11),(44987,31,31),(44991,31,70),(44992,31,76),(44932,32,1),(44933,32,2),(44934,32,3),(44938,32,6),(44937,32,11),(44931,32,32),(44935,32,70),(44936,32,76),(45055,33,33),(44727,34,1),(44732,34,2),(44731,34,3),(44735,34,6),(44734,34,11),(44728,34,13),(44729,34,33),(44726,34,34),(44730,34,70),(44733,34,76),(44770,35,1),(44775,35,2),(44774,35,3),(44777,35,6),(44776,35,11),(44769,35,35),(44773,35,70),(44771,35,75),(44772,35,76),(45281,36,1),(45283,36,2),(45282,36,3),(45287,36,6),(45286,36,11),(45278,36,36),(45279,36,44),(45280,36,47),(45284,36,70),(45285,36,76),(45027,37,1),(45032,37,2),(45031,37,3),(45034,37,6),(45033,37,11),(45026,37,37),(45030,37,70),(45028,37,74),(45029,37,76),(45041,38,1),(45044,38,2),(45043,38,3),(45046,38,6),(45045,38,11),(45036,38,13),(45037,38,37),(45035,38,38),(45038,38,64),(45042,38,70),(45040,38,74),(45039,38,76),(44651,39,1),(44656,39,2),(44655,39,3),(44644,39,5),(44658,39,6),(44657,39,11),(44649,39,13),(44648,39,18),(44645,39,21),(44650,39,33),(44643,39,39),(44652,39,53),(44653,39,56),(44646,39,57),(44654,39,70),(44647,39,76),(44997,40,1),(45000,40,2),(44999,40,3),(45008,40,6),(45007,40,11),(45002,40,36),(44996,40,40),(45005,40,44),(45004,40,47),(44998,40,49),(45003,40,58),(45001,40,70),(45006,40,76),(45016,41,1),(45020,41,2),(45019,41,3),(45025,41,6),(45024,41,11),(45010,41,13),(45011,41,35),(45017,41,36),(45012,41,40),(45009,41,41),(45023,41,44),(45022,41,47),(45014,41,49),(45021,41,58),(45018,41,70),(45015,41,75),(45013,41,76),(44742,42,1),(44747,42,2),(44746,42,3),(44750,42,6),(44749,42,11),(44737,42,35),(44740,42,36),(44736,42,42),(44744,42,44),(44748,42,47),(44738,42,49),(44743,42,58),(44745,42,70),(44741,42,75),(44739,42,76),(44755,43,1),(44761,43,2),(44760,43,3),(44767,43,6),(44766,43,11),(44752,43,13),(44754,43,35),(44762,43,36),(44753,43,42),(44751,43,43),(44765,43,44),(44764,43,47),(44756,43,49),(44763,43,58),(44759,43,70),(44758,43,75),(44757,43,76),(44624,44,1),(44625,44,2),(44626,44,3),(44630,44,6),(44629,44,11),(44623,44,44),(44627,44,70),(44628,44,76),(44634,45,1),(44636,45,2),(44635,45,3),(44640,45,6),(44639,45,11),(44632,45,13),(44633,45,44),(44631,45,45),(44637,45,70),(44638,45,76),(44811,47,1),(44812,47,2),(44813,47,3),(44817,47,6),(44816,47,11),(44810,47,47),(44814,47,70),(44815,47,76),(44835,48,1),(44838,48,2),(44837,48,3),(44840,48,6),(44839,48,11),(44830,48,13),(44831,48,35),(44832,48,47),(44829,48,48),(44836,48,70),(44834,48,75),(44833,48,76),(45222,49,1),(45225,49,2),(45224,49,3),(45228,49,6),(45227,49,11),(45218,49,36),(45221,49,44),(45220,49,47),(45217,49,49),(45219,49,58),(45223,49,70),(45226,49,76),(45270,50,1),(45275,50,2),(45274,50,3),(45277,50,6),(45276,50,11),(45257,50,13),(45269,50,18),(45258,50,21),(45259,50,35),(45266,50,36),(45272,50,44),(45271,50,47),(45260,50,49),(45256,50,50),(45268,50,53),(45264,50,56),(45261,50,57),(45265,50,58),(45262,50,59),(45273,50,70),(45267,50,75),(45263,50,76),(45136,51,1),(45141,51,2),(45140,51,3),(45144,51,6),(45143,51,11),(45135,51,51),(45139,51,70),(45137,51,74),(45138,51,75),(45142,51,76),(45154,52,1),(45159,52,2),(45158,52,3),(45161,52,6),(45160,52,11),(45146,52,13),(45156,52,18),(45147,52,19),(45153,52,21),(45148,52,35),(45149,52,51),(45145,52,52),(45155,52,53),(45157,52,70),(45151,52,74),(45152,52,75),(45150,52,76),(45048,53,1),(45049,53,2),(45050,53,3),(45054,53,6),(45053,53,11),(45047,53,53),(45051,53,70),(45052,53,76),(45057,54,1),(45058,54,2),(45059,54,3),(45063,54,6),(45062,54,11),(45056,54,54),(45060,54,70),(45061,54,76),(45067,55,1),(45069,55,2),(45068,55,3),(45073,55,6),(45072,55,11),(45065,55,13),(45066,55,54),(45064,55,55),(45070,55,70),(45071,55,76),(44845,56,1),(44846,56,2),(44847,56,3),(44851,56,6),(44850,56,11),(44844,56,56),(44848,56,70),(44849,56,76),(44856,57,1),(44859,57,2),(44858,57,3),(44861,57,6),(44860,57,11),(44853,57,13),(44854,57,56),(44852,57,57),(44857,57,70),(44855,57,76),(45188,58,1),(45189,58,2),(45190,58,3),(45194,58,6),(45193,58,11),(45187,58,58),(45191,58,70),(45192,58,76),(45199,59,1),(45209,59,2),(45208,59,3),(45216,59,6),(45215,59,11),(45196,59,13),(45206,59,18),(45198,59,21),(45200,59,35),(45210,59,36),(45214,59,44),(45213,59,47),(45201,59,49),(45197,59,50),(45205,59,53),(45212,59,56),(45202,59,57),(45211,59,58),(45195,59,59),(45207,59,70),(45204,59,75),(45203,59,76),(45239,60,1),(45251,60,2),(45250,60,3),(45230,60,5),(45255,60,6),(45254,60,11),(45235,60,13),(45248,60,18),(45238,60,21),(45237,60,33),(45240,60,35),(45245,60,36),(45231,60,37),(45253,60,44),(45252,60,47),(45241,60,49),(45232,60,50),(45247,60,53),(45243,60,56),(45233,60,57),(45244,60,58),(45242,60,59),(45229,60,60),(45249,60,70),(45236,60,74),(45246,60,75),(45234,60,76),(45292,61,1),(45296,61,2),(45295,61,3),(45299,61,6),(45298,61,11),(45289,61,13),(45290,61,36),(45291,61,44),(45293,61,47),(45288,61,61),(45294,61,70),(45297,61,76),(45162,62,62),(44768,64,64),(45170,65,1),(45179,65,2),(45178,65,3),(45186,65,6),(45185,65,11),(45168,65,13),(45181,65,18),(45164,65,19),(45171,65,21),(45165,65,35),(45176,65,36),(45184,65,44),(45183,65,47),(45172,65,49),(45166,65,50),(45180,65,53),(45182,65,56),(45173,65,57),(45175,65,58),(45174,65,59),(45163,65,65),(45177,65,70),(45169,65,75),(45167,65,76),(45420,66,1),(45416,66,2),(45403,66,3),(45401,66,5),(45425,66,6),(45419,66,9),(45398,66,11),(45451,66,13),(45434,66,15),(45435,66,16),(45400,66,17),(45450,66,18),(45449,66,19),(45436,66,20),(45448,66,21),(45452,66,22),(45423,66,30),(45424,66,31),(45421,66,32),(45431,66,33),(45404,66,34),(45408,66,35),(45446,66,36),(45428,66,37),(45429,66,38),(45399,66,39),(45426,66,40),(45427,66,41),(45405,66,42),(45406,66,43),(45396,66,44),(45397,66,45),(45413,66,47),(45415,66,48),(45443,66,49),(45445,66,50),(45437,66,51),(45438,66,52),(45430,66,53),(45432,66,54),(45433,66,55),(45417,66,56),(45418,66,57),(45441,66,58),(45442,66,59),(45444,66,60),(45447,66,61),(45439,66,62),(45407,66,64),(45440,66,65),(45393,66,66),(45402,66,67),(45414,66,69),(45453,66,70),(45411,66,71),(45412,66,72),(45422,66,73),(45454,66,74),(45410,66,75),(45394,66,76),(45395,66,100),(45409,66,101),(44711,67,1),(44719,67,2),(44718,67,3),(44708,67,5),(44722,67,6),(44721,67,11),(44716,67,13),(44715,67,18),(44710,67,21),(44712,67,33),(44709,67,37),(44720,67,53),(44707,67,67),(44717,67,70),(44714,67,74),(44713,67,76),(44822,69,1),(44826,69,2),(44825,69,3),(44828,69,6),(44827,69,11),(44819,69,35),(44820,69,47),(44818,69,69),(44824,69,70),(44821,69,75),(44823,69,76),(45478,70,6),(45476,70,11),(45475,70,70),(45477,70,76),(44792,71,1),(44795,71,2),(44794,71,3),(44799,71,6),(44798,71,11),(44793,71,58),(44796,71,70),(44791,71,71),(44797,71,76),(44804,72,1),(44806,72,2),(44805,72,3),(44809,72,6),(44808,72,11),(44801,72,13),(44802,72,18),(44807,72,70),(44800,72,72),(44803,72,76),(44945,73,1),(44950,73,2),(44949,73,3),(44940,73,5),(44954,73,6),(44953,73,11),(44947,73,13),(44951,73,18),(44941,73,19),(44944,73,21),(44943,73,33),(44952,73,53),(44942,73,64),(44948,73,70),(44939,73,73),(44946,73,76),(45479,74,74),(44789,75,75),(44790,76,76),(45326,100,1),(45322,100,2),(45308,100,3),(45306,100,5),(45331,100,6),(45325,100,9),(45303,100,11),(45358,100,13),(45340,100,15),(45341,100,16),(45305,100,17),(45356,100,18),(45355,100,19),(45342,100,20),(45354,100,21),(45359,100,22),(45329,100,30),(45330,100,31),(45327,100,32),(45337,100,33),(45309,100,34),(45313,100,35),(45352,100,36),(45334,100,37),(45335,100,38),(45304,100,39),(45332,100,40),(45333,100,41),(45310,100,42),(45311,100,43),(45301,100,44),(45302,100,45),(45319,100,47),(45321,100,48),(45349,100,49),(45351,100,50),(45343,100,51),(45344,100,52),(45336,100,53),(45338,100,54),(45339,100,55),(45323,100,56),(45324,100,57),(45347,100,58),(45348,100,59),(45350,100,60),(45353,100,61),(45345,100,62),(45312,100,64),(45346,100,65),(45357,100,66),(45307,100,67),(45320,100,69),(45360,100,70),(45317,100,71),(45318,100,72),(45328,100,73),(45361,100,74),(45315,100,75),(45316,100,76),(45300,100,100),(45314,100,101),(44782,101,1),(44786,101,2),(44785,101,3),(44788,101,6),(44787,101,11),(44779,101,13),(44780,101,35),(44784,101,70),(44781,101,75),(44783,101,76),(44778,101,101); /*!40000 ALTER TABLE `roleRole` ENABLE KEYS */; UNLOCK TABLES; @@ -120,9 +120,9 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2021-05-25 11:53:07 +-- Dump completed on 2021-08-31 14:42:28 USE `salix`; --- MariaDB dump 10.19 Distrib 10.5.9-MariaDB, for debian-linux-gnu (x86_64) +-- MariaDB dump 10.19 Distrib 10.6.4-MariaDB, for Linux (x86_64) -- -- Host: db.verdnatura.es Database: salix -- ------------------------------------------------------ @@ -144,7 +144,7 @@ USE `salix`; LOCK TABLES `ACL` WRITE; /*!40000 ALTER TABLE `ACL` DISABLE KEYS */; -INSERT INTO `ACL` VALUES (1,'Account','*','*','ALLOW','ROLE','employee'),(3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(7,'Client','*','*','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(18,'State','*','READ','ALLOW','ROLE','employee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(48,'ItemNiche','*','READ','ALLOW','ROLE','employee'),(49,'ItemNiche','*','WRITE','ALLOW','ROLE','buyer'),(50,'ItemNiche','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(62,'Ticket','*','*','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(71,'SaleChecked','*','READ','ALLOW','ROLE','employee'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','deleteSales','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(103,'ClaimEnd','importTicketSales','WRITE','ALLOW','ROLE','claimManager'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(107,'ItemNiche','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(123,'Worker','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','*','ALLOW','ROLE','deliveryBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'Calendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'Calendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(164,'InvoiceOut','regenerate','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','READ','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(174,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(175,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(188,'TicketDms','removeFile','WRITE','ALLOW','ROLE','employee'),(189,'TicketDms','*','READ','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryBoss'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','claimManager'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(219,'Account','acl','READ','ALLOW','ROLE','account'),(220,'Account','getCurrentUserData','READ','ALLOW','ROLE','account'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(222,'Client','*','READ','ALLOW','ROLE','trainee'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'),(234,'WorkerLog','*','READ','ALLOW','ROLE','salesAssistant'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'),(238,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(239,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(240,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(242,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(243,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(244,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(245,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(246,'Account','changePassword','*','ALLOW','ROLE','account'),(247,'UserAccount','exists','*','ALLOW','ROLE','account'),(248,'RoleMapping','*','READ','ALLOW','ROLE','account'),(249,'UserPassword','*','READ','ALLOW','ROLE','account'),(250,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(251,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(252,'Supplier','*','READ','ALLOW','ROLE','employee'),(253,'Supplier','*','WRITE','ALLOW','ROLE','administrative'),(254,'SupplierLog','*','READ','ALLOW','ROLE','employee'),(255,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(256,'Image','*','WRITE','ALLOW','ROLE','employee'),(257,'FixedPrice','*','*','ALLOW','ROLE','buyer'),(258,'PayDem','*','READ','ALLOW','ROLE','employee'),(259,'Client','createReceipt','*','ALLOW','ROLE','administrative'),(260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'),(261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'),(262,'Entry','*','*','ALLOW','ROLE','administrative'),(263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'),(264,'StarredModule','*','*','ALLOW','ROLE','employee'),(265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'),(266,'ZoneLog','*','READ','ALLOW','ROLE','employee'),(267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss'),(268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss'),(269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','invoicing'); +INSERT INTO `ACL` VALUES (1,'Account','*','*','ALLOW','ROLE','employee'),(3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(7,'Client','*','*','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(18,'State','*','READ','ALLOW','ROLE','employee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(48,'ItemNiche','*','READ','ALLOW','ROLE','employee'),(49,'ItemNiche','*','WRITE','ALLOW','ROLE','buyer'),(50,'ItemNiche','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(62,'Ticket','*','*','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(71,'SaleChecked','*','READ','ALLOW','ROLE','employee'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','deleteSales','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(103,'ClaimEnd','importTicketSales','WRITE','ALLOW','ROLE','claimManager'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(107,'ItemNiche','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(123,'Worker','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','*','ALLOW','ROLE','deliveryBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'Calendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'Calendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(164,'InvoiceOut','regenerate','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','READ','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(174,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(175,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(188,'TicketDms','removeFile','WRITE','ALLOW','ROLE','employee'),(189,'TicketDms','*','READ','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryBoss'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','claimManager'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(219,'Account','acl','READ','ALLOW','ROLE','account'),(220,'Account','getCurrentUserData','READ','ALLOW','ROLE','account'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(222,'Client','*','READ','ALLOW','ROLE','trainee'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'),(234,'WorkerLog','*','READ','ALLOW','ROLE','salesAssistant'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'),(238,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(239,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(240,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(242,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(244,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(246,'Account','changePassword','*','ALLOW','ROLE','account'),(247,'UserAccount','exists','*','ALLOW','ROLE','account'),(248,'RoleMapping','*','READ','ALLOW','ROLE','account'),(249,'UserPassword','*','READ','ALLOW','ROLE','account'),(250,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(251,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(252,'Supplier','*','READ','ALLOW','ROLE','employee'),(253,'Supplier','*','WRITE','ALLOW','ROLE','administrative'),(254,'SupplierLog','*','READ','ALLOW','ROLE','employee'),(256,'Image','*','WRITE','ALLOW','ROLE','employee'),(257,'FixedPrice','*','*','ALLOW','ROLE','buyer'),(258,'PayDem','*','READ','ALLOW','ROLE','employee'),(259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant'),(260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'),(261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'),(262,'Entry','*','*','ALLOW','ROLE','administrative'),(263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'),(264,'StarredModule','*','*','ALLOW','ROLE','employee'),(265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'),(266,'ZoneLog','*','READ','ALLOW','ROLE','employee'),(267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss'),(268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss'),(269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','invoicing'),(270,'SupplierAddress','*','*','ALLOW','ROLE','employee'),(271,'SalesMonitor','*','*','ALLOW','ROLE','employee'),(272,'InvoiceInLog','*','*','ALLOW','ROLE','employee'); /*!40000 ALTER TABLE `ACL` ENABLE KEYS */; UNLOCK TABLES; @@ -164,7 +164,7 @@ UNLOCK TABLES; LOCK TABLES `module` WRITE; /*!40000 ALTER TABLE `module` DISABLE KEYS */; -INSERT INTO `module` VALUES ('Claims'),('Clients'),('Entries'),('Invoices in'),('Invoices out'),('Items'),('Orders'),('Routes'),('Suppliers'),('Tickets'),('Travels'),('Users'),('Workers'),('Zones'); +INSERT INTO `module` VALUES ('Claims'),('Clients'),('Entries'),('Invoices in'),('Invoices out'),('Items'),('Monitors'),('Orders'),('Routes'),('Suppliers'),('Tickets'),('Travels'),('Users'),('Workers'),('Zones'); /*!40000 ALTER TABLE `module` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; @@ -176,9 +176,9 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2021-05-25 11:53:08 +-- Dump completed on 2021-08-31 14:42:29 USE `vn`; --- MariaDB dump 10.19 Distrib 10.5.9-MariaDB, for debian-linux-gnu (x86_64) +-- MariaDB dump 10.19 Distrib 10.6.4-MariaDB, for Linux (x86_64) -- -- Host: db.verdnatura.es Database: vn -- ------------------------------------------------------ @@ -200,7 +200,7 @@ USE `vn`; LOCK TABLES `alertLevel` WRITE; /*!40000 ALTER TABLE `alertLevel` DISABLE KEYS */; -INSERT INTO `alertLevel` VALUES ('DELIVERED',3),('FREE',0),('ON_PREPARATION',1),('PACKED',2); +INSERT INTO `alertLevel` VALUES ('FREE',0,0),('ON_PREPARATION',1,1),('PACKED',2,2),('DELIVERED',3,3); /*!40000 ALTER TABLE `alertLevel` ENABLE KEYS */; UNLOCK TABLES; @@ -214,6 +214,16 @@ INSERT INTO `bookingPlanner` VALUES (5,'2017-06-30 22:00:00','4770000002','WORLD /*!40000 ALTER TABLE `bookingPlanner` ENABLE KEYS */; UNLOCK TABLES; +-- +-- Dumping data for table `businessType` +-- + +LOCK TABLES `businessType` WRITE; +/*!40000 ALTER TABLE `businessType` DISABLE KEYS */; +INSERT INTO `businessType` VALUES ('decoration','Decoración'),('events','Eventos'),('florist','Floristería'),('mortuary','Funeraria'),('others','Otros'),('restoration','Restauración'),('wholesaler','Mayorista'); +/*!40000 ALTER TABLE `businessType` ENABLE KEYS */; +UNLOCK TABLES; + -- -- Dumping data for table `cplusInvoiceType472` -- @@ -370,7 +380,7 @@ UNLOCK TABLES; LOCK TABLES `department` WRITE; /*!40000 ALTER TABLE `department` DISABLE KEYS */; -INSERT INTO `department` VALUES (1,NULL,'VERDNATURA',1,2,763,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,0,NULL),(22,NULL,'COMPRAS',3,4,NULL,72,596,2,5,0,0,0,0,NULL,'/',NULL,1,NULL),(23,NULL,'CAMARA',14,19,NULL,72,604,2,6,1,0,1,2,37,'/37/',NULL,0,NULL),(31,'IT','INFORMATICA',5,6,NULL,72,127,3,9,0,0,0,0,NULL,'/','informatica-cau',1,NULL),(34,NULL,'CONTABILIDAD',7,8,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,1,NULL),(35,NULL,'FINANZAS',9,10,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,1,NULL),(36,NULL,'LABORAL',11,12,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,1,NULL),(37,NULL,'PRODUCCION',13,52,NULL,72,230,3,11,1,0,0,17,NULL,'/',NULL,0,NULL),(38,NULL,'SACADO',20,21,NULL,72,230,4,14,1,0,1,0,37,'/37/',NULL,0,NULL),(39,NULL,'ENCAJADO',22,23,NULL,72,230,4,12,1,0,1,0,37,'/37/',NULL,0,NULL),(41,NULL,'ADMINISTRACION',53,54,NULL,72,599,3,8,0,0,0,0,NULL,'/',NULL,1,NULL),(43,NULL,'VENTAS',55,76,NULL,0,NULL,NULL,NULL,0,0,0,10,NULL,'/',NULL,1,'direccioncomercial@verdnatura.es'),(44,NULL,'GERENCIA',77,78,NULL,72,300,2,7,0,0,0,0,NULL,'/',NULL,0,NULL),(45,NULL,'LOGISTICA',79,80,NULL,72,596,3,19,0,0,0,0,NULL,'/',NULL,1,NULL),(46,NULL,'REPARTO',81,84,NULL,72,659,3,10,0,0,0,1,NULL,'/',NULL,1,NULL),(48,NULL,'ALMACENAJE',85,86,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,'/',NULL,0,NULL),(49,NULL,'PROPIEDAD',87,88,NULL,72,1008,1,1,0,0,0,0,NULL,'/',NULL,0,NULL),(52,NULL,'CARGA AEREA',89,90,NULL,72,163,4,28,0,0,0,0,NULL,'/',NULL,0,NULL),(53,NULL,'MARKETING Y COMUNICACIÓN',91,92,NULL,72,1238,0,0,0,0,0,0,NULL,'/',NULL,1,NULL),(54,NULL,'ORNAMENTALES',93,94,NULL,72,433,3,21,0,0,0,0,NULL,'/',NULL,0,NULL),(55,NULL,'TALLER NATURAL',95,96,NULL,72,695,2,23,0,0,0,0,NULL,'/',NULL,0,NULL),(56,NULL,'TALLER ARTIFICIAL',97,98,NULL,72,1780,2,24,0,0,0,0,NULL,'/',NULL,0,NULL),(58,NULL,'CAMPOS',99,100,NULL,72,225,2,2,0,0,0,0,NULL,'/',NULL,0,NULL),(59,NULL,'MANTENIMIENTO',101,102,NULL,72,1907,4,16,0,0,0,0,NULL,'/',NULL,0,NULL),(60,NULL,'RECLAMACIONES',103,104,NULL,72,563,3,20,0,0,0,0,NULL,'/',NULL,1,NULL),(61,NULL,'VNH',105,106,NULL,73,1297,3,17,0,0,0,0,NULL,'/',NULL,0,NULL),(63,NULL,'VENTAS FRANCIA',56,57,NULL,72,277,2,27,0,0,1,0,43,'/43/',NULL,0,NULL),(66,NULL,'VERDNAMADRID',107,108,NULL,72,163,3,18,0,0,0,0,NULL,'/',NULL,0,NULL),(68,NULL,'COMPLEMENTOS',24,25,NULL,72,617,3,26,1,0,1,0,37,'/37/',NULL,0,NULL),(69,NULL,'VERDNABARNA',109,110,NULL,74,432,3,22,0,0,0,0,NULL,'/',NULL,0,NULL),(77,NULL,'PALETIZADO',82,83,NULL,72,230,4,15,1,0,1,0,46,'/46/',NULL,0,NULL),(80,NULL,'EQUIPO J VALLES',58,59,NULL,72,693,3,4,0,0,1,0,43,'/43/','jvp_equipo',1,NULL),(86,NULL,'LIMPIEZA',111,112,NULL,72,599,0,0,0,0,0,0,NULL,'/',NULL,0,NULL),(89,NULL,'COORDINACION',113,114,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,'/',NULL,0,NULL),(90,NULL,'TRAILER',115,116,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,0,NULL),(91,NULL,'ARTIFICIAL',26,27,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(92,NULL,'EQUIPO SILVERIO',60,61,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','sdc_equipo',1,NULL),(93,NULL,'CONFECCION',117,118,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,0,NULL),(94,NULL,'EQUIPO J BROCAL',62,63,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','jes_equipo',1,NULL),(95,NULL,'EQUIPO C ZAMBRANO',64,65,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','czg_equipo',1,NULL),(96,NULL,'EQUIPO C LOPEZ',66,67,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','cla_equipo',1,NULL),(98,NULL,'EQUIPO RODRIGO',68,69,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','rhr_equipo',1,NULL),(101,NULL,'EQUIPO J IBAÑEZ',70,71,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','jmi_equipo',1,NULL),(102,NULL,'EQ ROJO FV RUBEN C',28,29,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(103,NULL,'EQ AZUL FV A FOLQUES',30,31,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(104,NULL,'EQ AMARILLO FV NORMAN G',32,33,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(105,NULL,'EQ MORADO FV MATOU',34,35,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(106,NULL,'EQ VERDE PCA KEVIN GIMENEZ',36,37,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(107,NULL,'EQ NARANJA PCA RUBEN ZANON',38,39,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(110,NULL,'EQ ROSA PCA J BONDIA',40,41,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(111,NULL,'EQ REPONEDOR CAJAS',42,43,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(112,NULL,'CAMARA EQ EDGAR LLEO',15,16,NULL,0,NULL,NULL,NULL,1,0,2,0,23,'/37/23/',NULL,0,NULL),(113,NULL,'CAMARA EQ MARC ROCA',17,18,NULL,0,NULL,NULL,NULL,1,0,2,0,23,'/37/23/',NULL,0,NULL),(114,NULL,'EQ MARRON PCA JL NUEVO',44,45,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(115,NULL,'EQUIPO CLAUDI',72,73,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','csr_equipo',1,NULL),(120,NULL,'PCA PRODUCCION',46,47,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(121,NULL,'FV PRODUCCION',48,49,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(122,NULL,'PCA ALMACEN',50,51,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(123,NULL,'EQUIPO ELENA BASCUÑANA',74,75,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','ebt_equipo',1,NULL),(124,NULL,'CONTROL INTERNO',119,120,NULL,72,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,1,NULL); +INSERT INTO `department` VALUES (1,NULL,'VERDNATURA',1,2,763,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,0,NULL,0),(22,NULL,'COMPRAS',3,4,NULL,72,596,2,5,0,0,0,0,NULL,'/',NULL,1,NULL,1),(23,NULL,'CAMARA',14,19,NULL,72,604,2,6,1,0,1,2,37,'/37/',NULL,0,NULL,0),(31,'IT','INFORMATICA',5,6,NULL,72,127,3,9,0,0,0,0,NULL,'/','informatica-cau',1,NULL,1),(34,NULL,'CONTABILIDAD',7,8,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,1,NULL,1),(35,NULL,'FINANZAS',9,10,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,1,NULL,1),(36,NULL,'LABORAL',11,12,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,1,NULL,1),(37,NULL,'PRODUCCION',13,52,NULL,72,230,3,11,1,0,0,17,NULL,'/',NULL,0,NULL,0),(38,NULL,'SACADO',20,21,NULL,72,230,4,14,1,0,1,0,37,'/37/',NULL,0,NULL,0),(39,NULL,'ENCAJADO',22,23,NULL,72,230,4,12,1,0,1,0,37,'/37/',NULL,0,NULL,0),(41,NULL,'ADMINISTRACION',53,54,NULL,72,599,3,8,0,0,0,0,NULL,'/',NULL,1,NULL,1),(43,NULL,'VENTAS',55,78,NULL,0,NULL,NULL,NULL,0,0,0,11,NULL,'/',NULL,1,'direccioncomercial@verdnatura.es',1),(44,NULL,'GERENCIA',79,80,NULL,72,300,2,7,0,0,0,0,NULL,'/',NULL,0,NULL,0),(45,NULL,'LOGISTICA',81,82,NULL,72,596,3,19,0,0,0,0,NULL,'/',NULL,1,NULL,1),(46,NULL,'REPARTO',83,86,NULL,72,659,3,10,0,0,0,1,NULL,'/',NULL,0,NULL,0),(48,NULL,'ALMACENAJE',87,88,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,'/',NULL,0,NULL,0),(49,NULL,'PROPIEDAD',89,90,NULL,72,1008,1,1,0,0,0,0,NULL,'/',NULL,0,NULL,0),(52,NULL,'CARGA AEREA',91,92,NULL,72,163,4,28,0,0,0,0,NULL,'/',NULL,0,NULL,0),(53,NULL,'MARKETING Y COMUNICACIÓN',93,94,NULL,72,1238,0,0,0,0,0,0,NULL,'/',NULL,1,NULL,1),(54,NULL,'ORNAMENTALES',95,96,NULL,72,433,3,21,0,0,0,0,NULL,'/',NULL,0,NULL,0),(55,NULL,'TALLER NATURAL',97,98,NULL,72,695,2,23,0,0,0,0,NULL,'/',NULL,0,NULL,0),(56,NULL,'TALLER ARTIFICIAL',99,100,NULL,72,1780,2,24,0,0,0,0,NULL,'/',NULL,0,NULL,0),(58,NULL,'CAMPOS',101,102,NULL,72,225,2,2,0,0,0,0,NULL,'/',NULL,0,NULL,1),(59,NULL,'MANTENIMIENTO',103,104,NULL,72,1907,4,16,0,0,0,0,NULL,'/',NULL,0,NULL,0),(60,NULL,'RECLAMACIONES',105,106,NULL,72,563,3,20,0,0,0,0,NULL,'/',NULL,1,NULL,1),(61,NULL,'VNH',107,108,NULL,73,1297,3,17,0,0,0,0,NULL,'/',NULL,0,NULL,0),(63,NULL,'VENTAS FRANCIA',56,57,NULL,72,277,2,27,0,0,1,0,43,'/43/',NULL,0,NULL,0),(66,NULL,'VERDNAMADRID',109,110,NULL,72,163,3,18,0,0,0,0,NULL,'/',NULL,0,NULL,0),(68,NULL,'COMPLEMENTOS',24,25,NULL,72,617,3,26,1,0,1,0,37,'/37/',NULL,0,NULL,0),(69,NULL,'VERDNABARNA',111,112,NULL,74,432,3,22,0,0,0,0,NULL,'/',NULL,0,NULL,0),(77,NULL,'PALETIZADO',84,85,NULL,72,230,4,15,1,0,1,0,46,'/46/',NULL,0,NULL,0),(80,NULL,'EQUIPO J VALLES',58,59,NULL,72,693,3,4,0,0,1,0,43,'/43/','jvp_equipo',1,NULL,1),(86,NULL,'LIMPIEZA',113,114,NULL,72,599,0,0,0,0,0,0,NULL,'/',NULL,0,NULL,0),(89,NULL,'COORDINACION',115,116,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,'/',NULL,0,NULL,0),(90,NULL,'TRAILER',117,118,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,0,NULL,0),(91,NULL,'ARTIFICIAL',26,27,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL,0),(92,NULL,'EQUIPO SILVERIO',60,61,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','sdc_equipo',1,NULL,1),(93,NULL,'CONFECCION',119,120,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,0,NULL,0),(94,NULL,'EQUIPO J BROCAL',62,63,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','jes_equipo',1,NULL,1),(95,NULL,'EQUIPO C ZAMBRANO',64,65,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','czg_equipo',1,NULL,1),(96,NULL,'EQUIPO C LOPEZ',66,67,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','cla_equipo',1,NULL,1),(98,NULL,'EQUIPO RODRIGO',68,69,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','rhr_equipo',1,NULL,1),(101,NULL,'EQUIPO J IBAÑEZ',70,71,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','jmi_equipo',1,NULL,1),(102,NULL,'EQ ROJO FV RUBEN C',28,29,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL,0),(103,NULL,'EQ AZUL FV A FOLQUES',30,31,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL,0),(104,NULL,'EQ AMARILLO FV NORMAN G',32,33,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL,0),(105,NULL,'EQ MORADO FV MATOU',34,35,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL,0),(106,NULL,'EQ VERDE PCA KEVIN GIMENEZ',36,37,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL,0),(107,NULL,'EQ NARANJA PCA RUBEN ZANON',38,39,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL,0),(110,NULL,'EQ ROSA PCA J BONDIA',40,41,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL,0),(111,NULL,'EQ REPONEDOR CAJAS',42,43,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL,0),(112,NULL,'CAMARA EQ EDGAR LLEO',15,16,NULL,0,NULL,NULL,NULL,1,0,2,0,23,'/37/23/',NULL,0,NULL,0),(113,NULL,'CAMARA EQ MARC ROCA',17,18,NULL,0,NULL,NULL,NULL,1,0,2,0,23,'/37/23/',NULL,0,NULL,0),(114,NULL,'EQ MARRON PCA JL NUEVO',44,45,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL,0),(115,NULL,'EQUIPO CLAUDI',72,73,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','csr_equipo',1,NULL,1),(120,NULL,'PCA PRODUCCION',46,47,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL,0),(121,NULL,'FV PRODUCCION',48,49,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL,0),(122,NULL,'PCA ALMACEN',50,51,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL,0),(123,NULL,'EQUIPO ELENA BASCUÑANA',74,75,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','ebt_equipo',1,NULL,1),(124,NULL,'CONTROL INTERNO',121,122,NULL,72,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,1,NULL,1),(125,NULL,'EQUIPO MIRIAM MAR',76,77,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','mir_equipo',0,NULL,0),(126,NULL,'TALLER PRESERVADO',123,124,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,0,NULL,0); /*!40000 ALTER TABLE `department` ENABLE KEYS */; UNLOCK TABLES; @@ -410,7 +420,7 @@ UNLOCK TABLES; LOCK TABLES `volumeConfig` WRITE; /*!40000 ALTER TABLE `volumeConfig` DISABLE KEYS */; -INSERT INTO `volumeConfig` VALUES (2.67,1.60,0.8,150,0.30,120,57); +INSERT INTO `volumeConfig` VALUES (2.67,1.60,0.8,150,0.30,120,57,2.0); /*!40000 ALTER TABLE `volumeConfig` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; @@ -422,9 +432,9 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2021-05-25 11:53:09 +-- Dump completed on 2021-08-31 14:42:30 USE `cache`; --- MariaDB dump 10.19 Distrib 10.5.9-MariaDB, for debian-linux-gnu (x86_64) +-- MariaDB dump 10.19 Distrib 10.6.4-MariaDB, for Linux (x86_64) -- -- Host: db.verdnatura.es Database: cache -- ------------------------------------------------------ @@ -446,7 +456,7 @@ USE `cache`; LOCK TABLES `cache` WRITE; /*!40000 ALTER TABLE `cache` DISABLE KEYS */; -INSERT INTO `cache` VALUES (1,'equalizator','00:19:00'),(2,'available','00:06:00'),(3,'stock','00:30:00'),(4,'last_buy','00:30:00'),(5,'weekly_sales','12:00:00'),(6,'bionic','00:06:00'),(7,'sales','00:04:00'),(8,'visible','00:04:00'),(9,'item_range','00:03:00'),(10,'barcodes','01:00:00'),(11,'prod_graphic','00:17:00'),(12,'ticketShipping','00:01:00'),(13,'availableNoRaids','00:06:00'); +INSERT INTO `cache` VALUES (1,'equalizator','00:19:00'),(2,'available','00:06:00'),(3,'stock','00:30:00'),(4,'last_buy','00:30:00'),(5,'weekly_sales','12:00:00'),(6,'bionic','00:06:00'),(7,'sales','00:04:00'),(8,'visible','00:04:00'),(9,'item_range','00:03:00'),(10,'barcodes','01:00:00'),(11,'prod_graphic','00:17:00'),(12,'ticketShipping','00:01:00'),(13,'availableNoRaids','00:06:00'),(14,'lastBuy','00:30:00'); /*!40000 ALTER TABLE `cache` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; @@ -458,9 +468,9 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2021-05-25 11:53:10 +-- Dump completed on 2021-08-31 14:42:31 USE `hedera`; --- MariaDB dump 10.19 Distrib 10.5.9-MariaDB, for debian-linux-gnu (x86_64) +-- MariaDB dump 10.19 Distrib 10.6.4-MariaDB, for Linux (x86_64) -- -- Host: db.verdnatura.es Database: hedera -- ------------------------------------------------------ @@ -524,9 +534,9 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2021-05-25 11:53:10 +-- Dump completed on 2021-08-31 14:42:31 USE `postgresql`; --- MariaDB dump 10.19 Distrib 10.5.9-MariaDB, for debian-linux-gnu (x86_64) +-- MariaDB dump 10.19 Distrib 10.6.4-MariaDB, for Linux (x86_64) -- -- Host: db.verdnatura.es Database: postgresql -- ------------------------------------------------------ @@ -598,7 +608,7 @@ UNLOCK TABLES; LOCK TABLES `workcenter` WRITE; /*!40000 ALTER TABLE `workcenter` DISABLE KEYS */; -INSERT INTO `workcenter` VALUES (1,'Silla',20,1177,1,'Av espioca 100',552703),(2,'Mercaflor',19,NULL,NULL,NULL,NULL),(3,'Marjales',26,20008,NULL,NULL,NULL),(4,'VNH',NULL,NULL,3,NULL,NULL),(5,'Madrid',28,2861,5,'Av constitución 3',554145),(6,'Vilassar',88,88035,2,'Cami del Crist, 33',556412),(7,'Tenerife',NULL,NULL,10,NULL,NULL),(8,NULL,NULL,NULL,NULL,NULL,NULL),(9,'Algemesi',20,NULL,60,'Fenollars, 20',523549),(10,NULL,NULL,NULL,NULL,NULL,NULL); +INSERT INTO `workcenter` VALUES (1,'Silla',20,NULL,1,'Av espioca 100',552703),(2,'Mercaflor',19,NULL,NULL,NULL,NULL),(3,'Marjales',26,20008,NULL,NULL,NULL),(4,'VNH',NULL,NULL,3,NULL,NULL),(5,'Madrid',28,2865,5,'Av constitución 3',554145),(6,'Vilassar',88,88036,2,'Cami del Crist, 33',556412),(7,'Tenerife',NULL,NULL,10,NULL,NULL),(8,NULL,NULL,NULL,NULL,NULL,NULL),(9,'Algemesi',20,1266,60,'Fenollars, 2',523549),(10,NULL,NULL,NULL,NULL,NULL,NULL); /*!40000 ALTER TABLE `workcenter` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; @@ -610,9 +620,9 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2021-05-25 11:53:10 +-- Dump completed on 2021-08-31 14:42:32 USE `sage`; --- MariaDB dump 10.19 Distrib 10.5.9-MariaDB, for debian-linux-gnu (x86_64) +-- MariaDB dump 10.19 Distrib 10.6.4-MariaDB, for Linux (x86_64) -- -- Host: db.verdnatura.es Database: sage -- ------------------------------------------------------ @@ -666,4 +676,4 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2021-05-25 11:53:11 +-- Dump completed on 2021-08-31 14:42:32 diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 0f239bf652..2b65efbc10 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -6,6 +6,11 @@ ALTER TABLE `vn`.`address` AUTO_INCREMENT = 1; ALTER TABLE `vn`.`zoneGeo` AUTO_INCREMENT = 1; ALTER TABLE `vn`.`ticket` AUTO_INCREMENT = 1; +INSERT INTO `salix`.`AccessToken` (`id`, `ttl`, `created`, `userId`) + VALUES + ('TOTALLY_SECURE_TOKEN', '1209600', CURDATE(), 66); + + INSERT INTO `vn`.`ticketConfig` (`id`, `scopeDays`) VALUES ('1', '6'); @@ -53,18 +58,18 @@ INSERT INTO `hedera`.`tpvConfig`(`id`, `currency`, `terminal`, `transactionType` INSERT INTO `account`.`user`(`id`,`name`,`nickname`, `password`,`role`,`active`,`email`,`lang`, `image`) VALUES - (101, 'BruceWayne', 'Bruce Wayne', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'BruceWayne@mydomain.com', 'es', 'e7723f0b24ff05b32ed09d95196f2f29'), - (102, 'PetterParker', 'Petter Parker', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'PetterParker@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), - (103, 'ClarkKent', 'Clark Kent', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'ClarkKent@mydomain.com', 'fr', 'e7723f0b24ff05b32ed09d95196f2f29'), - (104, 'TonyStark', 'Tony Stark', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'TonyStark@mydomain.com', 'es', 'e7723f0b24ff05b32ed09d95196f2f29'), - (105, 'MaxEisenhardt', 'Max Eisenhardt', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'MaxEisenhardt@mydomain.com', 'pt', 'e7723f0b24ff05b32ed09d95196f2f29'), - (106, 'DavidCharlesHaller', 'David Charles Haller', 'ac754a330530832ba1bf7687f577da91', 1, 1, 'DavidCharlesHaller@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), - (107, 'HankPym', 'Hank Pym', 'ac754a330530832ba1bf7687f577da91', 1, 1, 'HankPym@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), - (108, 'CharlesXavier', 'Charles Xavier', 'ac754a330530832ba1bf7687f577da91', 1, 1, 'CharlesXavier@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), - (109, 'BruceBanner', 'Bruce Banner', 'ac754a330530832ba1bf7687f577da91', 1, 1, 'BruceBanner@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), - (110, 'JessicaJones', 'Jessica Jones', 'ac754a330530832ba1bf7687f577da91', 1, 1, 'JessicaJones@mydomain.com', 'en', NULL), - (111, 'Missing', 'Missing', 'ac754a330530832ba1bf7687f577da91', 2, 0, NULL, 'en', NULL), - (112, 'Trash', 'Trash', 'ac754a330530832ba1bf7687f577da91', 2, 0, NULL, 'en', NULL); + (1101, 'BruceWayne', 'Bruce Wayne', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'BruceWayne@mydomain.com', 'es', 'e7723f0b24ff05b32ed09d95196f2f29'), + (1102, 'PetterParker', 'Petter Parker', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'PetterParker@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), + (1103, 'ClarkKent', 'Clark Kent', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'ClarkKent@mydomain.com', 'fr', 'e7723f0b24ff05b32ed09d95196f2f29'), + (1104, 'TonyStark', 'Tony Stark', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'TonyStark@mydomain.com', 'es', 'e7723f0b24ff05b32ed09d95196f2f29'), + (1105, 'MaxEisenhardt', 'Max Eisenhardt', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'MaxEisenhardt@mydomain.com', 'pt', 'e7723f0b24ff05b32ed09d95196f2f29'), + (1106, 'DavidCharlesHaller', 'David Charles Haller', 'ac754a330530832ba1bf7687f577da91', 1, 1, 'DavidCharlesHaller@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), + (1107, 'HankPym', 'Hank Pym', 'ac754a330530832ba1bf7687f577da91', 1, 1, 'HankPym@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), + (1108, 'CharlesXavier', 'Charles Xavier', 'ac754a330530832ba1bf7687f577da91', 1, 1, 'CharlesXavier@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), + (1109, 'BruceBanner', 'Bruce Banner', 'ac754a330530832ba1bf7687f577da91', 1, 1, 'BruceBanner@mydomain.com', 'en', 'e7723f0b24ff05b32ed09d95196f2f29'), + (1110, 'JessicaJones', 'Jessica Jones', 'ac754a330530832ba1bf7687f577da91', 1, 1, 'JessicaJones@mydomain.com', 'en', NULL), + (1111, 'Missing', 'Missing', 'ac754a330530832ba1bf7687f577da91', 2, 0, NULL, 'en', NULL), + (1112, 'Trash', 'Trash', 'ac754a330530832ba1bf7687f577da91', 2, 0, NULL, 'en', NULL); INSERT INTO `account`.`mailAlias`(`id`, `alias`, `description`, `isPublic`) VALUES @@ -86,11 +91,11 @@ INSERT INTO `account`.`mailForward`(`account`, `forwardTo`) INSERT INTO `vn`.`worker`(`id`, `code`, `firstName`, `lastName`, `userFk`,`bossFk`, `phone`) VALUES - (106, 'LGN', 'David Charles', 'Haller', 106, 19, 432978106), - (107, 'ANT', 'Hank' , 'Pym' , 107, 19, 432978107), - (108, 'DCX', 'Charles' , 'Xavier', 108, 19, 432978108), - (109, 'HLK', 'Bruce' , 'Banner', 109, 19, 432978109), - (110, 'JJJ', 'Jessica' , 'Jones' , 110, 19, 432978110); + (1106, 'LGN', 'David Charles', 'Haller', 1106, 19, 432978106), + (1107, 'ANT', 'Hank' , 'Pym' , 1107, 19, 432978107), + (1108, 'DCX', 'Charles' , 'Xavier', 1108, 19, 432978108), + (1109, 'HLK', 'Bruce' , 'Banner', 1109, 19, 432978109), + (1110, 'JJJ', 'Jessica' , 'Jones' , 1110, 19, 432978110); INSERT INTO `vn`.`currency`(`id`, `code`, `name`, `ratio`) VALUES @@ -125,13 +130,14 @@ INSERT INTO `vn`.`warehouseAlias`(`id`, `name`) (1, 'Main Warehouse'), (2, 'Silla'); -INSERT INTO `vn`.`warehouse`(`id`, `name`, `code`, `isComparative`, `isInventory`, `hasAvailable`, `isManaged`, `hasStowaway`, `hasDms`, `hasComission`, `aliasFk`, `countryFk`) +INSERT INTO `vn`.`warehouse`(`id`, `name`, `code`, `isComparative`, `isInventory`, `hasAvailable`, `isManaged`, `hasStowaway`, `hasDms`, `hasComission`, `aliasFk`, `countryFk`, `hasProduction`) VALUES - (1, 'Warehouse One', 'ALG', 1, 1, 1, 1, 1, 1, 1, 2, 1), - (2, 'Warehouse Two', NULL, 1, 1, 1, 1, 0, 0, 1, 2, 13), - (3, 'Warehouse Three', NULL, 1, 1, 1, 1, 0, 0, 0, 2, 1), - (4, 'Warehouse Four', NULL, 1, 1, 1, 1, 0, 0, 0, 2, 1), - (5, 'Warehouse Five', NULL, 1, 1, 1, 1, 0, 0, 0, 2, 1); + (1, 'Warehouse One', 'ALG', 1, 1, 1, 1, 1, 1, 1, 2, 1, 1), + (2, 'Warehouse Two', NULL, 1, 1, 1, 1, 0, 0, 1, 2, 13, 1), + (3, 'Warehouse Three', NULL, 1, 1, 1, 1, 0, 0, 0, 2, 1, 1), + (4, 'Warehouse Four', NULL, 1, 1, 1, 1, 0, 0, 0, 2, 1, 1), + (5, 'Warehouse Five', NULL, 1, 1, 1, 1, 0, 0, 0, 2, 1, 1), + (13, 'Inventory', NULL, 1, 1, 1, 0, 0, 0, 0, 2, 1, 0); INSERT INTO `vn`.`sector`(`id`, `description`, `warehouseFk`, `isPreviousPreparedByPacking`, `code`, `pickingPlacement`, `path`) VALUES @@ -145,8 +151,8 @@ INSERT INTO `vn`.`parking` (`id`, `column`, `row`, `sectorFk`, `code`, `pickingO INSERT INTO `vn`.`shelving` (`code`, `parkingFk`, `isPrinted`, `priority`, `parked`, `userFk`) VALUES - ('GVC', '1', '0', '1', '0', '106'), - ('HEJ', '2', '0', '1', '0', '106'); + ('GVC', '1', '0', '1', '0', '1106'), + ('HEJ', '2', '0', '1', '0', '1106'); INSERT INTO `vn`.`accountingType`(`id`, `description`, `receiptDescription`,`code`) VALUES @@ -207,30 +213,39 @@ UPDATE `vn`.`agencyMode` SET `deliveryMethodFk` = 1 WHERE `id` = 8; UPDATE `vn`.`agencyMode` SET `deliveryMethodFk` = 4 WHERE `id` = 23; UPDATE `vn`.`agencyMode` SET `deliveryMethodFk` = 1 WHERE `id` = 10; -UPDATE `vn`.`agencyMode` SET `web` = 1; +UPDATE `vn`.`agencyMode` SET `web` = 1, `reportMail` = 'no-reply@gothamcity.com'; UPDATE `vn`.`agencyMode` SET `code` = 'refund' WHERE `id` = 23; INSERT INTO `vn`.`payMethod`(`id`,`code`, `name`, `graceDays`, `outstandingDebt`, `ibanRequired`) VALUES - (1, NULL, 'PayMethod one', 0, 001, 0), - (2, NULL, 'PayMethod two', 10, 001, 0), - (3, 'compensation', 'PayMethod three', 0, 001, 0), - (4, NULL, 'PayMethod with IBAN', 0, 001, 1), - (5, NULL, 'PayMethod five', 10, 001, 0); + (1, NULL, 'PayMethod one', 0, 001, 0), + (2, NULL, 'PayMethod two', 10, 001, 0), + (3, 'compensation', 'PayMethod three', 0, 001, 0), + (4, NULL, 'PayMethod with IBAN', 0, 001, 1), + (5, NULL, 'PayMethod five', 10, 001, 0), + (8,'wireTransfer', 'WireTransfer', 5, 001, 1); INSERT INTO `vn`.`payDem`(`id`, `payDem`) VALUES (1, 10), (2, 20); -INSERT INTO `vn`.`province`(`id`, `name`, `countryFk`, `warehouseFk`) +INSERT INTO `vn`.`autonomy`(`id`, `name`, `countryFk`) VALUES - (1, 'Province one', 1, NULL), - (2, 'Province two', 1, NULL), - (3, 'Province three', 1, NULL), - (4, 'Province four', 2, NULL), - (5, 'Province five', 13, NULL); + (1, 'Autonomy one', 1), + (2, 'Autonomy two', 1), + (3, 'Autonomy three', 2), + (4, 'Autonomy four', 13); + + +INSERT INTO `vn`.`province`(`id`, `name`, `countryFk`, `autonomyFk`, `warehouseFk`) + VALUES + (1, 'Province one', 1, 1, NULL), + (2, 'Province two', 1, 1, NULL), + (3, 'Province three', 1, 2, NULL), + (4, 'Province four', 2, 3, NULL), + (5, 'Province five', 13, 4, NULL); INSERT INTO `vn`.`town`(`id`, `name`, `provinceFk`) VALUES @@ -267,20 +282,20 @@ INSERT INTO `vn`.`contactChannel`(`id`, `name`) (4, 'GCN Channel'), (5, 'The Newspaper'); -INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city`,`postcode`,`phone`,`mobile`,`fax`,`isRelevant`,`email`,`iban`,`dueDay`,`accountingAccount`,`isEqualizated`,`provinceFk`,`hasToInvoice`,`credit`,`countryFk`,`isActive`,`gestdocFk`,`quality`,`payMethodFk`,`created`,`isToBeMailed`,`contactChannelFk`,`hasSepaVnl`,`hasCoreVnl`,`hasCoreVnh`,`riskCalculated`,`clientTypeFk`,`mailAddress`,`cplusTerIdNifFk`,`hasToInvoiceByAddress`,`isTaxDataChecked`,`isFreezed`,`creditInsurance`,`isCreatedAsServed`,`hasInvoiceSimplified`,`salesPersonFk`,`isVies`,`eypbc`) +INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city`,`postcode`,`phone`,`mobile`,`isRelevant`,`email`,`iban`,`dueDay`,`accountingAccount`,`isEqualizated`,`provinceFk`,`hasToInvoice`,`credit`,`countryFk`,`isActive`,`gestdocFk`,`quality`,`payMethodFk`,`created`,`isToBeMailed`,`contactChannelFk`,`hasSepaVnl`,`hasCoreVnl`,`hasCoreVnh`,`riskCalculated`,`clientTypeFk`,`mailAddress`,`hasToInvoiceByAddress`,`isTaxDataChecked`,`isFreezed`,`creditInsurance`,`isCreatedAsServed`,`hasInvoiceSimplified`,`salesPersonFk`,`isVies`,`eypbc`, `businessTypeFk`) VALUES - (101, 'Bruce Wayne', '84612325V', 'Batman', 'Alfred', '1007 Mountain Drive, Gotham', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'BruceWayne@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), - (102, 'Petter Parker', '87945234L', 'Spider man', 'Aunt May', '20 Ingram Street, Queens, USA', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'PetterParker@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), - (103, 'Clark Kent', '06815934E', 'Super man', 'lois lane', '344 Clinton Street, Apartament 3-D', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'ClarkKent@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 0, 19, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), - (104, 'Tony Stark', '06089160W', 'Iron man', 'Pepper Potts', '10880 Malibu Point, 90265', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'TonyStark@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), - (105, 'Max Eisenhardt', '251628698', 'Magneto', 'Rogue', 'Unknown Whereabouts', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'MaxEisenhardt@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 8, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 1, NULL, 0, 0, 18, 0, 1), - (106, 'DavidCharlesHaller', '53136686Q', 'Legion', 'Charles Xavier', 'City of New York, New York, USA', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'DavidCharlesHaller@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 0, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 19, 0, 1), - (107, 'Hank Pym', '09854837G', 'Ant man', 'Hawk', 'Anthill, San Francisco, California', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'HankPym@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 0, 0, NULL, 0, 0, 19, 0, 1), - (108, 'Charles Xavier', '22641921P', 'Professor X', 'Beast', '3800 Victory Pkwy, Cincinnati, OH 45207, USA', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'CharlesXavier@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 1, NULL, 0, 0, 19, 0, 1), - (109, 'Bruce Banner', '16104829E', 'Hulk', 'Black widow', 'Somewhere in New York', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'BruceBanner@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 0, 0, NULL, 0, 0, 9, 0, 1), - (110, 'Jessica Jones', '58282869H', 'Jessica Jones', 'Luke Cage', 'NYCC 2015 Poster', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'JessicaJones@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 0, 0, NULL, 0, 0, NULL, 0, 1), - (111, 'Missing', NULL, 'Missing man', 'Anton', 'The space, Universe far away', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, NULL, 1, 0, 1, 0, NULL, 1, 0, NULL, 0, 1), - (112, 'Trash', NULL, 'Garbage man', 'Unknown name', 'New York city, Underground', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, NULL, 1, 0, 1, 0, NULL, 1, 0, NULL, 0, 1); + (1101, 'Bruce Wayne', '84612325V', 'Batman', 'Alfred', '1007 Mountain Drive, Gotham', 'Silla', 46460, 1111111111, 222222222, 1, 'BruceWayne@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist'), + (1102, 'Petter Parker', '87945234L', 'Spider man', 'Aunt May', '20 Ingram Street, Queens, USA', 'Silla', 46460, 1111111111, 222222222, 1, 'PetterParker@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist'), + (1103, 'Clark Kent', '06815934E', 'Super man', 'lois lane', '344 Clinton Street, Apartament 3-D', 'Silla', 46460, 1111111111, 222222222, 1, 'ClarkKent@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 0, 19, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist'), + (1104, 'Tony Stark', '06089160W', 'Iron man', 'Pepper Potts', '10880 Malibu Point, 90265', 'Silla', 46460, 1111111111, 222222222, 1, 'TonyStark@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist'), + (1105, 'Max Eisenhardt', '251628698', 'Magneto', 'Rogue', 'Unknown Whereabouts', 'Silla', 46460, 1111111111, 222222222, 1, 'MaxEisenhardt@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 8, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 1, 1, NULL, 0, 0, 18, 0, 1, 'florist'), + (1106, 'DavidCharlesHaller', '53136686Q', 'Legion', 'Charles Xavier', 'City of New York, New York, USA', 'Silla', 46460, 1111111111, 222222222, 1, 'DavidCharlesHaller@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 0, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 1, 0, NULL, 0, 0, 19, 0, 1, 'florist'), + (1107, 'Hank Pym', '09854837G', 'Ant man', 'Hawk', 'Anthill, San Francisco, California', 'Silla', 46460, 1111111111, 222222222, 1, 'HankPym@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, 0, NULL, 0, 0, 19, 0, 1, 'florist'), + (1108, 'Charles Xavier', '22641921P', 'Professor X', 'Beast', '3800 Victory Pkwy, Cincinnati, OH 45207, USA', 'Silla', 46460, 1111111111, 222222222, 1, 'CharlesXavier@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 1, 1, NULL, 0, 0, 19, 0, 1, 'florist'), + (1109, 'Bruce Banner', '16104829E', 'Hulk', 'Black widow', 'Somewhere in New York', 'Silla', 46460, 1111111111, 222222222, 1, 'BruceBanner@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, 0, NULL, 0, 0, 9, 0, 1, 'florist'), + (1110, 'Jessica Jones', '58282869H', 'Jessica Jones', 'Luke Cage', 'NYCC 2015 Poster', 'Silla', 46460, 1111111111, 222222222, 1, 'JessicaJones@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, 0, NULL, 0, 0, NULL, 0, 1, 'florist'), + (1111, 'Missing', NULL, 'Missing man', 'Anton', 'The space, Universe far away', 'Silla', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, 1, 0, 1, 0, NULL, 1, 0, NULL, 0, 1, NULL), + (1112, 'Trash', NULL, 'Garbage man', 'Unknown name', 'New York city, Underground', 'Silla', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, 1, 0, 1, 0, NULL, 1, 0, NULL, 0, 1, NULL); INSERT INTO `vn`.`client`(`id`, `name`, `fi`, `socialName`, `contact`, `street`, `city`, `postcode`, `isRelevant`, `email`, `iban`,`dueDay`,`accountingAccount`, `isEqualizated`, `provinceFk`, `hasToInvoice`, `credit`, `countryFk`, `isActive`, `gestdocFk`, `quality`, `payMethodFk`,`created`, `isTaxDataChecked`) SELECT id, name, CONCAT(RPAD(CONCAT(id,9),8,id),'A'), CONCAT(name, 'Social'), CONCAT(name, 'Contact'), CONCAT(name, 'Street'), 'SILLA', 46460, 1, CONCAT(name,'@mydomain.com'), NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5, CURDATE(), 1 @@ -289,10 +304,10 @@ INSERT INTO `vn`.`client`(`id`, `name`, `fi`, `socialName`, `contact`, `street`, INSERT INTO `vn`.`clientManaCache`(`clientFk`, `mana`, `dated`) VALUES - (101, 50, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), - (102, 100, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), - (103, 0, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), - (104, -30, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)); + (1101, 50, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (1102, 100, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (1103, 0, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (1104, -30, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)); INSERT INTO `vn`.`clientConfig`(`riskTolerance`) VALUES @@ -300,64 +315,64 @@ INSERT INTO `vn`.`clientConfig`(`riskTolerance`) INSERT INTO `vn`.`address`(`id`, `nickname`, `street`, `city`, `postalCode`, `provinceFk`, `phone`, `mobile`, `isActive`, `clientFk`, `agencyModeFk`, `longitude`, `latitude`, `isEqualizated`, `isDefaultAddress`) VALUES - (1, 'Bruce Wayne', '1007 Mountain Drive, Gotham', 'Silla', 46460, 1, 1111111111, 222222222, 1, 101, 2, NULL, NULL, 0, 1), - (2, 'Petter Parker', '20 Ingram Street', 'Silla', 46460, 1, 1111111111, 222222222, 1, 102, 2, NULL, NULL, 0, 1), - (3, 'Clark Kent', '344 Clinton Street', 'Silla', 46460, 1, 1111111111, 222222222, 1, 103, 2, NULL, NULL, 0, 1), - (4, 'Tony Stark', '10880 Malibu Point', 'Silla', 46460, 1, 1111111111, 222222222, 1, 104, 2, NULL, NULL, 0, 1), - (5, 'Max Eisenhardt', 'Unknown Whereabouts', 'Silla', 46460, 1, 1111111111, 222222222, 1, 105, 2, NULL, NULL, 0, 1), - (6, 'DavidCharlesHaller', 'Evil hideout', 'Silla', 46460, 1, 1111111111, 222222222, 1, 106, 2, NULL, NULL, 0, 1), - (7, 'Hank Pym', 'Anthill', 'Silla', 46460, 1, 1111111111, 222222222, 1, 107, 2, NULL, NULL, 0, 1), - (8, 'Charles Xavier', '3800 Victory Pkwy, Cincinnati, OH 45207, USA', 'Silla', 46460, 1, 1111111111, 222222222, 1, 108, 2, NULL, NULL, 0, 1), - (9, 'Bruce Banner', 'Somewhere in New York', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 1), - (10, 'Jessica Jones', 'NYCC 2015 Poster', 'Silla', 46460, 1, 1111111111, 222222222, 1, 110, 2, NULL, NULL, 0, 1), - (11, 'Missing', 'The space', 'Silla', 46460, 1, 1111111111, 222222222, 1, 111, 10, NULL, NULL, 0, 1), - (12, 'Trash', 'New York city', 'Silla', 46460, 1, 1111111111, 222222222, 1, 112, 10, NULL, NULL, 0, 1), - (101, 'Somewhere in Thailand', 'address 01', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), - (102, 'Somewhere in Poland', 'address 02', 'Silla', 46460, 1, 3333333333, 444444444, 1, 109, 2, NULL, NULL, 0, 0), - (103, 'Somewhere in Japan', 'address 03', 'Silla', 46460, 1, 3333333333, 444444444, 1, 109, 2, NULL, NULL, 0, 0), - (104, 'Somewhere in Spain', 'address 04', 'Silla', 46460, 1, 3333333333, 444444444, 1, 109, 2, NULL, NULL, 0, 0), - (105, 'Somewhere in Potugal', 'address 05', 'Silla', 46460, 1, 5555555555, 666666666, 1, 109, 2, NULL, NULL, 0, 0), - (106, 'Somewhere in UK', 'address 06', 'Silla', 46460, 1, 5555555555, 666666666, 1, 109, 2, NULL, NULL, 0, 0), - (107, 'Somewhere in Valencia', 'address 07', 'Silla', 46460, 1, 5555555555, 666666666, 1, 109, 2, NULL, NULL, 0, 0), - (108, 'Somewhere in Silla', 'address 08', 'Silla', 46460, 1, 5555555555, 666666666, 1, 109, 2, NULL, NULL, 0, 0), - (109, 'Somewhere in London', 'address 09', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), - (110, 'Somewhere in Algemesi', 'address 10', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), - (111, 'Somewhere in Carlet', 'address 11', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), - (112, 'Somewhere in Campanar', 'address 12', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), - (113, 'Somewhere in Malilla', 'address 13', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), - (114, 'Somewhere in France', 'address 14', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), - (115, 'Somewhere in Birmingham', 'address 15', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), - (116, 'Somewhere in Scotland', 'address 16', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), - (117, 'Somewhere in nowhere', 'address 17', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), - (118, 'Somewhere over the rainbow', 'address 18', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), - (119, 'Somewhere in Alberic', 'address 19', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), - (120, 'Somewhere in Montortal', 'address 20', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), - (121, 'the bat cave', 'address 21', 'Silla', 46460, 1, 1111111111, 222222222, 1, 101, 2, NULL, NULL, 0, 0), - (122, 'NY roofs', 'address 22', 'Silla', 46460, 1, 1111111111, 222222222, 1, 102, 2, NULL, NULL, 0, 0), - (123, 'The phone box', 'address 23', 'Silla', 46460, 1, 1111111111, 222222222, 1, 103, 2, NULL, NULL, 0, 0), - (124, 'Stark tower Silla', 'address 24', 'Silla', 46460, 1, 1111111111, 222222222, 1, 104, 2, NULL, NULL, 0, 0), - (125, 'The plastic cell', 'address 25', 'Silla', 46460, 1, 1111111111, 222222222, 1, 105, 2, NULL, NULL, 0, 0), - (126, 'Many places', 'address 26', 'Silla', 46460, 1, 1111111111, 222222222, 1, 106, 2, NULL, NULL, 0, 0), - (127, 'Your pocket', 'address 27', 'Silla', 46460, 1, 1111111111, 222222222, 1, 107, 2, NULL, NULL, 0, 0), - (128, 'Cerebro', 'address 28', 'Silla', 46460, 1, 1111111111, 222222222, 1, 108, 2, NULL, NULL, 0, 0), - (129, 'Luke Cages Bar', 'address 29', 'Silla', 46460, 1, 1111111111, 222222222, 1, 110, 2, NULL, NULL, 0, 0), - (130, 'Non valid address', 'address 30', 'Silla', 46460, 1, 1111111111, 222222222, 0, 101, 2, NULL, NULL, 0, 0); + (1, 'Bruce Wayne', '1007 Mountain Drive, Gotham', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1101, 2, NULL, NULL, 0, 1), + (2, 'Petter Parker', '20 Ingram Street', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1102, 2, NULL, NULL, 0, 1), + (3, 'Clark Kent', '344 Clinton Street', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1103, 2, NULL, NULL, 0, 1), + (4, 'Tony Stark', '10880 Malibu Point', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1104, 2, NULL, NULL, 0, 1), + (5, 'Max Eisenhardt', 'Unknown Whereabouts', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1105, 2, NULL, NULL, 0, 1), + (6, 'DavidCharlesHaller', 'Evil hideout', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1106, 2, NULL, NULL, 0, 1), + (7, 'Hank Pym', 'Anthill', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1107, 2, NULL, NULL, 0, 1), + (8, 'Charles Xavier', '3800 Victory Pkwy, Cincinnati, OH 45207, USA', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1108, 2, NULL, NULL, 0, 1), + (9, 'Bruce Banner', 'Somewhere in New York', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1109, 2, NULL, NULL, 0, 1), + (10, 'Jessica Jones', 'NYCC 2015 Poster', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1110, 2, NULL, NULL, 0, 1), + (11, 'Missing', 'The space', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1111, 10, NULL, NULL, 0, 1), + (12, 'Trash', 'New York city', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1112, 10, NULL, NULL, 0, 1), + (101, 'Somewhere in Thailand', 'address 01', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1109, 2, NULL, NULL, 0, 0), + (102, 'Somewhere in Poland', 'address 02', 'Silla', 46460, 1, 3333333333, 444444444, 1, 1109, 2, NULL, NULL, 0, 0), + (103, 'Somewhere in Japan', 'address 03', 'Silla', 46460, 1, 3333333333, 444444444, 1, 1109, 2, NULL, NULL, 0, 0), + (104, 'Somewhere in Spain', 'address 04', 'Silla', 46460, 1, 3333333333, 444444444, 1, 1109, 2, NULL, NULL, 0, 0), + (105, 'Somewhere in Potugal', 'address 05', 'Silla', 46460, 1, 5555555555, 666666666, 1, 1109, 2, NULL, NULL, 0, 0), + (106, 'Somewhere in UK', 'address 06', 'Silla', 46460, 1, 5555555555, 666666666, 1, 1109, 2, NULL, NULL, 0, 0), + (107, 'Somewhere in Valencia', 'address 07', 'Silla', 46460, 1, 5555555555, 666666666, 1, 1109, 2, NULL, NULL, 0, 0), + (108, 'Somewhere in Silla', 'address 08', 'Silla', 46460, 1, 5555555555, 666666666, 1, 1109, 2, NULL, NULL, 0, 0), + (109, 'Somewhere in London', 'address 09', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1109, 2, NULL, NULL, 0, 0), + (110, 'Somewhere in Algemesi', 'address 10', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1109, 2, NULL, NULL, 0, 0), + (111, 'Somewhere in Carlet', 'address 11', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1109, 2, NULL, NULL, 0, 0), + (112, 'Somewhere in Campanar', 'address 12', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1109, 2, NULL, NULL, 0, 0), + (113, 'Somewhere in Malilla', 'address 13', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1109, 2, NULL, NULL, 0, 0), + (114, 'Somewhere in France', 'address 14', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1109, 2, NULL, NULL, 0, 0), + (115, 'Somewhere in Birmingham', 'address 15', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1109, 2, NULL, NULL, 0, 0), + (116, 'Somewhere in Scotland', 'address 16', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1109, 2, NULL, NULL, 0, 0), + (117, 'Somewhere in nowhere', 'address 17', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1109, 2, NULL, NULL, 0, 0), + (118, 'Somewhere over the rainbow', 'address 18', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1109, 2, NULL, NULL, 0, 0), + (119, 'Somewhere in Alberic', 'address 19', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1109, 2, NULL, NULL, 0, 0), + (120, 'Somewhere in Montortal', 'address 20', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1109, 2, NULL, NULL, 0, 0), + (121, 'the bat cave', 'address 21', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1101, 2, NULL, NULL, 0, 0), + (122, 'NY roofs', 'address 22', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1102, 2, NULL, NULL, 0, 0), + (123, 'The phone box', 'address 23', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1103, 2, NULL, NULL, 0, 0), + (124, 'Stark tower Silla', 'address 24', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1104, 2, NULL, NULL, 0, 0), + (125, 'The plastic cell', 'address 25', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1105, 2, NULL, NULL, 0, 0), + (126, 'Many places', 'address 26', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1106, 2, NULL, NULL, 0, 0), + (127, 'Your pocket', 'address 27', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1107, 2, NULL, NULL, 0, 0), + (128, 'Cerebro', 'address 28', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1108, 2, NULL, NULL, 0, 0), + (129, 'Luke Cages Bar', 'address 29', 'Silla', 46460, 1, 1111111111, 222222222, 1, 1110, 2, NULL, NULL, 0, 0), + (130, 'Non valid address', 'address 30', 'Silla', 46460, 1, 1111111111, 222222222, 0, 1101, 2, NULL, NULL, 0, 0); INSERT INTO `vn`.`address`( `nickname`, `street`, `city`, `postalCode`, `provinceFk`, `isActive`, `clientFk`, `agencyModeFk`, `isDefaultAddress`) SELECT name, CONCAT(name, 'Street'), 'SILLA', 46460, 1, 1, id, 2, 1 FROM `account`.`role` `r` WHERE `r`.`hasLogin` = 1; -UPDATE `vn`.`client` SET defaultAddressFk = 1 WHERE id = 101; -UPDATE `vn`.`client` SET defaultAddressFk = 2 WHERE id = 102; -UPDATE `vn`.`client` SET defaultAddressFk = 3 WHERE id = 103; -UPDATE `vn`.`client` SET defaultAddressFk = 4 WHERE id = 104; -UPDATE `vn`.`client` SET defaultAddressFk = 5 WHERE id = 105; -UPDATE `vn`.`client` SET defaultAddressFk = 6 WHERE id = 106; -UPDATE `vn`.`client` SET defaultAddressFk = 7 WHERE id = 107; -UPDATE `vn`.`client` SET defaultAddressFk = 8 WHERE id = 108; -UPDATE `vn`.`client` SET defaultAddressFk = 9 WHERE id = 109; -UPDATE `vn`.`client` SET defaultAddressFk = 10 WHERE id = 110; +UPDATE `vn`.`client` SET defaultAddressFk = 1 WHERE id = 1101; +UPDATE `vn`.`client` SET defaultAddressFk = 2 WHERE id = 1102; +UPDATE `vn`.`client` SET defaultAddressFk = 3 WHERE id = 1103; +UPDATE `vn`.`client` SET defaultAddressFk = 4 WHERE id = 1104; +UPDATE `vn`.`client` SET defaultAddressFk = 5 WHERE id = 1105; +UPDATE `vn`.`client` SET defaultAddressFk = 6 WHERE id = 1106; +UPDATE `vn`.`client` SET defaultAddressFk = 7 WHERE id = 1107; +UPDATE `vn`.`client` SET defaultAddressFk = 8 WHERE id = 1108; +UPDATE `vn`.`client` SET defaultAddressFk = 9 WHERE id = 1109; +UPDATE `vn`.`client` SET defaultAddressFk = 10 WHERE id = 1110; UPDATE `vn`.`client` SET defaultAddressFk = 11 WHERE id = 200; UPDATE `vn`.`client` SET defaultAddressFk = 12 WHERE id = 400; @@ -374,20 +389,20 @@ DROP TEMPORARY TABLE tmp.address; INSERT INTO `vn`.`clientCredit`(`id`, `clientFk`, `workerFk`, `amount`, `created`) VALUES - (1 , 101, 5, 300, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), - (2 , 101, 5, 900, DATE_ADD(CURDATE(), INTERVAL -2 MONTH)), - (3 , 101, 5, 800, DATE_ADD(CURDATE(), INTERVAL -3 MONTH)), - (4 , 101, 5, 700, DATE_ADD(CURDATE(), INTERVAL -4 MONTH)), - (5 , 101, 5, 600, DATE_ADD(CURDATE(), INTERVAL -5 MONTH)), - (6 , 101, 5, 500, DATE_ADD(CURDATE(), INTERVAL -6 MONTH)), - (7 , 101, 5, 400, DATE_ADD(CURDATE(), INTERVAL -7 MONTH)), - (8 , 101, 9, 300, DATE_ADD(CURDATE(), INTERVAL -8 MONTH)), - (9 , 101, 9, 200, DATE_ADD(CURDATE(), INTERVAL -9 MONTH)), - (10, 101, 9, 100, DATE_ADD(CURDATE(), INTERVAL -10 MONTH)), - (11, 101, 9, 50 , DATE_ADD(CURDATE(), INTERVAL -11 MONTH)), - (12, 102, 9, 800, CURDATE()), - (14, 104, 9, 90 , CURDATE()), - (15, 105, 9, 90 , CURDATE()); + (1 , 1101, 5, 300, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (2 , 1101, 5, 900, DATE_ADD(CURDATE(), INTERVAL -2 MONTH)), + (3 , 1101, 5, 800, DATE_ADD(CURDATE(), INTERVAL -3 MONTH)), + (4 , 1101, 5, 700, DATE_ADD(CURDATE(), INTERVAL -4 MONTH)), + (5 , 1101, 5, 600, DATE_ADD(CURDATE(), INTERVAL -5 MONTH)), + (6 , 1101, 5, 500, DATE_ADD(CURDATE(), INTERVAL -6 MONTH)), + (7 , 1101, 5, 400, DATE_ADD(CURDATE(), INTERVAL -7 MONTH)), + (8 , 1101, 9, 300, DATE_ADD(CURDATE(), INTERVAL -8 MONTH)), + (9 , 1101, 9, 200, DATE_ADD(CURDATE(), INTERVAL -9 MONTH)), + (10, 1101, 9, 100, DATE_ADD(CURDATE(), INTERVAL -10 MONTH)), + (11, 1101, 9, 50 , DATE_ADD(CURDATE(), INTERVAL -11 MONTH)), + (12, 1102, 9, 800, CURDATE()), + (14, 1104, 9, 90 , CURDATE()), + (15, 1105, 9, 90 , CURDATE()); INSERT INTO `vn`.`clientCreditLimit`(`id`, `maxAmount`, `roleFk`) VALUES @@ -397,16 +412,16 @@ INSERT INTO `vn`.`clientCreditLimit`(`id`, `maxAmount`, `roleFk`) INSERT INTO `vn`.`clientObservation`(`id`, `clientFk`, `workerFk`, `text`, `created`) VALUES - (1, 101, 1, 'Madness, as you know, is like gravity, all it takes is a little push', CURDATE()), - (2, 102, 1, 'With great power, comes great responsibility', CURDATE()), - (3, 103, 3, 'this is a job for Super-Man!', CURDATE()), - (4, 104, 3, 'yes... I am Iron-Man', CURDATE()), - (5, 105, 5, 'They do understand. Our mutant powers make us superior', CURDATE()), - (6, 106, 5, 'My name is Legion, for we are many!', CURDATE()), - (7, 107, 9, 'I think our first move should be calling the Avengers..', CURDATE()), - (8, 108, 9, 'Just because someone stumbles and loses their path, does not mean they are lost forever.', CURDATE()), - (9, 109, 18, 'HULK SMASH! ...', CURDATE()), - (10, 110, 18, 'They say everyone is born a hero. But if you let it, life will push you over the line until you are the villain.', CURDATE()); + (1, 1101, 1, 'Madness, as you know, is like gravity, all it takes is a little push', CURDATE()), + (2, 1102, 1, 'With great power, comes great responsibility', CURDATE()), + (3, 1103, 3, 'this is a job for Super-Man!', CURDATE()), + (4, 1104, 3, 'yes... I am Iron-Man', CURDATE()), + (5, 1105, 5, 'They do understand. Our mutant powers make us superior', CURDATE()), + (6, 1106, 5, 'My name is Legion, for we are many!', CURDATE()), + (7, 1107, 9, 'I think our first move should be calling the Avengers..', CURDATE()), + (8, 1108, 9, 'Just because someone stumbles and loses their path, does not mean they are lost forever.', CURDATE()), + (9, 1109, 18, 'HULK SMASH! ...', CURDATE()), + (10, 1110, 18, 'They say everyone is born a hero. But if you let it, life will push you over the line until you are the villain.', CURDATE()); INSERT INTO `vn`.`observationType`(`id`,`description`, `code`) VALUES @@ -426,11 +441,11 @@ INSERT INTO `vn`.`addressObservation`(`id`,`addressFk`,`observationTypeFk`,`desc INSERT INTO `vn`.`creditClassification`(`id`, `client`, `dateStart`, `dateEnd`) VALUES - (1, 101, CURDATE(), CURDATE()), - (2, 102, CURDATE(), CURDATE()), - (3, 103, CURDATE(), CURDATE()), - (4, 104, CURDATE(), CURDATE()), - (5, 105, CURDATE(), CURDATE()); + (1, 1101, CURDATE(), CURDATE()), + (2, 1102, CURDATE(), CURDATE()), + (3, 1103, CURDATE(), CURDATE()), + (4, 1104, CURDATE(), CURDATE()), + (5, 1105, CURDATE(), CURDATE()); INSERT INTO `vn`.`creditInsurance`(`id`, `creditClassification`, `credit`, `creationDate`, `grade`) VALUES @@ -474,11 +489,11 @@ INSERT INTO `vn`.`invoiceOutSerial` (`code`, `description`, `isTaxed`, `taxAreaF INSERT INTO `vn`.`invoiceOut`(`id`, `serial`, `amount`, `issued`,`clientFk`, `created`, `companyFk`, `dued`, `booked`, `bankFk`, `hasPdf`) VALUES - (1, 'T', 1014.24, CURDATE(), 101, CURDATE(), 442, CURDATE(), CURDATE(), 1, 1), - (2, 'T', 121.36, CURDATE(), 102, CURDATE(), 442, CURDATE(), CURDATE(), 1, 1), - (3, 'T', 8.88, CURDATE(), 103, CURDATE(), 442, CURDATE(), CURDATE(), 1, 1), - (4, 'T', 8.88, CURDATE(), 103, CURDATE(), 442, CURDATE(), CURDATE(), 1, 1), - (5, 'A', 8.88, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 103, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 442, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 1, 1); + (1, 'T', 1014.24, CURDATE(), 1101, CURDATE(), 442, CURDATE(), CURDATE(), 1, 1), + (2, 'T', 121.36, CURDATE(), 1102, CURDATE(), 442, CURDATE(), CURDATE(), 1, 1), + (3, 'T', 8.88, CURDATE(), 1103, CURDATE(), 442, CURDATE(), CURDATE(), 1, 1), + (4, 'T', 8.88, CURDATE(), 1103, CURDATE(), 442, CURDATE(), CURDATE(), 1, 1), + (5, 'A', 8.88, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 1103, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 442, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 1, 1); UPDATE `vn`.`invoiceOut` SET ref = 'T1111111' WHERE id = 1; UPDATE `vn`.`invoiceOut` SET ref = 'T2222222' WHERE id = 2; @@ -579,30 +594,30 @@ INSERT INTO `vn`.`route`(`id`, `time`, `workerFk`, `created`, `vehicleFk`, `agen INSERT INTO `vn`.`ticket`(`id`, `priority`, `agencyModeFk`,`warehouseFk`,`routeFk`, `shipped`, `landed`, `clientFk`,`nickname`, `addressFk`, `refFk`, `isDeleted`, `zoneFk`, `zonePrice`, `zoneBonus`, `created`) VALUES - (1 , 3, 1, 1, 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 101, 'Bat cave', 121, 'T1111111', 0, 1, 5, 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), - (2 , 1, 1, 1, 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 104, 'Stark tower', 124, 'T1111111', 0, 1, 5, 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), - (3 , 1, 7, 1, 6, DATE_ADD(CURDATE(), INTERVAL -2 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -2 MONTH), INTERVAL +1 DAY), 104, 'Stark tower', 124, 'T2222222', 0, 3, 5, 1, DATE_ADD(CURDATE(), INTERVAL -2 MONTH)), - (4 , 3, 2, 1, 2, DATE_ADD(CURDATE(), INTERVAL -3 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -3 MONTH), INTERVAL +1 DAY), 104, 'Stark tower', 124, 'T3333333', 0, 9, 5, 1, DATE_ADD(CURDATE(), INTERVAL -3 MONTH)), - (5 , 3, 3, 3, 3, DATE_ADD(CURDATE(), INTERVAL -4 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -4 MONTH), INTERVAL +1 DAY), 104, 'Stark tower', 124, 'T4444444', 0, 10, 5, 1, DATE_ADD(CURDATE(), INTERVAL -4 MONTH)), - (6 , 1, 3, 3, 3, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 101, 'Mountain Drive Gotham', 1, 'A1111111', 0, 10, 5, 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), - (7 , NULL, 7, 1, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 101, 'Mountain Drive Gotham', 1, NULL, 0, 3, 5, 1, CURDATE()), - (8 , NULL, 7, 1, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 101, 'Bat cave', 121, NULL, 0, 3, 5, 1, CURDATE()), - (9 , NULL, 7, 1, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 104, 'Stark tower', 124, NULL, 0, 3, 5, 1, CURDATE()), - (10, 1, 1, 5, 1, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 102, 'Ingram Street', 2, NULL, 0, 1, 5, 1, CURDATE()), - (11, 1, 7, 1, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 102, 'NY roofs', 122, NULL, 0, 3, 5, 1, CURDATE()), - (12, 1, 1, 1, 1, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 103, 'Phone Box', 123, NULL, 0, 1, 5, 1, CURDATE()), - (13, 1, 7, 1, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 103, 'Phone Box', 123, NULL, 0, 3, 5, 1, CURDATE()), - (14, 1, 2, 1, NULL, CURDATE(), CURDATE(), 104, 'Malibu Point', 4, NULL, 0, 9, 5, 1, CURDATE()), - (15, 1, 7, 1, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 105, 'An incredibly long alias for testing purposes', 125, NULL, 0, 3, 5, 1, CURDATE()), - (16, 1, 7, 1, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 106, 'Many Places', 126, NULL, 0, 3, 5, 1, CURDATE()), - (17, 1, 7, 2, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 106, 'Many Places', 126, NULL, 0, 3, 5, 1, CURDATE()), - (18, 1, 4, 4, 4, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 108, 'Cerebro', 128, NULL, 0, 12, 5, 1, CURDATE()), - (19, 1, 5, 5, NULL, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 109, 'Somewhere in Thailand', 129, NULL, 1, NULL, 5, 1, CURDATE()), - (20, 1, 5, 5, 3, DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 109, 'Somewhere in Thailand', 129, NULL, 0, 13, 5, 1, DATE_ADD(CURDATE(), INTERVAL +1 MONTH)), - (21, NULL, 5, 5, 5, DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 109, 'Somewhere in Holland', 102, NULL, 0, 13, 5, 1, DATE_ADD(CURDATE(), INTERVAL +1 MONTH)), - (22, NULL, 5, 5, 5, DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 109, 'Somewhere in Japan', 103, NULL, 0, 13, 5, 1, DATE_ADD(CURDATE(), INTERVAL +1 MONTH)), - (23, NULL, 8, 1, 7, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 101, 'address 21', 121, NULL, 0, 5, 5, 1, CURDATE()), - (24 ,NULL, 8, 1, 7, CURDATE(), CURDATE(), 101, 'Bruce Wayne', 1, NULL, 0, 5, 5, 1, CURDATE()); + (1 , 3, 1, 1, 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Bat cave', 121, 'T1111111', 0, 1, 5, 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (2 , 1, 1, 1, 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, 'T1111111', 0, 1, 5, 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (3 , 1, 7, 1, 6, DATE_ADD(CURDATE(), INTERVAL -2 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -2 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, 'T2222222', 0, 3, 5, 1, DATE_ADD(CURDATE(), INTERVAL -2 MONTH)), + (4 , 3, 2, 1, 2, DATE_ADD(CURDATE(), INTERVAL -3 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -3 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, 'T3333333', 0, 9, 5, 1, DATE_ADD(CURDATE(), INTERVAL -3 MONTH)), + (5 , 3, 3, 3, 3, DATE_ADD(CURDATE(), INTERVAL -4 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -4 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, 'T4444444', 0, 10, 5, 1, DATE_ADD(CURDATE(), INTERVAL -4 MONTH)), + (6 , 1, 3, 3, 3, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Mountain Drive Gotham', 1, 'A1111111', 0, 10, 5, 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (7 , NULL, 7, 1, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1101, 'Mountain Drive Gotham', 1, NULL, 0, 3, 5, 1, CURDATE()), + (8 , NULL, 7, 1, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1101, 'Bat cave', 121, NULL, 0, 3, 5, 1, CURDATE()), + (9 , NULL, 7, 1, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1104, 'Stark tower', 124, NULL, 0, 3, 5, 1, CURDATE()), + (10, 1, 1, 5, 1, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1102, 'Ingram Street', 2, NULL, 0, 1, 5, 1, CURDATE()), + (11, 1, 7, 1, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1102, 'NY roofs', 122, NULL, 0, 3, 5, 1, CURDATE()), + (12, 1, 1, 1, 1, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, CURDATE()), + (13, 1, 7, 1, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 3, 5, 1, CURDATE()), + (14, 1, 2, 1, NULL, CURDATE(), CURDATE(), 1104, 'Malibu Point', 4, NULL, 0, 9, 5, 1, CURDATE()), + (15, 1, 7, 1, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1105, 'An incredibly long alias for testing purposes', 125, NULL, 0, 3, 5, 1, CURDATE()), + (16, 1, 7, 1, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1106, 'Many Places', 126, NULL, 0, 3, 5, 1, CURDATE()), + (17, 1, 7, 2, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1106, 'Many Places', 126, NULL, 0, 3, 5, 1, CURDATE()), + (18, 1, 4, 4, 4, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1108, 'Cerebro', 128, NULL, 0, 12, 5, 1, CURDATE()), + (19, 1, 5, 5, NULL, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1109, 'Somewhere in Thailand', 129, NULL, 1, NULL, 5, 1, CURDATE()), + (20, 1, 5, 5, 3, DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 'Somewhere in Thailand', 129, NULL, 0, 13, 5, 1, DATE_ADD(CURDATE(), INTERVAL +1 MONTH)), + (21, NULL, 5, 5, 5, DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 'Somewhere in Holland', 102, NULL, 0, 13, 5, 1, DATE_ADD(CURDATE(), INTERVAL +1 MONTH)), + (22, NULL, 5, 5, 5, DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 'Somewhere in Japan', 103, NULL, 0, 13, 5, 1, DATE_ADD(CURDATE(), INTERVAL +1 MONTH)), + (23, NULL, 8, 1, 7, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1101, 'address 21', 121, NULL, 0, 5, 5, 1, CURDATE()), + (24 ,NULL, 8, 1, 7, CURDATE(), CURDATE(), 1101, 'Bruce Wayne', 1, NULL, 0, 5, 5, 1, CURDATE()); INSERT INTO `vn`.`ticketObservation`(`id`, `ticketFk`, `observationTypeFk`, `description`) VALUES @@ -682,18 +697,18 @@ INSERT INTO `vn`.`greugeType`(`id`, `name`, `code`) INSERT INTO `vn`.`greuge`(`id`, `clientFk`, `description`, `amount`, `shipped`, `created`, `greugeTypeFk`, `ticketFk`) VALUES - (1, 101, 'some diff charges', -19.99, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 1, 1), - (2, 101, 'more diff charges', 60, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 2, 1), - (3, 101, 'even more! diff charges', -9.99, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 3, 1), - (4, 101, 'insane diff charges', 60, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 4, 1), - (5, 101, 'gargantuous diff charges', -9.99, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 5, 1), - (6, 101, 'diff charges', 88.30, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 6, 1), - (7, 101, 'unaffordable diff charges', -39.12, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 1, 1), - (8, 101, 'some recovery charges', 29.35, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 2, 1), - (9, 101, 'some manna charges', -9.99, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 3, 1), - (10, 101, 'some claim charges', 13.13, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 4, 1), - (11, 101, 'some heritage charges', -15.99, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 5, 1), - (12, 101, 'some miscellaneous charges', 58.00, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 6, 1); + (1, 1101, 'some diff charges', -19.99, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 1, 1), + (2, 1101, 'more diff charges', 60, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 2, 1), + (3, 1101, 'even more! diff charges', -9.99, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 3, 1), + (4, 1101, 'insane diff charges', 60, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 4, 1), + (5, 1101, 'gargantuous diff charges', -9.99, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 5, 1), + (6, 1101, 'diff charges', 88.30, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 6, 1), + (7, 1101, 'unaffordable diff charges', -39.12, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 1, 1), + (8, 1101, 'some recovery charges', 29.35, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 2, 1), + (9, 1101, 'some manna charges', -9.99, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 3, 1), + (10, 1101, 'some claim charges', 13.13, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 4, 1), + (11, 1101, 'some heritage charges', -15.99, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 5, 1), + (12, 1101, 'some miscellaneous charges', 58.00, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 6, 1); INSERT INTO `vn`.`mandateType`(`id`, `name`) VALUES @@ -703,7 +718,7 @@ INSERT INTO `vn`.`mandateType`(`id`, `name`) INSERT INTO `vn`.`mandate`(`id`, `clientFk`, `companyFk`, `code`, `created`, `mandateTypeFk`) VALUES - (1, 102, 442, '1-1', CURDATE(), 2); + (1, 1102, 442, '1-1', CURDATE(), 2); INSERT INTO `vn`.`itemCategory`(`id`, `name`, `display`, `color`, `icon`, `code`) VALUES @@ -780,25 +795,29 @@ INSERT INTO `vn`.`itemFamily`(`code`, `description`) ('SER', 'Services'), ('VT', 'Sales'); -INSERT INTO `vn`.`item`(`id`, `typeFk`, `size`, `inkFk`, `stems`, `originFk`, `description`, `producerFk`, `intrastatFk`, `isOnOffer`, `expenceFk`, `isBargain`, `comment`, `relevancy`, `image`, `taxClassFk`, `subName`, `minPrice`, `stars`, `family`) +INSERT INTO `vn`.`item`(`id`, `typeFk`, `size`, `inkFk`, `stems`, `originFk`, `description`, `producerFk`, `intrastatFk`, `isOnOffer`, `expenceFk`, `isBargain`, `comment`, `relevancy`, `image`, `subName`, `minPrice`, `stars`, `family`) VALUES - (1, 2, 70, 'YEL', 1, 1, NULL, 1, 06021010, 0, 2000000000, 0, NULL, 0, '1', 1, NULL, 0, 1, 'VT'), - (2, 2, 70, 'BLU', 1, 2, NULL, 1, 06021010, 0, 2000000000, 0, NULL, 0, '2', 1, NULL, 0, 2, 'VT'), - (3, 1, 60, 'YEL', 1, 3, NULL, 1, 05080000, 0, 4751000000, 0, NULL, 0, '3', 1, NULL, 0, 5, 'VT'), - (4, 1, 60, 'YEL', 1, 1, 'Increases block', 1, 05080000, 1, 4751000000, 0, NULL, 0, '4', 2, NULL, 0, 3, 'VT'), - (5, 3, 30, 'RED', 1, 2, NULL, 2, 06021010, 1, 4751000000, 0, NULL, 0, '5', 2, NULL, 0, 3, 'VT'), - (6, 5, 30, 'RED', 1, 2, NULL, NULL, 06021010, 0, 4751000000, 0, NULL, 0, '6', 2, NULL, 0, 4, 'VT'), - (7, 5, 90, 'BLU', 1, 2, NULL, NULL, 06021010, 0, 4751000000, 0, NULL, 0, '7', 2, NULL, 0, 4, 'VT'), - (8, 2, 70, 'YEL', 1, 1, NULL, 1, 06021010, 0, 2000000000, 0, NULL, 0, '8', 1, NULL, 0, 5, 'VT'), - (9, 2, 70, 'BLU', 1, 2, NULL, 1, 06021010, 0, 2000000000, 0, NULL, 0, '9', 1, NULL, 0, 4, 'VT'), - (10, 1, 60, 'YEL', 1, 3, NULL, 1, 05080000, 0, 4751000000, 0, NULL, 0, '10', 1, NULL, 0, 4, 'VT'), - (11, 1, 60, 'YEL', 1, 1, NULL, 1, 05080000, 1, 4751000000, 0, NULL, 0, '11', 2, NULL, 0, 4, 'VT'), - (12, 3, 30, 'RED', 1, 2, NULL, 2, 06021010, 1, 4751000000, 0, NULL, 0, '12', 2, NULL, 0, 3, 'VT'), - (13, 5, 30, 'RED', 1, 2, NULL, NULL, 06021010, 0, 4751000000, 0, NULL, 0, '13', 2, NULL, 0, 2, 'VT'), - (14, 5, 90, 'BLU', 1, 2, NULL, NULL, 06021010, 0, 4751000000, 0, NULL, 0, '', 2, NULL, 0, 4, 'VT'), - (15, 4, NULL, NULL, NULL, 1, NULL, NULL, 06021010, 0, 4751000000, 0, NULL, 0, '', 2, NULL, 0, 0, 'EMB'), - (16, 4, NULL, NULL, NULL, 1, NULL, NULL, 06021010, 0, 4751000000, 0, NULL, 0, '', 2, NULL, 0, 0, 'EMB'), - (71, 4, NULL, NULL, NULL, 1, NULL, NULL, 06021010, 1, 4751000000, 0, NULL, 0, '', 2, NULL, 0, 0, 'VT'); + (1, 2, 70, 'YEL', 1, 1, NULL, 1, 06021010, 0, 2000000000, 0, NULL, 0, '1', NULL, 0, 1, 'VT'), + (2, 2, 70, 'BLU', 1, 2, NULL, 1, 06021010, 0, 2000000000, 0, NULL, 0, '2', NULL, 0, 2, 'VT'), + (3, 1, 60, 'YEL', 1, 3, NULL, 1, 05080000, 0, 4751000000, 0, NULL, 0, '3', NULL, 0, 5, 'VT'), + (4, 1, 60, 'YEL', 1, 1, 'Increases block', 1, 05080000, 1, 4751000000, 0, NULL, 0, '4', NULL, 0, 3, 'VT'), + (5, 3, 30, 'RED', 1, 2, NULL, 2, 06021010, 1, 4751000000, 0, NULL, 0, '5', NULL, 0, 3, 'VT'), + (6, 5, 30, 'RED', 1, 2, NULL, NULL, 06021010, 0, 4751000000, 0, NULL, 0, '6', NULL, 0, 4, 'VT'), + (7, 5, 90, 'BLU', 1, 2, NULL, NULL, 06021010, 0, 4751000000, 0, NULL, 0, '7', NULL, 0, 4, 'VT'), + (8, 2, 70, 'YEL', 1, 1, NULL, 1, 06021010, 0, 2000000000, 0, NULL, 0, '8', NULL, 0, 5, 'VT'), + (9, 2, 70, 'BLU', 1, 2, NULL, 1, 06021010, 0, 2000000000, 0, NULL, 0, '9', NULL, 0, 4, 'VT'), + (10, 1, 60, 'YEL', 1, 3, NULL, 1, 05080000, 0, 4751000000, 0, NULL, 0, '10', NULL, 0, 4, 'VT'), + (11, 1, 60, 'YEL', 1, 1, NULL, 1, 05080000, 1, 4751000000, 0, NULL, 0, '11', NULL, 0, 4, 'VT'), + (12, 3, 30, 'RED', 1, 2, NULL, 2, 06021010, 1, 4751000000, 0, NULL, 0, '12', NULL, 0, 3, 'VT'), + (13, 5, 30, 'RED', 1, 2, NULL, NULL, 06021010, 0, 4751000000, 0, NULL, 0, '13', NULL, 0, 2, 'VT'), + (14, 5, 90, 'BLU', 1, 2, NULL, NULL, 06021010, 0, 4751000000, 0, NULL, 0, '', NULL, 0, 4, 'VT'), + (15, 4, NULL, NULL, NULL, 1, NULL, NULL, 06021010, 0, 4751000000, 0, NULL, 0, '', NULL, 0, 0, 'EMB'), + (16, 4, NULL, NULL, NULL, 1, NULL, NULL, 06021010, 0, 4751000000, 0, NULL, 0, '', NULL, 0, 0, 'EMB'), + (71, 4, NULL, NULL, NULL, 1, NULL, NULL, 06021010, 1, 4751000000, 0, NULL, 0, '', NULL, 0, 0, 'VT'); + +-- Update the taxClass after insert of the items +UPDATE `vn`.`itemTaxCountry` SET `taxClassFk` = 2 + WHERE `itemFk` IN(4, 5, 6, 7, 11, 12, 13, 14, 15, 16, 71); INSERT INTO `vn`.`priceFixed`(`id`, `itemFk`, `rate0`, `rate1`, `rate2`, `rate3`, `started`, `ended`, `bonus`, `warehouseFk`, `created`) VALUES @@ -832,7 +851,7 @@ INSERT INTO `vn`.`expedition`(`id`, `agencyModeFk`, `ticketFk`, `isBox`, `create (7, 2, 4, 71, DATE_ADD(CURDATE(), INTERVAL -3 MONTH), NULL, 1, 1, 18, NULL, 94), (8, 3, 5, 71, DATE_ADD(CURDATE(), INTERVAL -4 MONTH), NULL, 1, 1, 18, NULL, 94), (9, 3, 6, 71, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), NULL, 1, 1, 18, NULL, 94), - (10, 7, 7, 71, CURDATE(), NULL, 1, 1, 18, NULL, 94); + (10, 7, 7, 71, NOW(), NULL, 1, 1, 18, NULL, 94); INSERT INTO `vn`.`ticketPackaging`(`id`, `ticketFk`, `packagingFk`, `quantity`, `created`, `pvp`) VALUES @@ -1017,15 +1036,15 @@ INSERT INTO `vn`.`saleComponent`(`saleFk`, `componentFk`, `value`) INSERT INTO `vn`.`itemShelving` (`id`, `itemFk`, `shelvingFk`, `shelve`, `deep`, `quantity`, `visible`, `available`, `grouping`, `packing`, `level`, `userFk`) VALUES - ('1', '2', 'GVC', 'A', '0', '1', '1', '1', '1', '1', '1', '106'), - ('2', '4', 'HEJ', 'A', '0', '2', '1', '1', '1', '1', '1', '106'); + ('1', '2', 'GVC', 'A', '0', '1', '1', '1', '1', '1', '1', '1106'), + ('2', '4', 'HEJ', 'A', '0', '2', '1', '1', '1', '1', '1', '1106'); INSERT INTO `vn`.`itemShelvingSale` (`itemShelvingFk`, `saleFk`, `quantity`, `created`, `userFk`) VALUES - ('1', '1', '1', '', '106'), - ('2', '2', '5', '', '106'), - ('1', '7', '1', '', '106'), - ('2', '8', '5', '', '106'); + ('1', '1', '1', '', '1106'), + ('2', '2', '5', '', '1106'), + ('1', '7', '1', '', '1106'), + ('2', '8', '5', '', '1106'); INSERT INTO `vncontrol`.`accion`(`accion_id`, `accion`) VALUES @@ -1054,10 +1073,15 @@ INSERT INTO `vn`.`itemPlacement`(`id`, `itemFk`, `warehouseFk`, `code`) (4, 2, 1, 'A44'); -INSERT INTO `vn`.`collection`(`id`, `workerFk`, `stateFk`) +INSERT INTO `vn`.`collection`(`id`, `workerFk`, `stateFk`, `created`) VALUES - (1, 106, 5), - (2, 106, 14); + (1, 1106, 5, DATE_ADD(CURDATE(),INTERVAL +1 DAY)), + (2, 1106, 14, CURDATE()); + +INSERT INTO `vn`.`ticketCollection`(`id`, `ticketFk`, `collectionFk`) + VALUES + (2, 2, 1), + (3, 3, 2); INSERT INTO `vn`.`parking` (`column`, `row`, `sectorFk`, `code`, `pickingOrder`) VALUES @@ -1065,11 +1089,11 @@ INSERT INTO `vn`.`parking` (`column`, `row`, `sectorFk`, `code`, `pickingOrder`) INSERT INTO `vn`.`shelving` (`code`, `parkingFk`, `priority`, `userFk`) VALUES - ('UXN', 1, 1, 106); + ('UXN', 1, 1, 1106); INSERT INTO `vn`.`itemShelving` (`itemFk`, `shelvingFk`, `shelve`, `deep`, `quantity`, `visible`, `available`, `grouping`, `packing`, `level`, `userFk`) VALUES - (1, 'UXN', 'A', 2, 12, 12, 12, 12, 12, 1, 106); + (1, 'UXN', 'A', 2, 12, 12, 12, 12, 12, 1, 1106); INSERT INTO `vn`.`ticketCollection` (`ticketFk`, `collectionFk`, `level`) VALUES @@ -1093,7 +1117,7 @@ INSERT INTO `vn`.`itemBotanical`(`itemFk`, `genusFk`, `specieFk`) (1, 1, 1), (2, 2, 2), (3, 2, NULL), - (4, NULL, NULL); + (4, 2, 1); INSERT INTO `vn`.`tag`(`id`, `code`, `name`, `isFree`, `isQuantitatif`, `sourceTable`, `unit`, `ediTypeFk`, `overwrite`) VALUES @@ -1231,18 +1255,18 @@ INSERT INTO `vn`.`itemLog` (`id`, `originFk`, `userFk`, `action`, `description`) INSERT INTO `vn`.`recovery`(`id`, `clientFk`, `started`, `finished`, `amount`, `period`) VALUES - (1, 101, DATE_ADD(CURDATE(),INTERVAL -7 MONTH), DATE_ADD(CURDATE(),INTERVAL -3 MONTH), 50, 7), - (2, 102, DATE_ADD(CURDATE(),INTERVAL -5 MONTH), CURDATE(), 100, 1), - (3, 102, CURDATE(), DATE_ADD(CURDATE(),INTERVAL 1 MONTH), 50, 7), - (4, 103, CURDATE(), NULL, 50, 7); + (1, 1101, DATE_ADD(CURDATE(),INTERVAL -7 MONTH), DATE_ADD(CURDATE(),INTERVAL -3 MONTH), 50, 7), + (2, 1102, DATE_ADD(CURDATE(),INTERVAL -5 MONTH), CURDATE(), 100, 1), + (3, 1102, CURDATE(), DATE_ADD(CURDATE(),INTERVAL 1 MONTH), 50, 7), + (4, 1103, CURDATE(), NULL, 50, 7); INSERT INTO `vn`.`annualAverageInvoiced`(`clientFk`, `invoiced`) VALUES - (101, 1500), - (102, 100), - (103, 1000), - (104, 500), - (105, 5000); + (1101, 1500), + (1102, 100), + (1103, 1000), + (1104, 500), + (1105, 5000); INSERT INTO `vn`.`supplierActivity`(`code`, `name`) VALUES @@ -1311,10 +1335,10 @@ INSERT INTO `vn`.`entry`(`id`, `supplierFk`, `created`, `travelFk`, `isConfirmed INSERT INTO `vn`.`claimRatio`(`clientFk`, `yearSale`, `claimAmount`, `claimingRate`, `priceIncreasing`, `packingRate`) VALUES - (101, 500, NULL, 0.00, 0.00, 1.00), - (102, 1000, 2.00, 0.01, 0.05, 1.00), - (103, 2000, 0.00, 0.00, 0.02, 1.00), - (104, 2500, 150.00, 0.02, 0.10, 1.00); + (1101, 500, NULL, 0.00, 0.00, 1.00), + (1102, 1000, 2.00, 0.01, 0.05, 1.00), + (1103, 2000, 0.00, 0.00, 0.02, 1.00), + (1104, 2500, 150.00, 0.02, 0.10, 1.00); INSERT INTO `bs`.`waste`(`buyer`, `year`, `week`, `family`, `itemFk`, `itemTypeFk`, `saleTotal`, `saleWaste`, `rate`) VALUES @@ -1354,28 +1378,28 @@ INSERT INTO `vn`.`buy`(`id`,`entryFk`,`itemFk`,`buyingValue`,`quantity`,`package 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 - (1, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 101, 3, 1, 121, 442, NULL, 'TPV', 1,'155.89', DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), - (2, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 104, 3, 1, 124, 442, NULL, 'WEB', 1,'100.10', DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), - (3, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -2 MONTH), INTERVAL +1 DAY), 104, 1, 2, 124, 442, NULL, 'ANDROID', 1,'107.25', DATE_ADD(CURDATE(), INTERVAL -2 MONTH), DATE_ADD(CURDATE(), INTERVAL -2 MONTH), DATE_ADD(CURDATE(), INTERVAL -2 MONTH)), - (4, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -3 MONTH), INTERVAL +1 DAY), 104, 1, 2, 124, 442, NULL, 'SALIX', 1,'10.01', DATE_ADD(CURDATE(), INTERVAL -3 MONTH), DATE_ADD(CURDATE(), INTERVAL -3 MONTH), DATE_ADD(CURDATE(), INTERVAL -3 MONTH)), - (5, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -4 MONTH), INTERVAL +1 DAY), 104, 1, 3, 124, 442, NULL, 'SALIX', 1,'10.01', DATE_ADD(CURDATE(), INTERVAL -4 MONTH), DATE_ADD(CURDATE(), INTERVAL -4 MONTH), DATE_ADD(CURDATE(), INTERVAL -4 MONTH)), - (6, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 101, 1, 3, 1, 442, NULL, 'SALIX', 1,'10.01', DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), - (7, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 101, 2, 7, 1, 442, NULL, 'SALIX', 0,'10.01', CURDATE(), CURDATE(), CURDATE()), - (8, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 101, 2, 7, 121, 442, NULL, 'SALIX', 0,'123.53', CURDATE(), CURDATE(), CURDATE()), - (9, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 104, 2, 7, 124, 442, NULL, 'SALIX', 0,'10.01', CURDATE(), CURDATE(), CURDATE()), - (10, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 102, 3, 1, 2, 442, NULL, 'SALIX', 0,'10.01', CURDATE(), CURDATE(), CURDATE()), - (11, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 102, 2, 7, 122, 442, NULL, 'SALIX', 0,'60.90', CURDATE(), CURDATE(), CURDATE()), - (12, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 103, 3, 1, 3, 442, NULL, 'SALIX', 0,'72.60', CURDATE(), CURDATE(), CURDATE()), - (13, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 103, 1, 2, 123, 442, NULL, 'SALIX', 0,'72.60', CURDATE(), CURDATE(), CURDATE()), - (14, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 104, 1, 2, 4, 442, NULL, 'SALIX', 0,'72.60', CURDATE(), CURDATE(), CURDATE()), - (15, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 105, 1, 3, 125, 442, NULL, 'SALIX', 0,'72.60', CURDATE(), CURDATE(), CURDATE()), - (16, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 106, 2, 7, 126, 442, NULL, 'SALIX', 0,'155.89', CURDATE(), CURDATE(), CURDATE()), - (17, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 107, 1, 4, 127, 442, NULL, 'SALIX', 0,'72.60', CURDATE(), CURDATE(), CURDATE()), - (18, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 108, 1, 4, 128, 442, NULL, 'SALIX', 0,'72.60', CURDATE(), CURDATE(), CURDATE()), - (19, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 109, 1, 5, 129, 442, NULL, 'SALIX', 0,'16.50', CURDATE(), CURDATE(), CURDATE()), - (20, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 109, 1, 5, 101, 442, NULL, 'SALIX', 0,'21.45', DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(CURDATE(), INTERVAL +1 MONTH)), - (21, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 109, 1, 5, 102, 442, NULL, 'SALIX', 0,'0.00', DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(CURDATE(), INTERVAL +1 MONTH)), - (22, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 109, 1, 5, 103, 442, NULL, 'SALIX', 0,'148.50', DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(CURDATE(), INTERVAL +1 MONTH)); + (1, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 3, 1, 121, 442, NULL, 'TPV', 1,'155.89', DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (2, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1104, 3, 1, 124, 442, NULL, 'WEB', 1,'100.10', DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (3, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -2 MONTH), INTERVAL +1 DAY), 1104, 1, 2, 124, 442, NULL, 'ANDROID', 1,'107.25', DATE_ADD(CURDATE(), INTERVAL -2 MONTH), DATE_ADD(CURDATE(), INTERVAL -2 MONTH), DATE_ADD(CURDATE(), INTERVAL -2 MONTH)), + (4, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -3 MONTH), INTERVAL +1 DAY), 1104, 1, 2, 124, 442, NULL, 'SALIX', 1,'10.01', DATE_ADD(CURDATE(), INTERVAL -3 MONTH), DATE_ADD(CURDATE(), INTERVAL -3 MONTH), DATE_ADD(CURDATE(), INTERVAL -3 MONTH)), + (5, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -4 MONTH), INTERVAL +1 DAY), 1104, 1, 3, 124, 442, NULL, 'SALIX', 1,'10.01', DATE_ADD(CURDATE(), INTERVAL -4 MONTH), DATE_ADD(CURDATE(), INTERVAL -4 MONTH), DATE_ADD(CURDATE(), INTERVAL -4 MONTH)), + (6, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 1, 3, 1, 442, NULL, 'SALIX', 1,'10.01', DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (7, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1101, 2, 7, 1, 442, NULL, 'SALIX', 0,'10.01', CURDATE(), CURDATE(), CURDATE()), + (8, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1101, 2, 7, 121, 442, NULL, 'SALIX', 0,'123.53', CURDATE(), CURDATE(), CURDATE()), + (9, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1104, 2, 7, 124, 442, NULL, 'SALIX', 0,'10.01', CURDATE(), CURDATE(), CURDATE()), + (10, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1102, 3, 1, 2, 442, NULL, 'SALIX', 0,'10.01', CURDATE(), CURDATE(), CURDATE()), + (11, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1102, 2, 7, 122, 442, NULL, 'SALIX', 0,'60.90', CURDATE(), CURDATE(), CURDATE()), + (12, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1103, 3, 1, 3, 442, NULL, 'SALIX', 0,'72.60', CURDATE(), CURDATE(), CURDATE()), + (13, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1103, 1, 2, 123, 442, NULL, 'SALIX', 0,'72.60', CURDATE(), CURDATE(), CURDATE()), + (14, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1104, 1, 2, 4, 442, NULL, 'SALIX', 0,'72.60', CURDATE(), CURDATE(), CURDATE()), + (15, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1105, 1, 3, 125, 442, NULL, 'SALIX', 0,'72.60', CURDATE(), CURDATE(), CURDATE()), + (16, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1106, 2, 7, 126, 442, NULL, 'SALIX', 0,'155.89', CURDATE(), CURDATE(), CURDATE()), + (17, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1107, 1, 4, 127, 442, NULL, 'SALIX', 0,'72.60', CURDATE(), CURDATE(), CURDATE()), + (18, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1108, 1, 4, 128, 442, NULL, 'SALIX', 0,'72.60', CURDATE(), CURDATE(), CURDATE()), + (19, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 1109, 1, 5, 129, 442, NULL, 'SALIX', 0,'16.50', CURDATE(), CURDATE(), CURDATE()), + (20, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 1, 5, 101, 442, NULL, 'SALIX', 0,'21.45', DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(CURDATE(), INTERVAL +1 MONTH)), + (21, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 1, 5, 102, 442, NULL, 'SALIX', 0,'0.00', DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(CURDATE(), INTERVAL +1 MONTH)), + (22, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 1, 5, 103, 442, NULL, 'SALIX', 0,'148.50', DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(CURDATE(), INTERVAL +1 MONTH)); INSERT INTO `hedera`.`orderRow`(`id`, `orderFk`, `itemFk`, `warehouseFk`, `shipment`, `amount`, `price`, `rate`, `created`, `saleFk`) VALUES @@ -1604,15 +1628,15 @@ INSERT INTO `hedera`.`visitAccess`(`id`, `agentFk`, `stamp`) INSERT INTO `hedera`.`visitUser`(`id`, `accessFk`, `userFk`, `stamp`) VALUES - (1, 1, 101, CURDATE()), - (2, 2, 101, CURDATE()), - (3, 3, 101, CURDATE()), - (4, 4, 102, CURDATE()), - (5, 5, 102, CURDATE()), - (6, 6, 102, CURDATE()), - (7, 7, 103, CURDATE()), - (8, 8, 103, CURDATE()), - (9, 9, 103, CURDATE()); + (1, 1, 1101, CURDATE()), + (2, 2, 1101, CURDATE()), + (3, 3, 1101, CURDATE()), + (4, 4, 1102, CURDATE()), + (5, 5, 1102, CURDATE()), + (6, 6, 1102, CURDATE()), + (7, 7, 1103, CURDATE()), + (8, 8, 1103, CURDATE()), + (9, 9, 1103, CURDATE()); INSERT INTO `hedera`.`userSession`(`created`, `lastUpdate`, `ssid`, `data`, `userVisitFk`) VALUES @@ -1628,10 +1652,10 @@ INSERT INTO `hedera`.`userSession`(`created`, `lastUpdate`, `ssid`, `data`, `use INSERT INTO `vn`.`clientContact`(`id`, `clientFk`, `name`, `phone`) VALUES - (1, 101, 'contact 1', 666777888), - (2, 101, 'contact 2', 111222333), - (3, 101, 'contact 3', 222333444), - (4, 102, 'contact 1', 876543219); + (1, 1101, 'contact 1', 666777888), + (2, 1101, 'contact 2', 111222333), + (3, 1101, 'contact 3', 222333444), + (4, 1102, 'contact 1', 876543219); INSERT INTO `vn`.`workerManaExcluded`(`workerFk`) VALUES @@ -1648,11 +1672,11 @@ call vn.manaSpellersRequery(18); INSERT INTO `vn`.`clientSample`(`id`, `clientFk`, `typeFk`, `created`, `workerFk`, `userFk`, `companyFk`) VALUES - (1, 101, 1, CURDATE(), 18, 18, 442), - (2, 101, 1, CURDATE(), 18, 18, 442), - (3, 101, 2, CURDATE(), 18, 18, 442), - (4, 102, 2, CURDATE(), 18, 18, 567), - (5, 102, 3, CURDATE(), 19, 19, 567); + (1, 1101, 1, CURDATE(), 18, 18, 442), + (2, 1101, 1, CURDATE(), 18, 18, 442), + (3, 1101, 2, CURDATE(), 18, 18, 442), + (4, 1102, 2, CURDATE(), 18, 18, 567), + (5, 1102, 3, CURDATE(), 19, 19, 567); INSERT INTO `vn`.`claimState`(`id`, `code`, `description`, `roleFk`, `priority`) VALUES @@ -1666,10 +1690,10 @@ INSERT INTO `vn`.`claimState`(`id`, `code`, `description`, `roleFk`, `priority`) INSERT INTO `vn`.`claim`(`id`, `ticketCreated`, `claimStateFk`, `observation`, `clientFk`, `workerFk`, `responsibility`, `isChargedToMana`, `created` ) VALUES - (1, CURDATE(), 1, 'observation one', 101, 18, 3, 0, CURDATE()), - (2, CURDATE(), 2, 'observation two', 101, 18, 3, 0, CURDATE()), - (3, CURDATE(), 3, 'observation three', 101, 18, 1, 1, CURDATE()), - (4, CURDATE(), 3, 'observation four', 104, 18, 5, 0, CURDATE()); + (1, CURDATE(), 1, 'observation one', 1101, 18, 3, 0, CURDATE()), + (2, CURDATE(), 2, 'observation two', 1101, 18, 3, 0, CURDATE()), + (3, CURDATE(), 3, 'observation three', 1101, 18, 1, 1, CURDATE()), + (4, CURDATE(), 3, 'observation four', 1104, 18, 5, 0, CURDATE()); INSERT INTO `vn`.`claimBeginning`(`id`, `claimFk`, `saleFk`, `quantity`) VALUES @@ -1706,12 +1730,12 @@ INSERT INTO `hedera`.`tpvMerchant`(`id`, `description`, `companyFk`, `bankFk`, ` INSERT INTO `hedera`.`tpvTransaction`(`id`,`merchantFk`, `clientFk`,`receiptFk`, `amount`, `response`, `errorCode`, `status`, `created`) VALUES - (1, 1, 101, NULL, 2000, NULL, 'SIS0042', 'ok', CURDATE()), - (2, 1, 101, NULL, 1000, NULL, 'SIS0051', 'started', CURDATE()), - (3, 2, 101, NULL, 7268, NULL, NULL, 'ok', CURDATE()), - (4, 2, 101, NULL, 4698, NULL, NULL, 'started', CURDATE()), - (5, 1, 104, NULL, 2000, NULL, 'SIS0043', 'ok', CURDATE()), - (6, 2, 104, NULL, 4000, NULL, 'SIS0044', 'started', CURDATE()); + (1, 1, 1101, NULL, 2000, NULL, 'SIS0042', 'ok', CURDATE()), + (2, 1, 1101, NULL, 1000, NULL, 'SIS0051', 'started', CURDATE()), + (3, 2, 1101, NULL, 7268, NULL, NULL, 'ok', CURDATE()), + (4, 2, 1101, NULL, 4698, NULL, NULL, 'started', CURDATE()), + (5, 1, 1104, NULL, 2000, NULL, 'SIS0043', 'ok', CURDATE()), + (6, 2, 1104, NULL, 4000, NULL, 'SIS0044', 'started', CURDATE()); INSERT INTO `vn`.`orderTicket`(`orderFk`, `ticketFk`) VALUES @@ -1747,20 +1771,20 @@ INSERT INTO `vn`.`userConfig` (`userFk`, `warehouseFk`, `companyFk`) INSERT INTO `vn`.`receipt`(`id`, `invoiceFk`, `amountPaid`, `amountUnpaid`, `payed`, `workerFk`, `bankFk`, `clientFk`, `created`, `companyFk`, `isConciliate`) VALUES - (1, 'Cobro web', 100.50, 0.00, CURDATE(), 9, 1, 101, CURDATE(), 442, 1), - (2, 'Cobro web', 200.50, 0.00, DATE_ADD(CURDATE(), INTERVAL -5 DAY), 9, 1, 101, DATE_ADD(CURDATE(), INTERVAL -5 DAY), 442, 1), - (3, 'Cobro en efectivo', 300.00, 100.00, DATE_ADD(CURDATE(), INTERVAL -10 DAY), 9, 1, 102, DATE_ADD(CURDATE(), INTERVAL -10 DAY), 442, 0), - (4, 'Cobro en efectivo', 400.00, -50.00, DATE_ADD(CURDATE(), INTERVAL -15 DAY), 9, 1, 103, DATE_ADD(CURDATE(), INTERVAL -15 DAY), 442, 0); + (1, 'Cobro web', 100.50, 0.00, CURDATE(), 9, 1, 1101, CURDATE(), 442, 1), + (2, 'Cobro web', 200.50, 0.00, DATE_ADD(CURDATE(), INTERVAL -5 DAY), 9, 1, 1101, DATE_ADD(CURDATE(), INTERVAL -5 DAY), 442, 1), + (3, 'Cobro en efectivo', 300.00, 100.00, DATE_ADD(CURDATE(), INTERVAL -10 DAY), 9, 1, 1102, DATE_ADD(CURDATE(), INTERVAL -10 DAY), 442, 0), + (4, 'Cobro en efectivo', 400.00, -50.00, DATE_ADD(CURDATE(), INTERVAL -15 DAY), 9, 1, 1103, DATE_ADD(CURDATE(), INTERVAL -15 DAY), 442, 0); INSERT INTO `vn`.`workerTeam`(`id`, `team`, `workerFk`) VALUES (1, 1, 9), (2, 2, 18), (3, 2, 19), - (4, 3, 101), - (5, 3, 102), - (6, 4, 103), - (7, 4, 104); + (4, 3, 1101), + (5, 3, 1102), + (6, 4, 1103), + (7, 4, 1104); INSERT INTO `vn`.`ticketRequest`(`id`, `description`, `requesterFk`, `attenderFk`, `quantity`, `itemFk`, `price`, `isOk`, `saleFk`, `ticketFk`, `created`) VALUES @@ -1819,7 +1843,7 @@ UPDATE `postgresql`.`business_labour` bl JOIN `postgresql`.`profile` pr ON pr.profile_id = b.client_id JOIN `postgresql`.`person` p ON p.person_id = pr.person_id SET bl.`professional_category_id` = 31 - WHERE p.`Id_trabajador` = 110; + WHERE p.`Id_trabajador` = 1110; UPDATE `postgresql`.`business_labour` bl SET bl.`department_id` = 43 @@ -1832,8 +1856,8 @@ INSERT INTO `postgresql`.`media`(`media_id`, `media_type_id`, `value`, `sort`) INSERT INTO `postgresql`.`profile_media`(`profile_media_id`, `profile_id`, `media_id`) VALUES - (1, 106, 1), - (2, 107, 2); + (1, 1106, 1), + (2, 1107, 2); INSERT INTO `vn`.`workCenter` (`id`, `name`, `warehouseFk`) VALUES @@ -1857,20 +1881,20 @@ INSERT INTO `postgresql`.`calendar_state` (`calendar_state_id`, `type`, `rgb`, ` INSERT INTO `postgresql`.`calendar_employee` (`business_id`, `calendar_state_id`, `date`) VALUES - (106, 1, IF(MONTH(CURDATE()) = 12 AND DAY(CURDATE()) > 10, DATE_ADD(CURDATE(), INTERVAL -10 DAY), DATE_ADD(CURDATE(), INTERVAL 10 DAY))), - (106, 1, IF(MONTH(CURDATE()) = 12 AND DAY(CURDATE()) > 10, DATE_ADD(CURDATE(), INTERVAL -11 DAY), DATE_ADD(CURDATE(), INTERVAL 11 DAY))), - (106, 1, IF(MONTH(CURDATE()) = 12 AND DAY(CURDATE()) > 10, DATE_ADD(CURDATE(), INTERVAL -12 DAY), DATE_ADD(CURDATE(), INTERVAL 12 DAY))), - (106, 1, IF(MONTH(CURDATE()) = 12 AND DAY(CURDATE()) > 10, DATE_ADD(CURDATE(), INTERVAL -20 DAY), DATE_ADD(CURDATE(), INTERVAL 20 DAY))), - (106, 2, IF(MONTH(CURDATE()) >= 1 AND DAY(CURDATE()) > 20, DATE_ADD(CURDATE(), INTERVAL -13 DAY), DATE_ADD(CURDATE(), INTERVAL 8 DAY))), - (106, 1, IF(MONTH(CURDATE()) >= 1 AND DAY(CURDATE()) > 20, DATE_ADD(CURDATE(), INTERVAL -14 DAY), DATE_ADD(CURDATE(), INTERVAL 9 DAY))), - (106, 2, IF(MONTH(CURDATE()) >= 1 AND DAY(CURDATE()) > 20, DATE_ADD(CURDATE(), INTERVAL -15 DAY), DATE_ADD(CURDATE(), INTERVAL 7 DAY))), - (107, 1, IF(MONTH(CURDATE()) = 12 AND DAY(CURDATE()) > 10, DATE_ADD(CURDATE(), INTERVAL -10 DAY), DATE_ADD(CURDATE(), INTERVAL 10 DAY))), - (107, 1, IF(MONTH(CURDATE()) = 12 AND DAY(CURDATE()) > 10, DATE_ADD(CURDATE(), INTERVAL -11 DAY), DATE_ADD(CURDATE(), INTERVAL 11 DAY))), - (107, 1, IF(MONTH(CURDATE()) = 12 AND DAY(CURDATE()) > 10, DATE_ADD(CURDATE(), INTERVAL -12 DAY), DATE_ADD(CURDATE(), INTERVAL 12 DAY))), - (107, 1, IF(MONTH(CURDATE()) = 12 AND DAY(CURDATE()) > 10, DATE_ADD(CURDATE(), INTERVAL -20 DAY), DATE_ADD(CURDATE(), INTERVAL 20 DAY))), - (107, 2, IF(MONTH(CURDATE()) >= 1 AND DAY(CURDATE()) > 20, DATE_ADD(CURDATE(), INTERVAL -13 DAY), DATE_ADD(CURDATE(), INTERVAL 8 DAY))), - (107, 1, IF(MONTH(CURDATE()) >= 1 AND DAY(CURDATE()) > 20, DATE_ADD(CURDATE(), INTERVAL -14 DAY), DATE_ADD(CURDATE(), INTERVAL 9 DAY))), - (107, 2, IF(MONTH(CURDATE()) >= 1 AND DAY(CURDATE()) > 20, DATE_ADD(CURDATE(), INTERVAL -15 DAY), DATE_ADD(CURDATE(), INTERVAL 7 DAY))); + (1106, 1, IF(MONTH(CURDATE()) = 12 AND DAY(CURDATE()) > 10, DATE_ADD(CURDATE(), INTERVAL -10 DAY), DATE_ADD(CURDATE(), INTERVAL 10 DAY))), + (1106, 1, IF(MONTH(CURDATE()) = 12 AND DAY(CURDATE()) > 10, DATE_ADD(CURDATE(), INTERVAL -11 DAY), DATE_ADD(CURDATE(), INTERVAL 11 DAY))), + (1106, 1, IF(MONTH(CURDATE()) = 12 AND DAY(CURDATE()) > 10, DATE_ADD(CURDATE(), INTERVAL -12 DAY), DATE_ADD(CURDATE(), INTERVAL 12 DAY))), + (1106, 1, IF(MONTH(CURDATE()) = 12 AND DAY(CURDATE()) > 10, DATE_ADD(CURDATE(), INTERVAL -20 DAY), DATE_ADD(CURDATE(), INTERVAL 20 DAY))), + (1106, 2, IF(MONTH(CURDATE()) >= 1 AND DAY(CURDATE()) > 20, DATE_ADD(CURDATE(), INTERVAL -13 DAY), DATE_ADD(CURDATE(), INTERVAL 8 DAY))), + (1106, 1, IF(MONTH(CURDATE()) >= 1 AND DAY(CURDATE()) > 20, DATE_ADD(CURDATE(), INTERVAL -14 DAY), DATE_ADD(CURDATE(), INTERVAL 9 DAY))), + (1106, 2, IF(MONTH(CURDATE()) >= 1 AND DAY(CURDATE()) > 20, DATE_ADD(CURDATE(), INTERVAL -15 DAY), DATE_ADD(CURDATE(), INTERVAL 7 DAY))), + (1107, 1, IF(MONTH(CURDATE()) = 12 AND DAY(CURDATE()) > 10, DATE_ADD(CURDATE(), INTERVAL -10 DAY), DATE_ADD(CURDATE(), INTERVAL 10 DAY))), + (1107, 1, IF(MONTH(CURDATE()) = 12 AND DAY(CURDATE()) > 10, DATE_ADD(CURDATE(), INTERVAL -11 DAY), DATE_ADD(CURDATE(), INTERVAL 11 DAY))), + (1107, 1, IF(MONTH(CURDATE()) = 12 AND DAY(CURDATE()) > 10, DATE_ADD(CURDATE(), INTERVAL -12 DAY), DATE_ADD(CURDATE(), INTERVAL 12 DAY))), + (1107, 1, IF(MONTH(CURDATE()) = 12 AND DAY(CURDATE()) > 10, DATE_ADD(CURDATE(), INTERVAL -20 DAY), DATE_ADD(CURDATE(), INTERVAL 20 DAY))), + (1107, 2, IF(MONTH(CURDATE()) >= 1 AND DAY(CURDATE()) > 20, DATE_ADD(CURDATE(), INTERVAL -13 DAY), DATE_ADD(CURDATE(), INTERVAL 8 DAY))), + (1107, 1, IF(MONTH(CURDATE()) >= 1 AND DAY(CURDATE()) > 20, DATE_ADD(CURDATE(), INTERVAL -14 DAY), DATE_ADD(CURDATE(), INTERVAL 9 DAY))), + (1107, 2, IF(MONTH(CURDATE()) >= 1 AND DAY(CURDATE()) > 20, DATE_ADD(CURDATE(), INTERVAL -15 DAY), DATE_ADD(CURDATE(), INTERVAL 7 DAY))); INSERT INTO `vn`.`smsConfig` (`id`, `uri`, `title`) VALUES @@ -1878,8 +1902,8 @@ INSERT INTO `vn`.`smsConfig` (`id`, `uri`, `title`) INSERT INTO `vn`.`sharingClient`(`id`, `workerFk`, `started`, `ended`, `clientFk`) VALUES - (1, 19, DATE_ADD(CURDATE(), INTERVAL -5 DAY), DATE_ADD(CURDATE(), INTERVAL +15 DAY), 101), - (2, 18, DATE_ADD(CURDATE(), INTERVAL -5 DAY), DATE_ADD(CURDATE(), INTERVAL +15 DAY), 106); + (1, 19, DATE_ADD(CURDATE(), INTERVAL -5 DAY), DATE_ADD(CURDATE(), INTERVAL +15 DAY), 1101), + (2, 18, DATE_ADD(CURDATE(), INTERVAL -5 DAY), DATE_ADD(CURDATE(), INTERVAL +15 DAY), 1106); INSERT INTO `vn`.`sharingCart`(`id`, `workerFk`, `started`, `ended`, `workerSubstitute`, `created`) VALUES @@ -1921,7 +1945,7 @@ INSERT INTO `vn`.`zoneIncluded` (`zoneFk`, `geoFk`, `isIncluded`) (8, 4, 0), (8, 5, 0), (8, 1, 1), - (10, 10, 1); + (10, 14, 1); INSERT INTO `vn`.`zoneEvent`(`zoneFk`, `type`, `dated`) VALUES @@ -2138,10 +2162,10 @@ INSERT INTO `vn`.`zoneEvent`(`zoneFk`, `type`, `weekDays`) INSERT INTO `vn`.`workerTimeControl`(`userFk`, `timed`, `manual`, `direction`) VALUES - (106, CONCAT(CURDATE(), ' 07:00'), TRUE, 'in'), - (106, CONCAT(CURDATE(), ' 10:00'), TRUE, 'middle'), - (106, CONCAT(CURDATE(), ' 10:10'), TRUE, 'middle'), - (106, CONCAT(CURDATE(), ' 15:00'), TRUE, 'out'); + (1106, CONCAT(CURDATE(), ' 07:00'), TRUE, 'in'), + (1106, CONCAT(CURDATE(), ' 10:00'), TRUE, 'middle'), + (1106, CONCAT(CURDATE(), ' 10:10'), TRUE, 'middle'), + (1106, CONCAT(CURDATE(), ' 15:00'), TRUE, 'out'); INSERT INTO `vn`.`dmsType`(`id`, `name`, `path`, `readRoleFk`, `writeRoleFk`, `code`) VALUES @@ -2182,13 +2206,13 @@ INSERT INTO `vn`.`ticketDms`(`ticketFk`, `dmsFk`) INSERT INTO `vn`.`clientDms`(`clientFk`, `dmsFk`) VALUES - (104, 2), - (104, 3); + (1104, 2), + (1104, 3); INSERT INTO `vn`.`workerDocument`(`id`, `worker`, `document`,`isReadableByWorker`) VALUES - (1, 106, 4, TRUE), - (2, 107, 3, FALSE); + (1, 1106, 4, TRUE), + (2, 1107, 3, FALSE); INSERT INTO `vn`.`device` (`sn`, `model`, `userFk`) VALUES @@ -2206,6 +2230,11 @@ INSERT INTO `vn`.`workerTimeControlParams` (`id`, `dayBreak`, `weekBreak`, `week INSERT IGNORE INTO `vn`.`greugeConfig` (`id`, `freightPickUpPrice`) VALUES ('1', '11'); +INSERT INTO `vn`.`temperature`(`code`, `name`, `description`) + VALUES + ('WARM', 'Warm', 'Warm'), + ('COOL', 'Cool', 'Cool'); + INSERT INTO `vn`.`thermograph`(`id`, `model`) VALUES ('TMM190901395', 'TEMPMATE'), @@ -2213,7 +2242,8 @@ INSERT INTO `vn`.`thermograph`(`id`, `model`) ('TZ1905012010', 'DISPOSABLE'), ('138350-0', 'DISPOSABLE'); -INSERT INTO `vn`.`travelThermograph`(`thermographFk`, `created`, `warehouseFk`, `travelFk`, `temperature`, `result`, `dmsFk`) + +INSERT INTO `vn`.`travelThermograph`(`thermographFk`, `created`, `warehouseFk`, `travelFk`, `temperatureFk`, `result`, `dmsFk`) VALUES ('TMM190901395', CURDATE(), 1, 1, 'WARM', 'Ok', NULL), ('TL.BBA85422', DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 2, 2, 'COOL', 'Ok', NULL), @@ -2282,7 +2312,7 @@ INSERT INTO `vn`.`awb` (id, code, package, weight, created, amount, transitoryFk (9, '99610289193', 302, 2972, CURDATE(), 3871, 442, 1), (10, '07546500856', 185, 2364, CURDATE(), 5321, 442, 1); -REPLACE INTO vn.dua (id, code, awbFk, issued, operated, booked, bookEntried, gestdocFk, customsValue, companyFk) +INSERT INTO `vn`.`dua` (id, code, awbFk, issued, operated, booked, bookEntried, gestdocFk, customsValue, companyFk) VALUES (1, '19ES0028013A481523', 1, CURDATE(), CURDATE(), CURDATE(), CURDATE(), 1, 11276.95, 442), (2, '21ES00280136115760', 2, CURDATE(), CURDATE(), CURDATE(), CURDATE(), 2, 1376.20, 442), @@ -2291,9 +2321,9 @@ REPLACE INTO vn.dua (id, code, awbFk, issued, operated, booked, bookEntried, ges (5, '19ES00280132022070', 5, CURDATE(), CURDATE(), CURDATE(), CURDATE(), 2, 10012.49, 442), (6, '19ES00280132032308', 6, CURDATE(), CURDATE(), CURDATE(), CURDATE(), 2, 19914.25, 442), (7, '19ES00280132025489', 7, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), CURDATE(), CURDATE(), CURDATE(), 2, 1934.06, 442), - (8, '19ES00280132025489', 8, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), CURDATE(), CURDATE(), CURDATE(), 2, 3618.52, 442), - (9, '19ES00280132025489', 9, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), CURDATE(), CURDATE(), CURDATE(), 2, 7126.23, 442), - (10, '19ES00280132025489', 10, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), CURDATE(), CURDATE(), CURDATE(), 2, 4631.45, 442); + (8, '19ES00280132025490', 8, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), CURDATE(), CURDATE(), CURDATE(), 2, 3618.52, 442), + (9, '19ES00280132025491', 9, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), CURDATE(), CURDATE(), CURDATE(), 2, 7126.23, 442), + (10, '19ES00280132025492', 10, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), CURDATE(), CURDATE(), CURDATE(), 2, 4631.45, 442); REPLACE INTO `vn`.`invoiceIn`(`id`, `serialNumber`,`serial`, `supplierFk`, `issued`, `created`, `supplierRef`, `isBooked`, `companyFk`, `docFk`) VALUES @@ -2330,11 +2360,26 @@ INSERT INTO `vn`.`duaInvoiceIn`(`id`, `duaFk`, `invoiceInFk`) (4, 4, 4), (5, 5, 5), (6, 6, 6), - (7, 7, 7), - (8, 8, 8), + (7, 7, 7), + (8, 8, 8), (9, 9, 9), (10, 10, 10); +INSERT INTO `vn`.`invoiceInTax` (`invoiceInFk`, `taxableBase`, `expenceFk`, `foreignValue`, `taxTypeSageFk`, `transactionTypeSageFk`) + VALUES + (1, 99.99, '2000000000', null, null, null), + (2, 999.99, '2000000000', null, null, null), + (3, 1000.50, '2000000000', null, null, null), + (4, 0.50, '2000000000', null, null, null), + (5, 150.50, '2000000000', null, null, null), + (1, 252.25, '4751000000', NULL, 7, 61), + (2, 223.17, '6210000567', NULL, 8, 20), + (3, 95.60, '7001000000', NULL, 8, 35), + (4, 446.63, '7001000000', NULL, 6, 61), + (5, 64.23, '6210000567', NULL, 8, 20), + (6, 29.95, '7001000000', NULL, 7, 20), + (7, 58.64, '6210000567', NULL, 8, 20); + INSERT INTO `vn`.`ticketRecalc`(`ticketFk`) SELECT `id` FROM `vn`.`ticket` t @@ -2369,4 +2414,6 @@ INSERT INTO `vn`.`expeditionScan` (`id`, `expeditionFk`, `scanned`, `palletFk`) (7, 7, CURDATE(), 1), (8, 8, CURDATE(), 1), (9, 9, CURDATE(), 1), - (10, 10, CURDATE(), 1); \ No newline at end of file + (10, 10, CURDATE(), 1); + +CALL `cache`.`last_buy_refresh`(FALSE); \ No newline at end of file diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 8df46890d0..1565e029fe 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -1,4 +1,4 @@ --- MariaDB dump 10.19 Distrib 10.5.9-MariaDB, for debian-linux-gnu (x86_64) +-- MariaDB dump 10.19 Distrib 10.6.4-MariaDB, for Linux (x86_64) -- -- Host: db.verdnatura.es Database: account -- ------------------------------------------------------ @@ -2544,7 +2544,7 @@ CREATE TABLE `clientDied` ( `Boss` varchar(3) COLLATE utf8_unicode_ci NOT NULL, `Aviso` varchar(13) CHARACTER SET utf8 DEFAULT NULL, PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Clientes que no han comprado en los ultimos 3 meses, se actualiza con proceso nocturno el 3 de cada mes'; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -2607,7 +2607,7 @@ DROP TABLE IF EXISTS `compradores`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `compradores` ( - `Id_Trabajador` int(11) NOT NULL, + `Id_Trabajador` int(10) unsigned NOT NULL, `año` int(4) NOT NULL, `semana` int(2) NOT NULL, `importe` decimal(10,2) DEFAULT NULL, @@ -2625,7 +2625,7 @@ DROP TABLE IF EXISTS `compradores_evolution`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `compradores_evolution` ( - `Id_Trabajador` int(11) NOT NULL, + `Id_Trabajador` int(10) unsigned NOT NULL, `fecha` date NOT NULL, `importe` decimal(10,0) DEFAULT NULL, PRIMARY KEY (`Id_Trabajador`,`fecha`), @@ -3205,7 +3205,7 @@ DROP TABLE IF EXISTS `salesByclientSalesPerson`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `salesByclientSalesPerson` ( `dated` date NOT NULL DEFAULT '0000-00-00', - `salesPersonFk` int(11) DEFAULT NULL, + `salesPersonFk` int(10) unsigned DEFAULT NULL, `clientFk` int(11) NOT NULL, `amount` decimal(10,3) NOT NULL DEFAULT '0.000', `equalizationTax` decimal(10,3) NOT NULL DEFAULT '0.000', @@ -3282,7 +3282,7 @@ DROP TABLE IF EXISTS `salesPersonEvolution`; CREATE TABLE `salesPersonEvolution` ( `id` int(11) NOT NULL AUTO_INCREMENT, `dated` date NOT NULL DEFAULT '0000-00-00', - `salesPersonFk` int(11) DEFAULT NULL, + `salesPersonFk` int(10) unsigned DEFAULT NULL, `amount` decimal(10,3) NOT NULL DEFAULT '0.000', `equalizationTax` decimal(10,3) NOT NULL DEFAULT '0.000', `amountNewBorn` decimal(10,3) NOT NULL DEFAULT '0.000', @@ -3318,7 +3318,7 @@ DROP TABLE IF EXISTS `vendedores`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `vendedores` ( - `Id_Trabajador` int(11) NOT NULL, + `Id_Trabajador` int(10) unsigned NOT NULL, `año` int(4) NOT NULL, `mes` int(2) NOT NULL, `importe` decimal(10,2) DEFAULT NULL, @@ -3343,7 +3343,7 @@ DROP TABLE IF EXISTS `vendedores_evolution`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `vendedores_evolution` ( - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, `year` int(11) NOT NULL, `sales` decimal(10,2) DEFAULT NULL, `month` int(11) NOT NULL, @@ -3412,11 +3412,12 @@ CREATE TABLE `waste` ( `year` int(4) NOT NULL, `week` int(2) NOT NULL, `family` varchar(30) COLLATE utf8_unicode_ci NOT NULL, - `itemFk` int(11) DEFAULT NULL, + `itemFk` int(11) NOT NULL DEFAULT '0', `itemTypeFk` smallint(5) unsigned DEFAULT NULL, `saleTotal` decimal(16,0) DEFAULT NULL, `saleWaste` decimal(16,0) DEFAULT NULL, `rate` decimal(5,1) DEFAULT NULL, + PRIMARY KEY (`buyer`,`year`,`week`,`family`,`itemFk`), KEY `waste_itemType_id` (`itemTypeFk`), KEY `waste_item_id` (`itemFk`), CONSTRAINT `waste_itemType_id` FOREIGN KEY (`itemTypeFk`) REFERENCES `vn`.`itemType` (`id`) ON UPDATE CASCADE, @@ -3449,7 +3450,7 @@ CREATE TABLE `workerProductivity` ( `id` int(11) NOT NULL AUTO_INCREMENT, `dated` date NOT NULL, `warehouseFk` smallint(6) unsigned NOT NULL, - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, `volume` decimal(10,6) NOT NULL, `seconds` int(11) NOT NULL, `roleFk` int(10) unsigned NOT NULL, @@ -3605,7 +3606,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `analisisComponentes` */; +/*!50003 DROP PROCEDURE IF EXISTS `analisisComponentes__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -3615,7 +3616,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `analisisComponentes`() +CREATE DEFINER=`root`@`%` PROCEDURE `analisisComponentes__`() BEGIN DECLARE vDateStart DATE DEFAULT '2016-01-01'; @@ -3700,9 +3701,10 @@ BEGIN SELECT c.Id_Banco, IFNULL(SUM(Entrada),0) - IFNULL(SUM(Salida),0) as saldo FROM vn2008.Cajas c JOIN vn2008.Bancos b using(Id_Banco) -- saldos de las cajas - WHERE cash IN (0,3) + JOIN vn.accountingType at2 ON at2.id = b.cash + WHERE at2.code IN ('wireTransfer','fundingLine') AND Cajafecha = vCurrentDate - AND (Serie = 'MB' OR cash = 3) + AND (Serie = 'MB' OR at2.code = 'fundingLine') GROUP BY Id_Banco )sub GROUP BY Id_Banco @@ -3750,7 +3752,8 @@ BEGIN FROM vn.time t JOIN vn2008.Saldos_Prevision sp ON sp.Fecha <= t.dated JOIN vn2008.Bancos b ON sp.Id_Banco = b.Id_Banco - WHERE b.cash IN (0,3) + JOIN vn.accountingType at2 ON at2.id = b.cash + WHERE at2.code IN ('wireTransfer','fundingLine') AND t.dated BETWEEN vStartingDate AND vMaxDate GROUP BY t.dated, sp.Id_Banco ON DUPLICATE KEY UPDATE saldo = saldo + VALUES(saldo); @@ -3762,10 +3765,11 @@ BEGIN -- Deuda UPDATE bs.bancos_evolution be - JOIN vn2008.Bancos using(Id_Banco) - SET be.deuda = IF(cash = 3, be.saldo_aux, 0) - , be.saldo = IF(cash = 3, 0, be.saldo_aux) - WHERE Fecha >= vStartingDate; + JOIN vn2008.Bancos b using(Id_Banco) + JOIN vn.accountingType at2 ON at2.id = b.cash + SET be.deuda = IF(at2.code = 'fundingLine', be.saldo_aux, 0) + , be.saldo = IF(at2.code = 'fundingLine', 0, be.saldo_aux) + WHERE Fecha >= vStartingDate; -- Liquidez update bs.bancos_evolution set liquidez = saldo - quilla + deuda WHERE Fecha >= vStartingDate; @@ -3982,7 +3986,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `bs` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 DROP PROCEDURE IF EXISTS `clean` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -4018,21 +4022,18 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `clientDied` */; +/*!50003 DROP PROCEDURE IF EXISTS `clientDied_recalc` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `clientDied`() +CREATE DEFINER=`root`@`%` PROCEDURE `clientDied_recalc`() BEGIN - - IF DAY(CURDATE()) = 3 THEN - SET @primerAviso := TIMESTAMPADD(MONTH,-1,CURDATE()); SET @segundoAviso := TIMESTAMPADD(MONTH,-2,CURDATE()); SET @tercerAviso := TIMESTAMPADD(MONTH,-3,CURDATE()); @@ -4059,8 +4060,9 @@ BEGIN WHERE (maxIssued IS NULL OR maxIssued < @primerAviso) AND c.created < @tercerAviso; - END IF; - + DELETE cd.* FROM bs.clientDied cd + JOIN vn.ticket t ON t.clientFk = cd.id + WHERE t.refFk IS NULL AND t.shipped >=TIMESTAMPADD(MONTH,-1,CURDATE()); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4446,7 +4448,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `bs` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 DROP PROCEDURE IF EXISTS `compradores_add_launcher` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -4676,7 +4678,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `bs` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 DROP PROCEDURE IF EXISTS `fruitsEvolution` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -5904,38 +5906,6 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `userSundayRole__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `userSundayRole__`() -BEGIN - -- 4996 Fran Natek Echevarria - DECLARE vDay INT; - SET vDay := (SELECT DAYOFWEEK(CURDATE())); - IF vDay = 1 THEN - UPDATE account.user u - JOIN account.role r - SET u.role = r.id - WHERE u.id = 4996 AND r.name = "salesAssistant"; - ELSE - UPDATE account.user u - JOIN account.role r - SET u.role = r.id - WHERE u.id = 4996 AND r.name = "salesPerson"; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `vendedores_add` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -6056,165 +6026,6 @@ BEGIN CALL bs.vendedores_evolution_add; CALL bs.salesPersonClient_add(YEAR(CURDATE()), QUARTER(CURDATE())); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `vendedores_add__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_add__`(intYEAR INT, vQuarter INT) -BEGIN - - DECLARE vCommissionRate DOUBLE DEFAULT 0.029; - - -- vaciar tabla - DELETE v.* FROM vendedores v - JOIN vn.`time` t ON t.`year` = v.año AND t.`month` = v.mes - WHERE t.`year` = intYEAR AND QUARTER(t.dated) = vQuarter; - - REPLACE vendedores(Id_Trabajador, año, mes, importe, comision) - SELECT c.Id_Trabajador - , intYEAR - , MONTH(v.fecha) intMONTH - , sum(v.importe) - , sum(v.importe) * vCommissionRate - FROM ventas v - JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente - JOIN vn.`time` t on t.dated = v.fecha - WHERE c.Id_Trabajador is not null - AND t.`year` = intYEAR AND QUARTER(t.dated) = vQuarter - GROUP BY c.Id_Trabajador, t.`month`; - - -- Ventas nuevas - UPDATE vendedores v - JOIN - ( - SELECT c.Id_Trabajador - , sum(importe) * vCommissionRate as comisionNueva - , t.`month` - , t.`year` - FROM ventas v - JOIN bs.clientNewBorn cnb on v.Id_Cliente = cnb.clientFk - JOIN vn2008.Clientes c ON c.Id_Cliente = v.Id_Cliente - JOIN vn2008.`time` t on t.`date` = v.fecha - WHERE c.Id_Trabajador is not null - AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter - AND cnb.firstShipped > DATE_ADD(v.fecha, INTERVAL -1 YEAR) - GROUP BY c.Id_Trabajador, t.`month` - ) sub ON sub.Id_Trabajador = v.Id_Trabajador AND sub.`month` = v.mes AND sub.`year` = v.año - SET v.comisionNuevos = sub.comisionNueva, v.comision = v.comision - sub.comisionNueva; - - -- Ventas cedidas - UPDATE vendedores v - JOIN ( - SELECT cc.Id_Trabajador_old as Id_Trabajador - , sum(importe) * vCommissionRate * comision_old as cedido - , sum(importe) * vCommissionRate * comision_new as arrendada - , t.`month` - , t.`year` - FROM ventas v - JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente - JOIN vn2008.Clientes_cedidos cc on cc.Id_Cliente = c.Id_Cliente AND v.fecha between datSTART and datEND - JOIN vn2008.`time` t on t.`date` = v.fecha - WHERE c.Id_Trabajador is not null - AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter - GROUP BY cc.Id_Trabajador_old, t.`month` - ) sub ON sub.Id_Trabajador = v.Id_Trabajador AND sub.`month` = v.mes AND sub.`year` = v.año - SET v.comisionCedida = sub.cedido, v.comision = v.comision - sub.cedido - sub.arrendada; - - -- Ventas arrendadas - UPDATE vendedores v - JOIN ( - SELECT cc.Id_Trabajador_new as Id_Trabajador - , sum(importe) * vCommissionRate * comision_new as arrendada - , t.`month` - , t.`year` - FROM ventas v - JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente - JOIN vn2008.Clientes_cedidos cc on cc.Id_Cliente = c.Id_Cliente AND v.fecha between datSTART and datEND - JOIN vn2008.`time` t on t.`date` = v.fecha - WHERE c.Id_Trabajador is not null - AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter - GROUP BY cc.Id_Trabajador_new, t.`month` - ) sub ON sub.Id_Trabajador = v.Id_Trabajador AND sub.`month` = v.mes AND sub.`year` = v.año - SET v.comisionArrendada = sub.arrendada; - - -- Sustitucion cedidas - lended - INSERT INTO vendedores (Id_Trabajador, mes, año, comision) - SELECT c.salesPersonFk - , t.`month` - , t.`year` - , sum(importe) * vCommissionRate as lended - FROM ventas v - JOIN vn.client c ON c.id = v.Id_Cliente - JOIN vn.sharingCartDaily scd on scd.ownerFk = c.salesPersonFk AND scd.dated = v.fecha - JOIN vn.`time` t ON t.dated = v.fecha - WHERE t.`year` = intYEAR AND QUARTER(t.dated) = vQuarter - GROUP BY c.salesPersonFk, t.`month` - ON DUPLICATE KEY UPDATE comision = comision - VALUES(comision); - - -- Sustitucion arrendadas - borrowed - INSERT INTO vendedores (Id_Trabajador, mes, año, sustitucionArrendada) - SELECT scd.substituteFk - , t.`month` - , t.`year` - , sum(importe) * vCommissionRate as borrowed - FROM ventas v - JOIN vn.client c ON c.id = v.Id_Cliente - JOIN vn.sharingCartDaily scd on scd.ownerFk = c.salesPersonFk AND scd.dated = v.fecha - JOIN vn.`time` t ON t.dated = v.fecha - WHERE t.`year` = intYEAR AND QUARTER(t.dated) = vQuarter - GROUP BY scd.substituteFk, t.`month` - ON DUPLICATE KEY UPDATE sustitucionArrendada = VALUES(sustitucionArrendada); - - DROP TEMPORARY TABLE IF EXISTS tmp.workerItemType; - CREATE TEMPORARY TABLE tmp.workerItemType - (INDEX(ownerWorkerFk, itemTypeFk)) - SELECT wd.workerFk ownerWorkerFk, itemTypeFk, dit.workerFk substituteFk - FROM vn.departmentItemType dit - JOIN vn.workerDepartment wd ON wd.departmentFk = dit.departmentFk; - - -- itemType Lended, prestado - UPDATE vendedores v - JOIN ( - SELECT c.Id_Trabajador - , sum(importe) * vCommissionRate as amount - , t.`month` - , t.`year` - FROM ventas v - JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente - JOIN tmp.workerItemType wit ON wit.ownerWorkerFk = c.Id_Trabajador AND wit.itemTypeFk = v.tipo_id - JOIN vn2008.`time` t on t.`date` = v.fecha - WHERE t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter - GROUP BY c.Id_Trabajador, t.`month` - ) sub ON sub.Id_Trabajador = v.Id_Trabajador AND sub.`month` = v.mes AND sub.`year` = v.año - SET v.comision = v.comision - sub.amount; - - -- itemType borrowed, tomado prestado - INSERT INTO vendedores (Id_Trabajador, año, mes, itemTypeBorrowed) - SELECT wit.substituteFk - , t.`year` - , t.`month` - , importe * vCommissionRate - FROM ventas v - JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente - JOIN tmp.workerItemType wit ON wit.ownerWorkerFk = c.Id_Trabajador AND wit.itemTypeFk = v.tipo_id - JOIN vn2008.`time` t on t.`date` = v.fecha - WHERE t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter - ON DUPLICATE KEY UPDATE itemTypeBorrowed = itemTypeBorrowed + values(itemTypeBorrowed); - - DROP TEMPORARY TABLE tmp.workerItemType; - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6278,80 +6089,6 @@ Inserta en la tabla compradores_evolution las ventas acumuladas en el ultimo mes END IF; END WHILE; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `vendedores_evolution_add__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_evolution_add__`() -BEGIN -/* - -Inserta en la tabla compradores_evolution las ventas acumuladas en el ultimo mes - -*/ - -DECLARE vYear, vMonth INTEGER; -DECLARE vCurYear, vCurMonth INTEGER; -DECLARE vFirstYear INTEGER DEFAULT 2017; -DECLARE vFirstMonth INTEGER DEFAULT 1; - -DECLARE vDateFrom DATE; -DECLARE vDateTo DATE; - -SET vCurYear = year(CURDATE()); -SET vCurMonth = month(CURDATE()); - -SELECT IFNULL(max(year),vFirstYear), IFNULL(max(month),vFirstMonth) - INTO vYear, vMonth - FROM bs.vendedores_evolution; - - WHILE (vYear < vCurYear) OR (vYear = vCurYear AND vMonth < vCurMonth) DO - - SELECT max(dated), TIMESTAMPADD(DAY,-364,max(dated)) INTO vDateTo, vDateFrom - FROM vn.time - WHERE year = vYear - AND month = vMonth; - - SELECT vDateTo, vDateFrom, vYear, vMonth; - - REPLACE bs.vendedores_evolution( workerFk - , year - , month - , sales) - SELECT c.salesPersonFk - , vYear as year - , vMonth as month - , sum(v.importe) as sales - FROM bs.ventas v - JOIN vn.client c on c.id = v.Id_Cliente - WHERE v.fecha BETWEEN vDateFrom AND vDateTo - AND c.salesPersonFk is not null - GROUP BY c.salesPersonFk; - - SET vMonth = vMonth + 1; - - IF vMonth = 13 THEN - - SET vMonth = 1; - SET vYear = vYear + 1; - - END IF; - - END WHILE; - - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6398,21 +6135,31 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ventas_add`(IN datSTART DATETIME, IN datEND DATETIME) BEGIN + /** + * Añade las ventas que se realizaron de hace + * una semana hasta hoy + * + * @param datSTART Fecha de inicio + * @param datEND Fecha de finalizacion + * + **/ + DECLARE vStartingDate DATETIME; DECLARE vEndingDate DATETIME; DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; - IF datSTART < '2015-10-01' OR datEND < '2015-10-01' THEN - CALL util.throw('fechaDemasiadoAntigua'); + IF datSTART < TIMESTAMPADD(YEAR,-5,CURDATE()) + OR datEND < TIMESTAMPADD(YEAR,-5,CURDATE()) THEN + CALL util.throw('fechaDemasiadoAntigua'); END IF; SET datEND = util.dayEnd(datEND); @@ -6421,54 +6168,52 @@ BEGIN DELETE FROM ventas - WHERE fecha between vStartingDate and datEND; - + WHERE fecha BETWEEN vStartingDate AND datEND; + WHILE vEndingDate <= datEND DO - + REPLACE ventas(Id_Movimiento, importe, recargo, fecha, tipo_id, Id_Cliente, empresa_id) SELECT Id_Movimiento, - SUM(IF(base, Cantidad * Valor, 0)) as importe, - SUM(IF(base, 0, Cantidad * Valor)) as recargo, + SUM(IF(base, Cantidad * Valor, 0)) AS importe, + SUM(IF(base, 0, Cantidad * Valor)) AS recargo, vStartingDate, a.tipo_id, cs.Id_Cliente, t.empresa_id FROM vn2008.Movimientos_componentes mc - JOIN bi.tarifa_componentes tc using(Id_Componente) - JOIN bi.tarifa_componentes_series tcs using(tarifa_componentes_series_id) - JOIN vn2008.Movimientos m using(Id_Movimiento) - JOIN vn2008.Articles a using(Id_Article) - JOIN vn2008.Tipos tp using(tipo_id) - JOIN vn2008.reinos r on r.id = tp.reino_id - JOIN vn2008.Tickets t using(Id_Ticket) - JOIN vn2008.Consignatarios cs using(Id_Consigna) - JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente - WHERE t.Fecha between vStartingDate and vEndingDate + JOIN bi.tarifa_componentes tc USING(Id_Componente) + JOIN bi.tarifa_componentes_series tcs USING(tarifa_componentes_series_id) + JOIN vn2008.Movimientos m USING(Id_Movimiento) + JOIN vn2008.Articles a USING(Id_Article) + JOIN vn2008.Tipos tp USING(tipo_id) + JOIN vn2008.reinos r ON r.id = tp.reino_id + JOIN vn2008.Tickets t USING(Id_Ticket) + JOIN vn2008.Consignatarios cs USING(Id_Consigna) + JOIN vn2008.Clientes c ON c.Id_Cliente = cs.Id_Cliente + WHERE t.Fecha BETWEEN vStartingDate AND vEndingDate AND c.typeFk IN ('Normal','handMaking','internalUse') AND m.Cantidad <> 0 AND a.tipo_id != TIPO_PATRIMONIAL AND m.Descuento <> 100 - AND (m.Id_Article = 98 or m.Id_Article = 95 or r.mercancia != 0) + AND (m.Id_Article = 98 OR m.Id_Article = 95 OR r.mercancia != 0) GROUP BY mc.Id_Movimiento HAVING IFNULL(importe,0) <> 0 OR IFNULL(recargo,0) <> 0; - UPDATE bs.ventas v JOIN ( SELECT s.id, sum(s.quantity * sc.value ) AS margen, s.quantity * s.price * (100 - s.discount ) / 100 AS pvp FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.saleComponent sc ON sc.saleFk = s.id - JOIN vn.component c ON c.id = sc.componentFk - JOIN vn.componentType ct ON ct.id = c.typeFk + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.saleComponent sc ON sc.saleFk = s.id + JOIN vn.component c ON c.id = sc.componentFk + JOIN vn.componentType ct ON ct.id = c.typeFk WHERE t.shipped BETWEEN vStartingDate AND vEndingDate AND ct.isMargin = TRUE GROUP BY s.id) sub ON sub.id = v.Id_Movimiento - SET v.margen = sub.margen + v.importe + v.recargo - sub.pvp; - + + SET v.margen = sub.margen + v.importe + v.recargo - sub.pvp; SET vStartingDate = TIMESTAMPADD(DAY,1, vStartingDate); SET vEndingDate = util.dayEnd(vStartingDate); - END WHILE; @@ -6482,83 +6227,22 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ventas_add_launcher`() BEGIN + + /** + * Añade las ventas que se realizaron de hace + * una semana hasta hoy + * + **/ - call bs.ventas_add(timestampadd(week,-1,curdate()),curdate()); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ventas_add__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_add__`(IN datSTART DATETIME, IN datEND DATETIME) -BEGIN - - DECLARE vStartingDate DATETIME; - DECLARE vEndingDate DATETIME; - DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; - - SET datEND = util.dayEnd(datEND); - SET vStartingDate = GREATEST('2015-10-01',datSTART); - SET vEndingDate = vn2008.dayend(vStartingDate); - - DELETE - FROM ventas - WHERE fecha between vStartingDate and datEND; - - WHILE vEndingDate <= datEND DO - - REPLACE ventas(Id_Movimiento, importe, recargo, fecha, tipo_id, Id_Cliente, empresa_id) - SELECT Id_Movimiento, - SUM(IF(base, Cantidad * Valor, 0)) as importe, - SUM(IF(base, 0, Cantidad * Valor)) as recargo, - vStartingDate, - a.tipo_id, - cs.Id_Cliente, - t.empresa_id - FROM vn2008.Movimientos_componentes mc - JOIN bi.tarifa_componentes tc using(Id_Componente) - JOIN bi.tarifa_componentes_series tcs using(tarifa_componentes_series_id) - JOIN vn2008.Movimientos m using(Id_Movimiento) - JOIN vn2008.Articles a using(Id_Article) - JOIN vn2008.Tipos tp using(tipo_id) - JOIN vn2008.reinos r on r.id = tp.reino_id - JOIN vn2008.Tickets t using(Id_Ticket) - JOIN vn2008.Consignatarios cs using(Id_Consigna) - JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente - WHERE t.Fecha between vStartingDate and vEndingDate - AND datEND >= '2015-10-01' - AND c.typeFk IN ('Normal','handMaking','internalUse') - AND m.Cantidad <> 0 - AND a.tipo_id != TIPO_PATRIMONIAL - AND c.Id_Trabajador IS NOT NULL - AND m.Descuento <> 100 - AND (m.Id_Article = 98 or m.Id_Article = 95 or r.mercancia != 0) - GROUP BY mc.Id_Movimiento - HAVING IFNULL(importe,0) <> 0 OR IFNULL(recargo,0) <> 0; - - SET vStartingDate = TIMESTAMPADD(DAY,1, vStartingDate); - SET vEndingDate = util.dayEnd(vStartingDate); - - END WHILE; + CALL bs.ventas_add(timestampadd(week,-1,curdate()),curdate()); END ;; DELIMITER ; @@ -6570,13 +6254,155 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_add`(IN vYear INT, IN vMonth INT) +BEGIN + + /** + * Reemplaza las ventas contables del último año. + * Es el origen de datos para el balance de Entradas + * + * @param vYear Año a reemplazar + * @param vMonth Mes a reemplazar + * + **/ + + DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; + + DELETE FROM bs.ventas_contables + WHERE year = vYear + AND month = vMonth; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; + CREATE TEMPORARY TABLE tmp.ticket_list + (PRIMARY KEY (Id_Ticket)) + ENGINE = MEMORY + SELECT Id_Ticket + FROM vn2008.Tickets t + JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura + WHERE year(f.Fecha) = vYear + AND month(f.Fecha) = vMonth; + + INSERT INTO bs.ventas_contables(year + , month + , venta + , grupo + , reino_id + , tipo_id + , empresa_id + , gasto) + + SELECT vYear + , vMonth + , round(sum(Cantidad * Preu * (100 - m.Descuento)/100)) + , IF( + e.empresa_grupo = e2.empresa_grupo + ,1 + ,IF(e2.empresa_grupo,2,0) + ) as grupo + , tp.reino_id + , a.tipo_id + , t.empresa_id + , 7000000000 + + IF(e.empresa_grupo = e2.empresa_grupo + ,1 + ,IF(e2.empresa_grupo,2,0) + ) * 1000000 + + tp.reino_id * 10000 as Gasto + FROM vn2008.Movimientos m + JOIN vn2008.Tickets t on t.Id_Ticket = m.Id_Ticket + JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna + JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente + JOIN tmp.ticket_list tt on tt.Id_Ticket = t.Id_Ticket + JOIN vn2008.Articles a on m.Id_Article = a.Id_Article + JOIN vn2008.empresa e on e.id = t.empresa_id + LEFT JOIN vn2008.empresa e2 on e2.Id_Cliente = c.Id_Cliente + JOIN vn2008.Tipos tp on tp.tipo_id = a.tipo_id + WHERE Cantidad <> 0 + AND Preu <> 0 + AND m.Descuento <> 100 + AND a.tipo_id != TIPO_PATRIMONIAL + GROUP BY grupo, reino_id, tipo_id, empresa_id, Gasto; + + INSERT INTO bs.ventas_contables(year + , month + , venta + , grupo + , reino_id + , tipo_id + , empresa_id + , gasto) + SELECT vYear + , vMonth + , sum(ts.quantity * ts.price) + , IF( + c.companyGroupFk = c2.companyGroupFk + ,1 + ,IF(c2.companyGroupFk, 2, 0) + ) as grupo + , NULL + , NULL + , t.companyFk + , 7050000000 + FROM vn.ticketService ts + JOIN vn.ticket t ON ts.ticketFk = t.id + JOIN vn.address a on a.id = t.addressFk + JOIN vn.client cl on cl.id = a.clientFk + JOIN tmp.ticket_list tt on tt.Id_Ticket = t.id + JOIN vn.company c on c.id = t.companyFk + LEFT JOIN vn.company c2 on c2.clientFk = cl.id + GROUP BY grupo, t.companyFk ; + + DROP TEMPORARY TABLE tmp.ticket_list; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ventas_contables_add_launcher` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_add_launcher`() +BEGIN + + /** + * Reemplaza las ventas contables del último año. + * Es el origen de datos para el balance de Entradas + * + **/ + + CALL bs.ventas_contables_add(YEAR(TIMESTAMPADD(MONTH,-1,CURDATE())), MONTH(TIMESTAMPADD(MONTH,-1,CURDATE()))); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ventas_contables_add__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; /*!50003 SET character_set_client = utf8 */ ; /*!50003 SET character_set_results = utf8 */ ; /*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_add`(IN vYear INT, IN vMonth INT) +CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_add__`(IN vYear INT, IN vMonth INT) BEGIN /** * Reemplaza las ventas contables. Es el origen de datos para el balance de Entradas @@ -6646,27 +6472,6 @@ INSERT INTO bs.ventas_contables(year DROP TEMPORARY TABLE tmp.ticket_list; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ventas_contables_add_launcher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_add_launcher`() -BEGIN - - call bs.ventas_contables_add(YEAR(TIMESTAMPADD(MONTH,-1,CURDATE())), MONTH(TIMESTAMPADD(MONTH,-1,CURDATE()))); - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6677,52 +6482,55 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_por_cliente`(IN vYear INT, IN vMonth INT) BEGIN + + /** + * Muestra las ventas (€) de cada cliente + * dependiendo del año + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - -DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - -CREATE TEMPORARY TABLE tmp.ticket_list - (PRIMARY KEY (Id_Ticket)) - SELECT Id_Ticket - FROM vn2008.Tickets t - JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura - WHERE year(f.Fecha) = vYear - AND month(f.Fecha) = vMonth; - - - - SELECT vYear Año - , vMonth Mes - , t.Id_Cliente - , round(sum(Cantidad * Preu * (100 - m.Descuento)/100)) Venta - , if( - e.empresa_grupo = e2.empresa_grupo - ,1 - ,if(e2.empresa_grupo,2,0) - ) as grupo - , t.empresa_id empresa + CREATE TEMPORARY TABLE tmp.ticket_list + (PRIMARY KEY (Id_Ticket)) + SELECT Id_Ticket + FROM vn2008.Tickets t + JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura + WHERE year(f.Fecha) = vYear + AND month(f.Fecha) = vMonth; + + SELECT vYear Año, + vMonth Mes, + t.Id_Cliente, + round(sum(Cantidad * Preu * (100 - m.Descuento)/100)) Venta, + IF(e.empresa_grupo = e2.empresa_grupo, + 1, + IF(e2.empresa_grupo,2,0)) + AS grupo, + t.empresa_id empresa FROM vn2008.Movimientos m - JOIN vn2008.Tickets t on t.Id_Ticket = m.Id_Ticket - JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna - JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente - JOIN tmp.ticket_list tt on tt.Id_Ticket = t.Id_Ticket - JOIN vn2008.Articles a on m.Id_Article = a.Id_Article - JOIN vn2008.empresa e on e.id = t.empresa_id - LEFT JOIN vn2008.empresa e2 on e2.Id_Cliente = c.Id_Cliente - JOIN vn2008.Tipos tp on tp.tipo_id = a.tipo_id - WHERE Cantidad <> 0 + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna + JOIN vn2008.Clientes c ON c.Id_Cliente = cs.Id_Cliente + JOIN tmp.ticket_list tt ON tt.Id_Ticket = t.Id_Ticket + JOIN vn2008.Articles a ON m.Id_Article = a.Id_Article + JOIN vn2008.empresa e ON e.id = t.empresa_id + LEFT JOIN vn2008.empresa e2 ON e2.Id_Cliente = c.Id_Cliente + JOIN vn2008.Tipos tp ON tp.tipo_id = a.tipo_id + WHERE Cantidad <> 0 AND Preu <> 0 AND m.Descuento <> 100 AND a.tipo_id != 188 GROUP BY t.Id_Cliente, grupo,t.empresa_id; + + DROP TEMPORARY TABLE tmp.ticket_list; END ;; DELIMITER ; @@ -6734,52 +6542,71 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `vivosMuertos`() BEGIN + + /** + * Devuelve el número de clientes nuevos y muertos, + * dependiendo de la fecha actual. + * + * @param @datSTART Fecha de inicio a buscar + * @param @datEND Fecha de finalización a buscar + */ -SET @datSTART = TIMESTAMPADD(YEAR,-2,CURDATE()); -SET @datEND = TIMESTAMPADD(DAY,-DAY(CURDATE()),CURDATE()); + SET @datSTART = TIMESTAMPADD(YEAR,-2,CURDATE()); + SET @datEND = TIMESTAMPADD(DAY,-DAY(CURDATE()),CURDATE()); + + DROP TEMPORARY TABLE IF EXISTS tmp.VivosMuertos; + + CREATE TEMPORARY TABLE tmp.VivosMuertos + SELECT c.Id_Cliente, tm.yearMonth, f.Compra, 0 as Nuevo, 0 as Muerto + FROM vn2008.Clientes c + JOIN + (SELECT DISTINCT yearMonth + FROM vn2008.time + WHERE date BETWEEN @datSTART + AND @datEND ) tm + LEFT JOIN + (SELECT DISTINCT tm.yearMonth, f.Id_Cliente , 1 as Compra + FROM vn2008.Facturas f + JOIN vn2008.time tm ON tm.date = f.Fecha + WHERE Fecha BETWEEN @datSTART + AND @datEND) f ON f.yearMonth = tm.yearMonth + AND f.Id_Cliente = c.Id_Cliente; + + UPDATE tmp.VivosMuertos vm + JOIN + (SELECT MIN(tm.yearMonth) firstMonth, f.Id_Cliente + FROM vn2008.Facturas f + JOIN vn2008.time tm ON tm.date = f.Fecha + WHERE Fecha BETWEEN @datSTART AND @datEND + GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth + AND fm.Id_Cliente = vm.Id_Cliente -DROP TEMPORARY TABLE IF EXISTS tmp.VivosMuertos; + SET Nuevo = 1; + + SELECT max(yearMonth) INTO @lastYearMonth FROM tmp.VivosMuertos; + + UPDATE tmp.VivosMuertos vm + JOIN ( + SELECT MAX(tm.yearMonth) firstMonth, f.Id_Cliente + FROM vn2008.Facturas f + JOIN vn2008.time tm ON tm.date = f.Fecha + WHERE Fecha BETWEEN @datSTART AND @datEND + GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth + AND fm.Id_Cliente = vm.Id_Cliente -CREATE TEMPORARY TABLE tmp.VivosMuertos -SELECT c.Id_Cliente, tm.yearMonth, f.Compra, 0 as Nuevo, 0 as Muerto -FROM vn2008.Clientes c -JOIN (SELECT DISTINCT yearMonth FROM vn2008.time WHERE date BETWEEN @datSTART AND @datEND ) tm -LEFT JOIN - (SELECT DISTINCT tm.yearMonth, f.Id_Cliente , 1 as Compra - FROM vn2008.Facturas f - JOIN vn2008.time tm ON tm.date = f.Fecha - WHERE Fecha BETWEEN @datSTART AND @datEND) f ON f.yearMonth = tm.yearMonth AND f.Id_Cliente = c.Id_Cliente; - -UPDATE tmp.VivosMuertos vm -JOIN ( - SELECT MIN(tm.yearMonth) firstMonth, f.Id_Cliente - FROM vn2008.Facturas f - JOIN vn2008.time tm ON tm.date = f.Fecha - WHERE Fecha BETWEEN @datSTART AND @datEND - GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth AND fm.Id_Cliente = vm.Id_Cliente -SET Nuevo = 1; - -SELECT max(yearMonth) INTO @lastYearMonth FROM tmp.VivosMuertos; - -UPDATE tmp.VivosMuertos vm -JOIN ( - SELECT MAX(tm.yearMonth) firstMonth, f.Id_Cliente - FROM vn2008.Facturas f - JOIN vn2008.time tm ON tm.date = f.Fecha - WHERE Fecha BETWEEN @datSTART AND @datEND - GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth AND fm.Id_Cliente = vm.Id_Cliente -SET Muerto = 1 -WHERE yearMonth < @lastYearMonth; - - SELECT * FROM tmp.VivosMuertos; + SET Muerto = 1 + + WHERE yearMonth < @lastYearMonth; + + SELECT * FROM tmp.VivosMuertos; END ;; DELIMITER ; @@ -6875,121 +6702,6 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `weekWaste_byWorker__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `weekWaste_byWorker__`(IN vWorkerFk INT) -BEGIN - - DECLARE vWeek INT; - DECLARE vYear INT; - - SELECT week, year - INTO vWeek, vYear - FROM vn.time - WHERE dated = TIMESTAMPADD(WEEK, -1, CURDATE()); - - SELECT *, 100 * mermas / total AS porcentaje - FROM ( - SELECT ws.family, - SUM(ws.saleTotal) AS total, - SUM(ws.saleWaste) AS mermas - FROM bs.waste ws - JOIN vn.worker w ON w.user = ws.buyer - WHERE year = vYear - AND week = vWeek - AND w.id = vWorkerFk - GROUP BY family - ) sub - ORDER BY porcentaje DESC; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `weekWaste_getDetail__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `weekWaste_getDetail__`() -BEGIN - DECLARE vLastWeek DATE; - DECLARE vWeek INT; - DECLARE vYear INT; - - SET vLastWeek = TIMESTAMPADD(WEEK, -1, CURDATE()); - SET vYear = YEAR(vLastWeek); - SET vWeek = WEEK(vLastWeek, 1); - - SELECT *, 100 * dwindle / total AS percentage - FROM ( - SELECT buyer, - ws.family, - SUM(ws.saleTotal) AS total, - SUM(ws.saleWaste) AS dwindle - FROM bs.waste ws - WHERE year = vYear - AND week = vWeek - GROUP BY buyer, family - ) sub - ORDER BY percentage DESC; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `weekWaste__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `weekWaste__`() -BEGIN - DECLARE vWeek INT; - DECLARE vYear INT; - - SELECT week, year - INTO vWeek, vYear - FROM vn.time - WHERE dated = DATE_ADD(CURDATE(), INTERVAL -1 WEEK); - - SELECT *, 100 * dwindle / total AS percentage - FROM ( - SELECT buyer, - SUM(saleTotal) AS total, - SUM(saleWaste) AS dwindle - FROM bs.waste - WHERE year = vYear - AND week = vWeek - GROUP BY buyer - ) sub - ORDER BY percentage DESC; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `workerProductivity_add` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -7033,10 +6745,9 @@ BEGIN LEFT JOIN vn.workerDepartment wd ON wd.workerFk = st.workerFk LEFT JOIN vn.department d ON d.id = wd.departmentFk JOIN workerProductivityConfig w ON TRUE - WHERE t.shipped >= vDateFrom AND - ISNULL(sp.saleFk)AND - NOT IFNULL(d.name,'') LIKE 'EQUIPO%' AND - a.accion='SACAR' + WHERE t.shipped >= vDateFrom + AND ISNULL(sp.saleFk) + AND a.accion='SACAR' GROUP BY t.id, t.warehouseFk, st.workerFk ) sub JOIN account.role r ON r.name='itemPicker' @@ -7076,172 +6787,6 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `workerSpeed_detail__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `workerSpeed_detail__`(vWorkerCode VARCHAR(3), vAction VARCHAR(25)) -BEGIN - - SELECT * FROM - ( - SELECT time_format(st.created,'%H:%i') as hora, - t.warehouseFk as Almacen, - t.id as ticketFk, - floor(sum(s.quantity * r.cm3) / 1000) as Litros - - FROM vn.saleTracking st - JOIN vn.sale s ON s.id = st.saleFk - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN bi.rotacion r ON r.warehouse_id = t.warehouseFk AND r.Id_Article = s.itemFk - JOIN vn.worker w ON w.id = st.workerFk - JOIN vn.state e ON e.id = st.stateFk - JOIN vncontrol.accion a ON a.accion_id = st.actionFk - WHERE st.created > CURDATE() - AND a.accion LIKE vAction - AND w.code LIKE vWorkerCode - GROUP BY t.id) sub - ORDER BY hora; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `workerSpeed__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `workerSpeed__`() -BEGIN - - /* #UPDATED PAK 2019/09/02 - * #PENDING REVIEW - * - * - * - * - */ - - DECLARE vLastUpdated DATETIME; - DECLARE vSecondsDelay INT DEFAULT 300; - - SELECT IFNULL(MAX(lastUpdated),CURDATE()) INTO vLastUpdated - FROM bs.workerSpeed; - - IF TIMESTAMPDIFF(SECOND, vLastUpdated, NOW()) > vSecondsDelay THEN - - DELETE FROM bs.workerSpeed ; - -- WHERE lastUpdated < CURDATE(); - - -- Sacadores - REPLACE bs.workerSpeed - SELECT workerCode, - accion, - warehouseFk, - CAST(60 * sumaLitros / time_to_sec(timediff(finished, started)) AS DECIMAL(10,1)) as LitrosMinuto, - CAST(sumaLitrosLastHour / 60 AS DECIMAL(10,1)) as LitrosMinutoLastHour, - now() as lastUpdated - FROM - ( - SELECT warehouseFk, - accion, - workerCode, - sum(litros) as sumaLitros, - min(created) as started, - max(created) as finished, - sum(IF(created >= TIMESTAMPADD(HOUR, -1, NOW()),litros, 0)) as sumaLitrosLastHour - FROM - ( - SELECT t.warehouseFk, - st.saleFk, - st.isChecked, - st.originalQuantity, - a.accion, - st.created, - e.code, - w.firstname, - w.lastName, - w.code as workerCode, - r.cm3 * s.quantity / 1000 as litros, - s.concept - FROM vn.saleTracking st - LEFT JOIN - (SELECT saleFk - FROM vn.saleTracking st - JOIN vn.state e ON e.id = st.stateFk - WHERE st.created > CURDATE() - AND e.code LIKE 'PREVIOUS_PREPARATION') prevPrepSales ON prevPrepSales.saleFk = st.saleFk - JOIN vn.sale s ON s.id = st.saleFk - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN bi.rotacion r ON r.warehouse_id = t.warehouseFk AND r.Id_Article = s.itemFk - JOIN vn.worker w ON w.id = st.workerFk - JOIN vn.state e ON e.id = st.stateFk - JOIN vncontrol.accion a ON a.accion_id = st.actionFk - WHERE st.created > TIMESTAMPADD(HOUR,-1,NOW()) - AND prevPrepSales.saleFk IS NULL - ) sub - GROUP BY warehouseFk, accion, workerCode - ) sub2; - - -- Encajadores - REPLACE bs.workerSpeed - SELECT code as workerCode, - 'ENCAJAR' as accion, - warehouseFk, - CAST(60 * sum(Litros) / time_to_sec(timediff(MAX(finished), MIN(started))) AS DECIMAL(10,1)) as LitrosMinuto, - CAST(sum(litrosUltimaHora) / 60 AS DECIMAL(10,1)) as LitrosMinutoLastHour, - now() as lastUpdated - FROM ( - SELECT sv.ticketFk, - sum(sv.litros) as litros, - sum(IF(started > TIMESTAMPADD(HOUR,-1,NOW()),sv.litros,0)) as litrosUltimaHora, - code, - started, - finished, - cajas, - warehouseFk - FROM vn.saleVolume sv - JOIN - ( - SELECT ticketFk, - min(e.created) as started, - max(e.created) as finished, - max(counter) as cajas, - w.code, - t.warehouseFk - FROM vn.expedition e - JOIN vn.worker w ON w.id = e.workerFk - JOIN vn.ticket t ON t.id = e.ticketFk - WHERE e.created > CURDATE() - GROUP BY ticketFk - ) sub ON sub.ticketFk = sv.ticketFk - GROUP BY sv.ticketFk) sub2 - GROUP BY code; - - END IF; - - SELECT * FROM bs.workerSpeed; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `zone_ETD_byTime` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -8103,7 +7648,6 @@ proc: BEGIN IF v_calc IS NULL THEN - -- call util.debugAdd(concat('if start ', v_lock_id) ,v_refresh); INSERT INTO cache_calc SET cache_id = v_cache_id, cacheName = v_cache_name, @@ -8111,17 +7655,15 @@ proc: BEGIN last_refresh = NULL, expires = NULL, connection_id = CONNECTION_ID(); - -- call util.debugAdd(concat('if end ', v_lock_id),v_refresh); + SET v_calc = LAST_INSERT_ID(); ELSE - -- call util.debugAdd(concat('else start ', v_lock_id) ,v_refresh); UPDATE cache_calc SET last_refresh = NULL, expires = NULL, connection_id = CONNECTION_ID() WHERE id = v_calc; - -- call util.debugAdd(concat('else end ', v_lock_id) ,v_refresh); END IF; -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. @@ -8300,7 +7842,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `departure_timing_beta` */; +/*!50003 DROP PROCEDURE IF EXISTS `departure_timing_beta__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -8310,7 +7852,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `departure_timing_beta`(vWarehouseId INT) +CREATE DEFINER=`root`@`%` PROCEDURE `departure_timing_beta__`(vWarehouseId INT) BEGIN DECLARE done BOOL DEFAULT FALSE; @@ -8447,65 +7989,6 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `last_buy_refresh__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `last_buy_refresh__`(vRefresh BOOL) -proc: BEGIN -/** - * BERNAT: WORKING IN THIS FILE - * Crea o actualiza la cache con la última compra y fecha de cada - * artículo hasta ayer. Para obtener la última compra hasta una fecha - * determinada utilizar el procedimiento vn2008.item_last_buy_(). - * - * @param vRefresh %TRUE para forzar el recálculo de la cache - **/ - DECLARE vCalc INT; - DECLARE started DATE; - DECLARE ended DATE; - DECLARE vLastRefresh DATE; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - CALL cache_calc_unlock (vCalc); - RESIGNAL; - END; - - CALL cache_calc_start (vCalc, vRefresh, 'last_buy', NULL); - - IF !vRefresh - THEN - LEAVE proc; - END IF; - - -- TODO: ¿Se puede usar la fecha del ultimo inventario? - SET started = vn2008.date_inv();-- TIMESTAMPADD(DAY, -90, CURDATE()); - SET ended = CURDATE(); -- TIMESTAMPADD(DAY, -1, CURDATE()); - - CALL vn.buyUltimateFromInterval(NULL, started, ended); - - DELETE FROM last_buy; - - INSERT INTO last_buy (item_id, warehouse_id, buy_id, landing) - SELECT itemFk, warehouseFk, buyFk, landed - FROM tmp.buyUltimateFromInterval; - - DROP TEMPORARY TABLE tmp.buyUltimateFromInterval; - - CALL cache_calc_end (vCalc); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `prod_graphic_refresh` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -8885,6 +8368,9 @@ CREATE TABLE `VMPSettings` ( `closedTo` int(11) DEFAULT NULL, `totalRefreshHours` int(11) DEFAULT NULL COMMENT 'Numero > 4 para no saturar, no repetir para que no solapen las actualizaciones', `UseSupplierEmbalageCode` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'vmp you want to see their embalage code', + `firstSupplyResponseId` int(11) DEFAULT NULL, + `ApiId` int(11) DEFAULT NULL, + `ApiKey` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`VMPID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -8929,6 +8415,20 @@ CREATE TABLE `bucket_type` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/VBN020101/FB090916.txt'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `clientFHAdminNumber` +-- + +DROP TABLE IF EXISTS `clientFHAdminNumber`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `clientFHAdminNumber` ( + `fhAdminNumber` int(11) NOT NULL, + `clientFk` int(11) NOT NULL, + PRIMARY KEY (`clientFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `deliveryInformation` -- @@ -9170,6 +8670,18 @@ CREATE TABLE `fileConfig` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `floraHollandConfig` +-- + +DROP TABLE IF EXISTS `floraHollandConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `floraHollandConfig` ( + `defaultAdminNumber` int(11) NOT NULL DEFAULT '66011' +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `ftpConfig` -- @@ -9530,6 +9042,7 @@ CREATE TABLE `putOrder` ( `error` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `barcode` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL, `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `FHAdminNumber` int(11) DEFAULT '66011', PRIMARY KEY (`id`), UNIQUE KEY `orderTradelineItemID_UNIQUE` (`orderTradelineItemID`), KEY `deliveryInformationID_idx` (`deliveryInformationID`), @@ -9825,44 +9338,25 @@ CREATE TABLE `supplyResponse` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER supplyResponse_BU -BEFORE UPDATE -ON supplyResponse FOR EACH ROW -BEGIN - - - INSERT INTO edi.supplyResponseLog (supplyResponseFk, NumberOfUnitsOld, NumberOfUnitsNew, lastVMPUpdate) - SELECT OLD.ID, OLD.NumberOfUnits, NEW.NumberOfUnits, v.dateTimeLastSync - FROM edi.VMPSettings v - WHERE v.VMPID = OLD.vmpID; - -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER supplyResponse_AFTER_UPDATE AFTER UPDATE ON supplyResponse FOR EACH ROW BEGIN -/* - IF NEW.NumberOfUnits = 0 AND OLD.NumberOfUnits <> 0 AND NEW.MarketPlaceID = 8713783439043 THEN - INSERT INTO vn.mail(sender, `subject`, body) - VALUES( 'jgallego@verdnatura.es', - 'Cantidad a cero', - CONCAT('SupplyResponse: ', NEW.ID, ', Articulo: ' , NEW.VBNOmschrijving)); - END IF;*/ + + 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.agencyFk + 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.landed >= CURDATE(); + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10864,8 +10358,7 @@ proc: BEGIN numberOfItemsPerCask, embalageCode, quality, - isFloramondo, - inkFk) + isFloramondo) SELECT iti.itemFk, iti.product_name, iti.product_name, @@ -10878,11 +10371,9 @@ proc: BEGIN iti.NumberOfItemsPerCask, iti.EmbalageCode, iti.Quality, - TRUE, - ii.inkFk - FROM itemToInsert iti - LEFT JOIN vn.itemInk ii ON ii.longName = iti.product_name; - + TRUE + FROM itemToInsert iti; + INSERT IGNORE INTO vn.itemImageQueue(itemFk, url) SELECT i.id, PictureReference FROM itemToInsert ii @@ -10963,14 +10454,17 @@ proc: BEGIN JOIN vn.item i ON i.supplyResponseFk = ii.`srId` WHERE s6Value != ''; - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, ink.name, 11 + 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' - JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode - JOIN edi.`type` tp ON tp.type_id = f.feature_type_id AND tp.`description` = 'Hoofdkleur 1' - JOIN vn.ink ON ink.dutchCode = f.feature_value; + 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; UPDATE vn.item i JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId` @@ -11167,6 +10661,66 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `orderLog` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `orderLog`(vItemFk INT) +BEGIN + + DECLARE vSupplyResponseFk INT; + DECLARE vDescription VARCHAR(100); + + SELECT supplyResponseFk, CONCAT(id, ' ',longName) INTO vSupplyResponseFk, vDescription + FROM vn.item + WHERE id = vItemFk; + + SELECT * FROM + ( + SELECT 'Cliente confirma' accion, or2.created hora, amount Cantidad + FROM hedera.order_row or2 + JOIN vn.item i ON i.id = or2.item_id + WHERE i.supplyResponseFk = vSupplyResponseFk + + UNION ALL + + SELECT vDescription, NULL, NULL + + UNION ALL + + SELECT 'Cliente se conecta' , o.date_make , NULL + FROM hedera.`order` o + JOIN hedera.order_row or2 ON or2.order_id = o.id + JOIN vn.item i ON i.id = or2.item_id + WHERE i.supplyResponseFk = vSupplyResponseFk + + UNION ALL + + SELECT DISTINCT 'Subasta cambia cantidad', srl.created, srl.NumberOfUnitsNew * sr.NumberOfItemsPerCask + FROM edi.supplyResponseLog srl + JOIN edi.supplyResponse sr ON sr.ID = srl.supplyResponseFk + WHERE srl.supplyResponseFk = vSupplyResponseFk + + UNION ALL + + SELECT 'Linea de venta definitiva', s.created, s.quantity + FROM vn.sale s + JOIN vn.item i ON i.id = s.itemFk + WHERE i.supplyResponseFk = vSupplyResponseFk) sub + ORDER BY hora; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; -- -- Current Database: `hedera` @@ -12011,6 +11565,34 @@ CREATE TABLE `order` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER order_afterInsert +AFTER INSERT +ON `order` FOR EACH ROW +BEGIN + IF NEW.address_id = 2850 THEN + -- Fallo que se insertan no se sabe como tickets en este cliente + INSERT INTO vn.mail SET + `sender` = 'jgallego@verdnatura.es', + `replyTo` = 'jgallego@verdnatura.es', + `subject` = 'Creada order al address 2850', + `body` = CONCAT(account.myUserGetName(), ' ha creado la order ', + NEW.id); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `hedera`.`order_afterUpdate` AFTER UPDATE ON `order` FOR EACH ROW @@ -12058,7 +11640,7 @@ DROP TABLE IF EXISTS `orderConfig`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `orderConfig` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `employeeFk` int(11) NOT NULL, + `employeeFk` int(10) unsigned NOT NULL, `defaultAgencyFk` int(11) DEFAULT NULL, `guestMethod` varchar(45) CHARACTER SET utf8 NOT NULL, `guestAgencyFk` int(11) NOT NULL, @@ -12425,7 +12007,7 @@ CREATE TABLE `tpvConfig` ( `terminal` tinyint(3) unsigned NOT NULL, `transactionType` tinyint(3) unsigned NOT NULL, `maxAmount` int(10) unsigned DEFAULT NULL, - `employeeFk` int(10) NOT NULL, + `employeeFk` int(10) unsigned NOT NULL, `url` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'The bank web service URL for production environment', `testMode` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT 'Whether test mode is enabled', `testUrl` varchar(255) CHARACTER SET utf8 DEFAULT NULL COMMENT 'The bank web service URL for test environment', @@ -13111,6 +12693,142 @@ CREATE DEFINER=`root`@`%` PROCEDURE `item_getVisible`( vType INT, vPrefix VARCHAR(255)) BEGIN + +/** + * Gets visible items of the specified type at specified date. + * + * @param vWarehouse The warehouse id + * @param vDate The visible date + * @param vType The type id + * @param vPrefix The article prefix to filter or %NULL for all + * @return tmp.itemVisible Visible items + */ + DECLARE vPrefixLen SMALLINT; + DECLARE vFilter VARCHAR(255) DEFAULT NULL; + DECLARE vDateInv DATE DEFAULT vn2008.date_inv(); + DECLARE EXIT HANDLER FOR 1114 + BEGIN + GET DIAGNOSTICS CONDITION 1 + @message = MESSAGE_TEXT; + CALL vn.mail_insert( + 'cau@verdnatura.es', + NULL, + CONCAT('hedera.item_getVisible error: ', @message), + CONCAT( + 'warehouse: ', IFNULL(vWarehouse, ''), + ', Fecha:', IFNULL(vDate, ''), + ', tipo: ', IFNULL(vType,''), + ', prefijo: ', IFNULL(vPrefix,''))); + RESIGNAL; + END; + SET vPrefixLen = IFNULL(LENGTH(vPrefix), 0) + 1; + + IF vPrefixLen > 1 THEN + SET vFilter = CONCAT(vPrefix, '%'); + END IF; + + DROP TEMPORARY TABLE IF EXISTS `filter`; + CREATE TEMPORARY TABLE `filter` + (INDEX (itemFk)) + ENGINE = MEMORY + SELECT id itemFk FROM vn.item + WHERE typeFk = vType + AND (vFilter IS NULL OR `name` LIKE vFilter); + + DROP TEMPORARY TABLE IF EXISTS currentStock; + CREATE TEMPORARY TABLE currentStock + (INDEX (itemFk)) + ENGINE = MEMORY + SELECT itemFk, SUM(quantity) quantity + FROM ( + SELECT b.itemFk, b.quantity + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel t ON t.id = e.travelFk + WHERE t.landed BETWEEN vDateInv AND vDate + AND t.warehouseInFk = vWarehouse + AND NOT e.isRaid + UNION ALL + SELECT b.itemFk, -b.quantity + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel t ON t.id = e.travelFk + WHERE t.shipped BETWEEN vDateInv AND CURDATE() + AND t.warehouseOutFk = vWarehouse + AND NOT e.isRaid + AND t.isDelivered + UNION ALL + SELECT m.itemFk, -m.quantity + FROM vn.sale m + JOIN vn.ticket t ON t.id = m.ticketFk + JOIN vn.ticketState s ON s.ticket = t.id + WHERE t.shipped BETWEEN vDateInv AND CURDATE() + AND t.warehouseFk = vWarehouse + AND s.alertLevel = 3 + ) t + GROUP BY itemFk + HAVING quantity > 0; + + DROP TEMPORARY TABLE IF EXISTS tmp; + CREATE TEMPORARY TABLE tmp + (INDEX (itemFk)) + ENGINE = MEMORY + SELECT * + FROM ( + SELECT b.itemFk, b.packageFk, b.packing + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel t ON t.id = e.travelFk + WHERE t.landed BETWEEN vDateInv AND vDate + AND NOT b.isIgnored + AND b.price2 >= 0 + AND b.packageFk IS NOT NULL + ORDER BY t.warehouseInFk = vWarehouse DESC, t.landed DESC + ) t GROUP BY itemFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.itemVisible; + CREATE TEMPORARY TABLE tmp.itemVisible + ENGINE = MEMORY + SELECT i.id Id_Article, + SUBSTRING(i.`name`, vPrefixLen) Article, + t.packing, p.id Id_Cubo, + IF(p.depth > 0, p.depth, 0) depth, p.width, p.height, + CEIL(s.quantity / t.packing) etiquetas + FROM vn.item i + JOIN `filter` f ON f.itemFk = i.id + JOIN currentStock s ON s.itemFk = i.id + LEFT JOIN tmp t ON t.itemFk = i.id + LEFT JOIN vn.packaging p ON p.id = t.packageFk + WHERE CEIL(s.quantity / t.packing) > 0 + -- FIXME: Column Cubos.box not included in view vn.packaging + /* AND p.box */; + + DROP TEMPORARY TABLE + `filter`, + currentStock, + tmp; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `item_getVisible__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `item_getVisible__`( + vWarehouse TINYINT, + vDate DATE, + vType INT, + vPrefix VARCHAR(255)) +BEGIN /** * Gets visible items of the specified type at specified date. * @@ -14750,29 +14468,24 @@ BEGIN SET available = GREATEST(0,available - vAmount) WHERE item_id = vItem AND calc_id = vCalc; - /* - CALL util.debugAdd('vShipment vWarehouse vOrder vClient vAmount vItem availableNoRaids', - CONCAT( vShipment,' ', - vWarehouse,' ', - vOrder,' ', - vClientId,' ', - vAmount,' ', - vItem, ' ', - @available)); - */ + INSERT INTO edi.putOrder (deliveryInformationID, supplyResponseId, quantity , EndUserPartyId, - EndUserPartyGLN) + EndUserPartyGLN, + FHAdminNumber) SELECT di.ID, i.supplyResponseFk, CEIL((vAmount - @available)/ sr.NumberOfItemsPerCask ), FALSE, - vClientId + vClientId, + IFNULL(ca.fhAdminNumber, fhc.defaultAdminNumber) FROM edi.deliveryInformation di JOIN vn.item i ON i.supplyResponseFk = di.supplyResponseID JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + LEFT JOIN edi.clientFHAdminNumber ca ON ca.clientFk = vClientId + JOIN edi.floraHollandConfig fhc WHERE i.id = vItem AND di.LatestOrderDateTime > NOW() AND vAmount > @available @@ -15731,7 +15444,7 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `tpvTransaction_undo` */; -ALTER DATABASE `hedera` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `hedera` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -15825,7 +15538,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `hedera` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `hedera` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 DROP PROCEDURE IF EXISTS `visitUser_new` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -17400,7 +17113,7 @@ DROP TABLE IF EXISTS `business_labour`; CREATE TABLE `business_labour` ( `business_id` int(11) NOT NULL, `notes` longtext, - `department_id` int(11) DEFAULT '2', + `department_id` int(11) NOT NULL, `professional_category_id` int(11) DEFAULT '0', `incentivo` double DEFAULT '0', `calendar_labour_type_id` int(11) DEFAULT '1', @@ -17414,7 +17127,7 @@ CREATE TABLE `business_labour` ( KEY `business_labour_department_idx` (`department_id`), CONSTRAINT `bus_restriction` FOREIGN KEY (`business_id`) REFERENCES `business` (`business_id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `business_labour_agreement` FOREIGN KEY (`labour_agreement_id`) REFERENCES `labour_agreement` (`labour_agreement_id`) ON UPDATE CASCADE, - CONSTRAINT `business_labour_department` FOREIGN KEY (`department_id`) REFERENCES `vn`.`department` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `business_labour_department_id` FOREIGN KEY (`department_id`) REFERENCES `vn`.`department` (`id`) ON UPDATE CASCADE, CONSTRAINT `horario_tipo` FOREIGN KEY (`calendar_labour_type_id`) REFERENCES `calendar_labour_type` (`calendar_labour_type_id`) ON UPDATE CASCADE, CONSTRAINT `workcenter_labour` FOREIGN KEY (`workcenter_id`) REFERENCES `workcenter` (`workcenter_id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; @@ -17743,7 +17456,7 @@ CREATE TABLE `person` ( `firstname` varchar(20) DEFAULT NULL, `p2` longtext, `nis` int(11) DEFAULT NULL, - `id_trabajador` int(11) DEFAULT NULL, + `id_trabajador` int(10) unsigned DEFAULT NULL, `isDisable` smallint(6) NOT NULL DEFAULT '0', `isFreelance` smallint(6) NOT NULL DEFAULT '0' COMMENT 'M Male\nF Female', `isSsDiscounted` smallint(6) NOT NULL DEFAULT '0', @@ -17919,13 +17632,13 @@ CREATE TABLE `workcenter` ( /*!40101 SET character_set_client = @saved_cs_client */; -- --- Table structure for table `workerTimeControlConfig` +-- Table structure for table `workerTimeControlConfig__` -- -DROP TABLE IF EXISTS `workerTimeControlConfig`; +DROP TABLE IF EXISTS `workerTimeControlConfig__`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `workerTimeControlConfig` ( +CREATE TABLE `workerTimeControlConfig__` ( `id` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `warehouseFk` smallint(6) unsigned NOT NULL, PRIMARY KEY (`id`), @@ -18455,8 +18168,7 @@ TRUNCATE TABLE clientesProveedores; IF (sn.SiglaNacion = "XB",IF(sp.CodigoProvincia IN (51,52), 22, IF (sp.CodigoProvincia IN (35,38), 21, sn.CodigoNacion)), sn.CodigoNacion) CodigoNacion, IF (sn.SiglaNacion = "XB",IF(sp.CodigoProvincia IN (51,52), "XC",IF (sp.CodigoProvincia IN (35,38), "XB", sn.SiglaNacion)), sn.SiglaNacion) SiglaNacion, IF((cl.fi REGEXP '^([[:blank:]]|[[:digit:]])'), 'J','F') PersonaFisicaJuridica, - IF((co.id = 1 OR co.id = 30) OR (co.isUeeMember = 1 AND NOT cl.isVies) , 1, - IF((co.isUeeMember = 1 AND cl.isVies), 2, 4)) TipoDocumentoPersona, + IF((co.id = 1 OR co.id = 30), 1, IF((co.isUeeMember = 1 AND cl.isVies), 2, 4)) TipoDocumentoPersona, -- IF(cl.isEqualizated, 'R', IF ((cl.isVies AND cl.countryFk <> 1) OR (NOT co.isUeeMember),'E','I'))AS CodigoIva, cl.taxTypeSageFk CodigoIva, IF(sn.SiglaNacion = "XB", IF(sp.CodigoProvincia IN (51,52), "CEUTA Y MELILLA", IF (sp.CodigoProvincia IN (35,38), "ISLAS CANARIAS",sn.Nacion)) , sn.Nacion) Nacion, @@ -20205,7 +19917,8 @@ BEGIN JOIN TiposIva t ON t.CodigoIva = it.taxTypeSageFk JOIN TiposTransacciones tt ON tt.CodigoTransaccion = it.transactionTypeSageFk LEFT JOIN tmp.invoiceDua id ON id.id = vXDiarioId - WHERE i.id = vInvoiceInFk AND i.id> 70000; -- los DUAS no son vInvoiceInFk, pero se pasan en el mismo parametro comparten id en tablas distintas de InvoiceIN (100000) dua(20000) + WHERE i.id = vInvoiceInFk + AND i.id> 70000; -- los DUAS no son vInvoiceInFk, pero se pasan en el mismo parametro comparten id en tablas distintas de InvoiceIN (100000) dua(20000) DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; @@ -20278,7 +19991,7 @@ BEGIN CodigoIva4 = vTaxCode WHERE id = vXDiarioId; ELSE - SELECT vXDiarioId; + SELECT vXDiarioId INTO vXDiarioId; END CASE; IF vIsIntracommunity THEN @@ -20325,41 +20038,31 @@ BEGIN xmi.FechaOperacion = ii.issued, xmi.MantenerAsiento = TRUE, xmi.SuFacturaNo = ii.supplierRef, - xmi.IvaDeducible1 = IF(id.id,FALSE,IF(IFNULL(xmi.BaseIva1,FALSE),FALSE,ii.isVatDeductible)), - xmi.IvaDeducible1 = IF(id.id,FALSE,IF(IFNULL(xmi.BaseIva2,FALSE),FALSE,ii.isVatDeductible)), - xmi.IvaDeducible1 = IF(id.id,FALSE,IF(IFNULL(xmi.BaseIva3,FALSE),FALSE,ii.isVatDeductible)), - xmi.IvaDeducible1 = IF(id.id,FALSE,IF(IFNULL(xmi.BaseIva4,FALSE),FALSE,ii.isVatDeductible)), + xmi.IvaDeducible1 = IF(id.id, FALSE, IF(IFNULL(xmi.BaseIva1, FALSE) = FALSE, FALSE, ii.isVatDeductible)), + xmi.IvaDeducible2 = IF(id.id, FALSE, IF(IFNULL(xmi.BaseIva2, FALSE) = FALSE, FALSE, ii.isVatDeductible)), + xmi.IvaDeducible3 = IF(id.id, FALSE, IF(IFNULL(xmi.BaseIva3, FALSE) = FALSE, FALSE, ii.isVatDeductible)), + xmi.IvaDeducible4 = IF(id.id, FALSE, IF(IFNULL(xmi.BaseIva4, FALSE) = FALSE, FALSE, ii.isVatDeductible)), xmi.FechaFacturaOriginal = x.FECHA_EX WHERE xmi.id = vXDiarioId; -- RETENCIONES - /* UPDATE XDiario_movConta_IVA xmi - JOIN vn.invoiceIn ii ON ii.id = vInvoiceInFk - JOIN vn2008.XDiario x ON x.id = xmi.id - JOIN vn.supplier s ON s.id = supplierFk - JOIN vn.invoiceInTax iit ON iit.invoiceInFk = ii.id - JOIN TiposRetencion t ON t.CodigoRetencion = ii.withholdingSageFk - SET xmi.CodigoRetencion = t.CodigoRetencion, - xmi.BaseRetencion = iit.taxableBase, - xmi.PorRetencion = t.PorcentajeRetencion, - xmi.ImporteRetencion = iit.taxableBase * (t.PorcentajeRetencion / 100) - WHERE xmi.id = vXDiarioId AND iit.taxableBase < 0 ;*/ UPDATE XDiario_movConta_IVA xmi - JOIN vn.invoiceIn ii ON ii.id = vInvoiceInFk - JOIN vn2008.XDiario x ON x.id = xmi.id - JOIN vn.supplier s ON s.id = supplierFk - JOIN vn.invoiceInTax iit ON iit.invoiceInFk = ii.id - JOIN TiposRetencion t ON t.CodigoRetencion = ii.withholdingSageFk - JOIN (SELECT SUM(BASEEURO) taxableBase, SUM(EURODEBE) taxBase - FROM vn.XDiario - WHERE BASEEURO <> 0 AND ASIEN = (SELECT ASIEN FROM vn.XDiario WHERE id = vXDiarioId) - )sub - SET xmi.CodigoRetencion = t.CodigoRetencion, - xmi.BaseRetencion = IF (t.CodigoRetencion = 2, sub.taxableBase + sub.taxBase, sub.taxableBase), - xmi.PorRetencion = t.PorcentajeRetencion, - xmi.ImporteRetencion = iit.taxableBase * - 1 - WHERE xmi.id = vXDiarioId AND iit.expenceFk= 4751000000 ; + JOIN vn.invoiceIn ii ON ii.id = vInvoiceInFk + JOIN vn2008.XDiario x ON x.id = xmi.id + JOIN vn.supplier s ON s.id = supplierFk + JOIN vn.invoiceInTax iit ON iit.invoiceInFk = ii.id + JOIN TiposRetencion t ON t.CodigoRetencion = ii.withholdingSageFk + JOIN (SELECT SUM(BASEEURO) taxableBase, SUM(EURODEBE) taxBase + FROM vn.XDiario + WHERE BASEEURO <> 0 AND ASIEN = (SELECT ASIEN FROM vn.XDiario WHERE id = vXDiarioId) + )sub + SET xmi.CodigoRetencion = t.CodigoRetencion, + xmi.ClaveOperacionFactura = IF( t.Retencion = 'ARRENDAMIENTO Y SUBARRENDAMIENTO', 'R', xmi.ClaveOperacionFactura), + xmi.BaseRetencion = IF (t.CodigoRetencion = 2, sub.taxableBase + sub.taxBase, sub.taxableBase), + xmi.PorRetencion = t.PorcentajeRetencion, + xmi.ImporteRetencion = iit.taxableBase * - 1 + WHERE xmi.id = vXDiarioId AND iit.expenceFk = 4751000000; END ;; DELIMITER ; @@ -20744,7 +20447,7 @@ BEGIN FROM vn2008.XDiario x LEFT JOIN vn.invoiceIn ii ON x.CLAVE = ii.id LEFT JOIN vn.invoiceInTax it ON it.invoiceInFk = ii.id - WHERE it.taxTypeSageFk IS NOT NULL AND + WHERE(it.taxTypeSageFk IS NOT NULL OR x.SERIE='D') AND x.enlazadoSage = FALSE AND x.FECHA >= vDated ) sub ON sub.ASIEN =x.ASIEN -- Elimina las Facturas con IVA 0 (-) no se trasladan a sage @@ -20774,7 +20477,7 @@ BEGIN i.serial serial, i.supplierFk supplierFk, i.issued issued, - i.isVatDeductible isVatDeductible, + IF(expenceFkDeductible, FALSE, i.isVatDeductible) isVatDeductible, i.serialNumber serialNumber, IF(c.code = "EUR", '',c.code) currencyFk FROM vn.invoiceIn i @@ -22216,7 +21919,7 @@ CREATE TABLE `inbound` ( KEY `isSync` (`isSync`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -ALTER DATABASE `stock` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `stock` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -22244,7 +21947,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `stock` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `stock` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -22341,7 +22044,7 @@ CREATE TABLE `outbound` ( KEY `isSync` (`isSync`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -ALTER DATABASE `stock` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `stock` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -22370,7 +22073,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `stock` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `stock` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -23458,7 +23161,7 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `visible_log` */; -ALTER DATABASE `stock` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `stock` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -23491,7 +23194,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `stock` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `stock` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; -- -- Current Database: `util` @@ -23878,7 +23581,7 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP FUNCTION IF EXISTS `nextWeek` */; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `util` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -23909,7 +23612,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `util` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 DROP FUNCTION IF EXISTS `quarterFirstDay` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -23967,7 +23670,7 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP FUNCTION IF EXISTS `today` */; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `util` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -23994,7 +23697,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `util` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 DROP FUNCTION IF EXISTS `tomorrow` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -24021,7 +23724,7 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP FUNCTION IF EXISTS `twoDaysAgo` */; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `util` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -24046,9 +23749,9 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `util` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 DROP FUNCTION IF EXISTS `yearRelativePosition` */; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `util` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -24089,9 +23792,9 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `util` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 DROP FUNCTION IF EXISTS `yesterday` */; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `util` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -24116,7 +23819,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `util` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 DROP PROCEDURE IF EXISTS `compareObjects` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -24234,7 +23937,7 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `debugAdd` */; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `util` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -24267,7 +23970,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `util` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 DROP PROCEDURE IF EXISTS `exec` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -24565,13 +24268,13 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `throw`(vMessage CHAR(35)) +CREATE DEFINER=`root`@`%` PROCEDURE `throw`(vMessage CHAR(55)) BEGIN /** * Throws a user-defined exception. @@ -24837,7 +24540,8 @@ CREATE TABLE `accountingType` ( `receiptDescription` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Descripción por defecto al crear nuevo recibo', `code` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, `isAutoConciliated` tinyint(1) DEFAULT '1' COMMENT 'Si hay que marcar como conciliado el recibo al usar este tipo', - PRIMARY KEY (`id`) + PRIMARY KEY (`id`), + KEY `accountingType_code_IDX` (`code`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='descripcio dels valors de la columna "cash" de la taula vn2008.Bancios'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -24937,8 +24641,13 @@ DELIMITER ;; BEGIN DECLARE vIsEqualizated BOOL; - CALL pbx.phone_isValid(NEW.phone); - CALL pbx.phone_isValid(NEW.mobile); + IF (NEW.phone <> '') THEN + CALL pbx.phone_isValid(NEW.phone); + END IF; + + IF (NEW.mobile <> '') THEN + CALL pbx.phone_isValid(NEW.mobile); + END IF; IF NEW.isEqualizated IS NULL THEN SELECT isEqualizated @@ -24966,8 +24675,15 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`address_beforeUpdate` BEFORE UPDATE ON `vn`.`address` FOR EACH ROW BEGIN - CALL pbx.phone_isValid(NEW.phone); - CALL pbx.phone_isValid(NEW.mobile); + + IF !(NEW.phone <=> OLD.phone) AND (NEW.phone <> '') THEN + CALL pbx.phone_isValid(NEW.phone); + END IF; + + IF !(NEW.mobile <=> OLD.mobile) AND (NEW.mobile <> '')THEN + CALL pbx.phone_isValid(NEW.mobile); + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -25189,8 +24905,8 @@ CREATE TABLE `agencyTerm` ( `packagePrice` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT 'precio extra por bulto', `routePrice` decimal(10,2) DEFAULT NULL COMMENT 'precio fijo por ruta', `minimumKm` int(11) NOT NULL DEFAULT '0', - `minimumM3` decimal(10,0) DEFAULT NULL, - `m3Price` decimal(10,0) DEFAULT NULL, + `minimumM3` decimal(10,2) NOT NULL DEFAULT '0.00', + `m3Price` decimal(10,0) NOT NULL DEFAULT '0', PRIMARY KEY (`agencyFk`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -25204,9 +24920,9 @@ DROP TABLE IF EXISTS `alertLevel`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `alertLevel` ( `code` varchar(45) CHARACTER SET utf8 NOT NULL, + `id` int(11) NOT NULL, `alertLevel` int(11) NOT NULL, - PRIMARY KEY (`code`), - CONSTRAINT `fk_code_1` FOREIGN KEY (`code`) REFERENCES `state` (`code`) ON DELETE CASCADE ON UPDATE CASCADE + PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -25294,13 +25010,13 @@ CREATE TABLE `autoRadioLogCall` ( /*!40101 SET character_set_client = @saved_cs_client */; -- --- Table structure for table `autonomousRegion` +-- Table structure for table `autonomousRegion__` -- -DROP TABLE IF EXISTS `autonomousRegion`; +DROP TABLE IF EXISTS `autonomousRegion__`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `autonomousRegion` ( +CREATE TABLE `autonomousRegion__` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) CHARACTER SET utf8 NOT NULL, `geoFk` int(11) DEFAULT NULL, @@ -25311,6 +25027,96 @@ CREATE TABLE `autonomousRegion` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `autonomy` +-- + +DROP TABLE IF EXISTS `autonomy`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `autonomy` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, + `countryFk` mediumint(8) unsigned NOT NULL, + `geoFk` int(11) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `autonomy_FK` (`countryFk`), + KEY `autonomy_FK_1` (`geoFk`), + CONSTRAINT `autonomy_FK` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `autonomy_FK_1` FOREIGN KEY (`geoFk`) REFERENCES `zoneGeo` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Comunidades autónomas o su equivalente en otros paises. Agrupación de provincias, en una categoria inferior a country.'; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER autonomy_BI +BEFORE INSERT +ON autonomy FOR EACH ROW +BEGIN + + SET NEW.geoFk = zoneGeo_new('autonomy', NEW.`name`, (SELECT geoFk FROM country WHERE id = NEW.countryFk)); + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER autonomy_BU +BEFORE UPDATE +ON autonomy FOR EACH ROW +BEGIN + IF !(OLD.countryFk <=> NEW.countryFk) THEN + CALL zoneGeo_setParent(NEW.geoFk, + (SELECT geoFk FROM country WHERE id = NEW.countryFk)); + END IF; + + IF !(OLD.`name` <=> NEW.`name`) THEN + UPDATE zoneGeo SET `name` = NEW.`name` + WHERE id = NEW.geoFk; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER autonomy_AD +AFTER DELETE +ON autonomy FOR EACH ROW +BEGIN + CALL zoneGeo_delete(OLD.geoFk); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + -- -- Table structure for table `awb` -- @@ -25324,7 +25130,7 @@ CREATE TABLE `awb` ( `package` float unsigned NOT NULL, `weight` float unsigned DEFAULT NULL, `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `transitoryFk` int(11) NOT NULL DEFAULT '582', + `transitoryFk` int(11) DEFAULT NULL, `taxFk` int(10) unsigned DEFAULT '62', `duakk` varchar(18) COLLATE utf8_unicode_ci DEFAULT NULL, `docFk` int(11) DEFAULT NULL, @@ -25483,6 +25289,37 @@ CREATE TABLE `bankEntity` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Entidades bancarias '; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Temporary table structure for view `bankPolicy` +-- + +DROP TABLE IF EXISTS `bankPolicy`; +/*!50001 DROP VIEW IF EXISTS `bankPolicy`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE TABLE `bankPolicy` ( + `id` tinyint NOT NULL, + `ref` tinyint NOT NULL, + `amount` tinyint NOT NULL, + `balanceInterestDrawn` tinyint NOT NULL, + `commissionAvailableBalances` tinyint NOT NULL, + `openingCommission` tinyint NOT NULL, + `started` tinyint NOT NULL, + `ended` tinyint NOT NULL, + `bankFk` tinyint NOT NULL, + `companyFk` tinyint NOT NULL, + `supplierFk` tinyint NOT NULL, + `description` tinyint NOT NULL, + `hasGuarantee` tinyint NOT NULL, + `dmsFk` tinyint NOT NULL, + `notaryFk` tinyint NOT NULL, + `currencyFk` tinyint NOT NULL, + `amortizationTypeFk` tinyint NOT NULL, + `periodicityTypeFk` tinyint NOT NULL, + `insuranceExpired` tinyint NOT NULL +) ENGINE=MyISAM */; +SET character_set_client = @saved_cs_client; + -- -- Table structure for table `beach` -- @@ -25496,6 +25333,7 @@ CREATE TABLE `beach` ( `x` int(11) NOT NULL, `y` int(11) NOT NULL, `name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `isShowed` tinyint(1) DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Ubicaciones respecto a la playa del almacén'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -25618,6 +25456,20 @@ CREATE TABLE `businessReasonEnd` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `businessType` +-- + +DROP TABLE IF EXISTS `businessType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `businessType` ( + `code` varchar(100) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `description` varchar(100) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `buy` -- @@ -25953,6 +25805,7 @@ CREATE TABLE `calendar` ( KEY `calendar_employee_business_labour_id_idx` (`businessFk`), KEY `calendar_employee_calendar_state_calendar_state_id_idx` (`dayOffTypeFk`), KEY `id_index` (`id`), + CONSTRAINT `calendar_businessFk` FOREIGN KEY (`businessFk`) REFERENCES `postgresql`.`business` (`business_id`) ON UPDATE CASCADE, CONSTRAINT `calendar_employee_state_id` FOREIGN KEY (`dayOffTypeFk`) REFERENCES `postgresql`.`calendar_state` (`calendar_state_id`) ON DELETE NO ACTION ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; @@ -26069,7 +25922,10 @@ CREATE TABLE `chain` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `rappel` decimal(5,2) NOT NULL DEFAULT '0.00', - PRIMARY KEY (`id`) + `componentFk` int(11) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `chain_FK` (`componentFk`), + CONSTRAINT `chain_FK` FOREIGN KEY (`componentFk`) REFERENCES `component` (`id`) ON DELETE SET NULL ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Grupos de clientes'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -26201,7 +26057,7 @@ CREATE TABLE `claimDevelopment` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `claimFk` int(10) unsigned NOT NULL, `claimResponsibleFk` int(10) unsigned NOT NULL DEFAULT '1', - `workerFk` int(11) DEFAULT NULL, + `workerFk` int(10) unsigned DEFAULT NULL, `claimReasonFk` int(10) unsigned NOT NULL DEFAULT '1', `claimResultFk` int(10) unsigned NOT NULL DEFAULT '1', `claimRedeliveryFk` tinyint(3) unsigned NOT NULL DEFAULT '1', @@ -26252,7 +26108,7 @@ CREATE TABLE `claimEnd` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `saleFk` int(11) DEFAULT NULL, `claimFk` int(10) unsigned NOT NULL, - `workerFk` int(11) NOT NULL DEFAULT '20', + `workerFk` int(10) unsigned NOT NULL DEFAULT '20', `claimDestinationFk` tinyint(4) DEFAULT NULL, `isGreuge` tinyint(4) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), @@ -26422,7 +26278,7 @@ CREATE TABLE `client` ( `street` longtext COLLATE utf8_unicode_ci, `fi` varchar(14) COLLATE utf8_unicode_ci DEFAULT NULL, `phone` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, - `fax` varchar(11) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'obsoleta (comprobar)', + `fax__` varchar(11) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'obsoleta (comprobar)', `email` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `cc` varchar(23) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'obsoleta (comprobar)', `dueDay` smallint(6) NOT NULL DEFAULT '5', @@ -26445,7 +26301,7 @@ CREATE TABLE `client` ( `invoiceCopy__` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'obsoleta (comprobar)', `hold` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'obsoleta (comprobar)', `isFreezed` tinyint(1) NOT NULL DEFAULT '0', - `salesPersonFk` int(11) DEFAULT NULL, + `salesPersonFk` int(10) unsigned DEFAULT NULL, `credit` decimal(10,2) NOT NULL DEFAULT '0.00', `cyc` double DEFAULT NULL COMMENT 'obsoleta (comprobar)', `countryFk` mediumint(8) unsigned NOT NULL DEFAULT '1', @@ -26472,7 +26328,7 @@ CREATE TABLE `client` ( `creditInsurance` int(11) DEFAULT NULL, `eypbc` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Email\\nYesterday\\nPurchases\\nBy\\nConsigna', `hasToInvoiceByAddress` tinyint(1) DEFAULT '0', - `cplusTerIdNifFk` int(11) NOT NULL DEFAULT '1' COMMENT 'OBSOLETO', + `cplusTerIdNifFk__` int(11) NOT NULL DEFAULT '1' COMMENT 'OBSOLETO', `isCreatedAsServed` tinyint(1) DEFAULT '0', `hasInvoiceSimplified` tinyint(1) NOT NULL DEFAULT '0', `iban` varchar(45) CHARACTER SET utf8 DEFAULT NULL, @@ -26483,6 +26339,7 @@ CREATE TABLE `client` ( `transactionTypeSageFk` tinyint(4) DEFAULT NULL COMMENT 'Tipo de transacción por defecto asociado al cliente en SAGE', `transferorFk` int(11) DEFAULT NULL COMMENT 'Cliente que le ha transmitido la titularidad de la empresa', `lastSalesPersonFk` int(11) DEFAULT NULL COMMENT 'ultimo comercial que tuvo, para el calculo del peso en los rankings de equipo', + `businessTypeFk` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `IF` (`fi`), KEY `Id_Trabajador` (`salesPersonFk`), @@ -26500,7 +26357,9 @@ CREATE TABLE `client` ( KEY `typeFk` (`typeFk`), KEY `client_taxTypeSageFk_idx` (`taxTypeSageFk`), KEY `client_transactionTypeSageFk_idx` (`transactionTypeSageFk`), + KEY `client_FK` (`businessTypeFk`), 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_ibfk_1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE, CONSTRAINT `client_ibfk_2` FOREIGN KEY (`payMethodFk`) REFERENCES `payMethod` (`id`) ON UPDATE CASCADE, CONSTRAINT `client_ibfk_3` FOREIGN KEY (`salesPersonFk`) REFERENCES `worker` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, @@ -26526,9 +26385,13 @@ DELIMITER ;; FOR EACH ROW BEGIN - CALL pbx.phone_isValid(NEW.phone); - CALL pbx.phone_isValid(NEW.mobile); - CALL pbx.phone_isValid(NEW.fax); + IF (NEW.phone <> '') THEN + CALL pbx.phone_isValid(NEW.phone); + END IF; + + IF (NEW.mobile <> '') THEN + CALL pbx.phone_isValid(NEW.mobile); + END IF; SET NEW.accountingAccount = 4300000000 + NEW.id; @@ -26553,21 +26416,22 @@ DELIMITER ;; FOR EACH ROW BEGIN DECLARE vText VARCHAR(255) DEFAULT NULL; + DECLARE vPayMethodFk INT; -- Comprueba que el formato de los teléfonos es válido - IF !(NEW.phone <=> OLD.phone) THEN + IF !(NEW.phone <=> OLD.phone) AND (NEW.phone <> '') THEN CALL pbx.phone_isValid(NEW.phone); END IF; - IF !(NEW.mobile <=> OLD.mobile) THEN + IF !(NEW.mobile <=> OLD.mobile) AND (NEW.mobile <> '')THEN CALL pbx.phone_isValid(NEW.mobile); END IF; - IF !(NEW.fax <=> OLD.fax) THEN - CALL pbx.phone_isValid(NEW.fax); - END IF; - - IF NEW.payMethodFk = 4 AND NEW.dueDay = 0 THEN + SELECT id INTO vPayMethodFk + FROM vn.payMethod + WHERE code = 'bankDraft'; + + IF NEW.payMethodFk = vPayMethodFk AND NEW.dueDay = 0 THEN SET NEW.dueDay = 5; END IF; @@ -26710,12 +26574,12 @@ CREATE TABLE `clientCredit` ( `clientFk` int(11) NOT NULL, `amount` double unsigned NOT NULL, `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `workerFk` int(11) DEFAULT NULL, + `workerFk` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), KEY `workers_fk_idx` (`workerFk`), KEY `credit_ClienteFk` (`clientFk`), CONSTRAINT `credit_ClienteFk` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `workers_fk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE + CONSTRAINT `workers_fk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -26823,7 +26687,7 @@ DROP TABLE IF EXISTS `clientObservation`; CREATE TABLE `clientObservation` ( `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, `clientFk` int(11) NOT NULL, - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned DEFAULT NULL, `text` text COLLATE utf8_unicode_ci NOT NULL, `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), @@ -26885,7 +26749,7 @@ DROP TABLE IF EXISTS `clientProtected`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `clientProtected` ( `clientFk` int(11) NOT NULL, - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, `isValidated__` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`clientFk`), KEY `clientProtected_fk2_idx` (`workerFk`), @@ -27004,6 +26868,8 @@ CREATE TABLE `cmr` ( `addressFromFk` int(11) DEFAULT NULL, `supplierFk` int(11) DEFAULT NULL, `packagesList` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `merchandiseDetail` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `state` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`), KEY `cmr_fk1_idx` (`ticketFk`), KEY `cmr_fk2_idx` (`companyFk`), @@ -27056,6 +26922,18 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +-- +-- Table structure for table `cmrConfig` +-- + +DROP TABLE IF EXISTS `cmrConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `cmrConfig` ( + `dayOfMonth` int(11) DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `cmr_expeditionPallet` -- @@ -27116,7 +26994,9 @@ SET character_set_client = utf8; `carrierCountry` tinyint NOT NULL, `phone` tinyint NOT NULL, `mobile` tinyint NOT NULL, - `addressFk` tinyint NOT NULL + `addressFk` tinyint NOT NULL, + `stamp` tinyint NOT NULL, + `merchandiseDetail` tinyint NOT NULL ) ENGINE=MyISAM */; SET character_set_client = @saved_cs_client; @@ -27130,7 +27010,7 @@ DROP TABLE IF EXISTS `collection`; CREATE TABLE `collection` ( `id` int(11) NOT NULL AUTO_INCREMENT, `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `workerFk` int(11) DEFAULT NULL, + `workerFk` int(10) unsigned DEFAULT NULL, `stateFk` tinyint(3) unsigned DEFAULT NULL, `itemPackingTypeFk` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, `saleTotalCount` int(11) NOT NULL DEFAULT '0', @@ -27248,6 +27128,29 @@ SET character_set_client = utf8; ) ENGINE=MyISAM */; SET character_set_client = @saved_cs_client; +-- +-- Temporary table structure for view `collectionSmartTag2` +-- + +DROP TABLE IF EXISTS `collectionSmartTag2`; +/*!50001 DROP VIEW IF EXISTS `collectionSmartTag2`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE TABLE `collectionSmartTag2` ( + `code` tinyint NOT NULL, + `ticketFk` tinyint NOT NULL, + `level` tinyint NOT NULL, + `wagon` tinyint NOT NULL, + `shelvingFk` tinyint NOT NULL, + `collectionFk` tinyint NOT NULL, + `agencyFk` tinyint NOT NULL, + `clientFk` tinyint NOT NULL, + `worker` tinyint NOT NULL, + `shipped` tinyint NOT NULL, + `landed` tinyint NOT NULL +) ENGINE=MyISAM */; +SET character_set_client = @saved_cs_client; + -- -- Table structure for table `collectionVolumetry` -- @@ -27316,7 +27219,7 @@ CREATE TABLE `company` ( `id` smallint(5) unsigned NOT NULL, `code` char(3) COLLATE utf8_unicode_ci DEFAULT NULL, `register` varchar(120) COLLATE utf8_unicode_ci NOT NULL, - `workerManagerFk` int(11) NOT NULL, + `workerManagerFk` int(10) unsigned NOT NULL, `registered` date NOT NULL, `expired` date DEFAULT NULL, `logo` longblob, @@ -27335,6 +27238,7 @@ CREATE TABLE `company` ( `companyCodeTest` int(2) DEFAULT NULL, `footnotes` longtext COLLATE utf8_unicode_ci COMMENT 'pie de paginas en las facturas', `phytosanitary` longtext COLLATE utf8_unicode_ci, + `fhAdminNumber` int(11) DEFAULT NULL COMMENT 'número de cliente en FloraHolland', PRIMARY KEY (`id`), KEY `gerente_id` (`workerManagerFk`), KEY `empresa_cliente_idx` (`clientFk`), @@ -27536,6 +27440,8 @@ CREATE TABLE `config` ( `fakeEmail` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `defaultersMaxAmount` int(10) DEFAULT '200' COMMENT 'maxima deuda permitida a partir de la cual se bloquea a un usuario', `ASIEN` bigint(20) DEFAULT NULL, + `deviceHuntingMode` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Habilita el modo cazador para usuarios sin device registrado', + `tractorHuntingMode` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Habilita el modo cazador para usuarios que no se han logeado un tractor para sacar', PRIMARY KEY (`id`), KEY `fechainv_idx` (`inventoried`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; @@ -27580,7 +27486,7 @@ DROP TABLE IF EXISTS `contratos_subvencion_270619`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `contratos_subvencion_270619` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, `cod_centroFk` int(11) NOT NULL, `CodContratoFk` int(11) NOT NULL, `journey` decimal(5,2) NOT NULL DEFAULT '8.00', @@ -27612,7 +27518,10 @@ CREATE TABLE `conveyor` ( `height` int(11) DEFAULT NULL, `x` int(11) DEFAULT NULL, `y` int(11) DEFAULT NULL, - `color` int(11) DEFAULT '14548991', + `freeSpace` int(11) NOT NULL DEFAULT '0', + `isBusy` tinyint(1) NOT NULL DEFAULT '0', + `tandem` int(11) DEFAULT NULL COMMENT 'agrupa conveyors para dividir las cajas por tipo en una misma ruta', + `conveyorBuildingClassFk` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `conveyor_fk1_idx` (`typeFk`), CONSTRAINT `conveyor_fk1` FOREIGN KEY (`typeFk`) REFERENCES `conveyorType` (`id`) ON UPDATE CASCADE @@ -27630,6 +27539,7 @@ CREATE TABLE `conveyorBuildingClass` ( `id` int(11) NOT NULL AUTO_INCREMENT, `description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `priority` int(11) NOT NULL DEFAULT '0', + `weightThreshold` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Tipo de caja para el montaje de pallets'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -27663,14 +27573,19 @@ CREATE TABLE `conveyorExpedition` ( `expeditionFk` int(11) NOT NULL, `conveyorFk` int(11) DEFAULT NULL, `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `conveyorBuildingClassFk` int(11) NOT NULL, + `conveyorBuildingClassFk` int(11) NOT NULL DEFAULT '1', `length` int(11) NOT NULL DEFAULT '1', `width` int(11) NOT NULL DEFAULT '1', `height` int(11) NOT NULL DEFAULT '1', - `x` int(11) NOT NULL DEFAULT '1', + `x` int(11) NOT NULL DEFAULT '18100', `y` int(11) NOT NULL DEFAULT '1', `routeFk` int(11) NOT NULL, - `isBuilt` tinyint(4) NOT NULL DEFAULT '0', + `isIn` tinyint(4) NOT NULL DEFAULT '0', + `productionMinute` int(11) DEFAULT NULL, + `isOut` tinyint(4) NOT NULL DEFAULT '0', + `truck` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, + `criterion` int(11) DEFAULT NULL, + `isHeavy` tinyint(1) NOT NULL DEFAULT '1', PRIMARY KEY (`expeditionFk`), KEY `conveyorExpedition_fk1_idx` (`conveyorFk`), KEY `conveyorExpedition_fk2_idx` (`conveyorBuildingClassFk`), @@ -27696,13 +27611,13 @@ CREATE TABLE `conveyorMode` ( /*!40101 SET character_set_client = @saved_cs_client */; -- --- Table structure for table `conveyorMove` +-- Table structure for table `conveyorMove_kk` -- -DROP TABLE IF EXISTS `conveyorMove`; +DROP TABLE IF EXISTS `conveyorMove_kk`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `conveyorMove` ( +CREATE TABLE `conveyorMove_kk` ( `id` int(11) NOT NULL AUTO_INCREMENT, `fromConveyorFk` int(11) NOT NULL, `toConveyorFk` int(11) NOT NULL, @@ -27723,6 +27638,7 @@ DROP TABLE IF EXISTS `conveyorType`; CREATE TABLE `conveyorType` ( `id` int(11) NOT NULL AUTO_INCREMENT, `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `color` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -27798,6 +27714,36 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`country_AFTER_INSERT` AFTER INSERT ON `country` FOR EACH ROW +BEGIN + + UPDATE sage.Naciones + SET countryFk = NEW.id + WHERE Nacion = NEW.country; + + IF ROW_COUNT() = 0 THEN + INSERT INTO vn.mail (sender, subject, body) + VALUES ('cau@verdnatura.es', + 'Actualizar tabla sage.Naciones', + CONCAT('Se ha insertado un nuevo país en la tabla vn.conuntry. Para el correcto funcionamiento del sistema de contabilidad es necesario actualizar la columna sage.Naciones.countryFk con el valor del nuevo país. + Hay que buscar el nuevo país: ', NEW.country, ' en la tabla sage.Naciones y actualizar el campo sage.Naciones.countryFk con el valor ', NEW.id)); + END IF; + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`country_beforeUpdate` BEFORE UPDATE ON `country` FOR EACH ROW BEGIN @@ -28203,7 +28149,7 @@ CREATE TABLE `department` ( `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, `lft` int(11) DEFAULT NULL, `rgt` int(11) DEFAULT NULL, - `workerFk` int(11) DEFAULT NULL COMMENT 'Id_Trabajador es el jefe del departamento', + `workerFk` int(10) unsigned DEFAULT NULL COMMENT 'Id_Trabajador es el jefe del departamento', `companyFk` int(11) NOT NULL, `bossFk__` int(11) DEFAULT NULL, `x__` int(11) DEFAULT NULL, @@ -28217,6 +28163,7 @@ CREATE TABLE `department` ( `chatName` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, `isTeleworking` tinyint(1) DEFAULT '0', `notificationEmail` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, + `hasToRefill` tinyint(1) DEFAULT '0' COMMENT 'Rellenar días sin fichadas presenciales', PRIMARY KEY (`id`), UNIQUE KEY `name_UNIQUE` (`name`), KEY `fk_department_Trabajadores1_idx` (`workerFk`), @@ -28296,7 +28243,7 @@ CREATE TABLE `departmentItemType` ( `id` int(11) NOT NULL AUTO_INCREMENT, `departmentFk` int(11) NOT NULL, `itemTypeFk` smallint(5) unsigned NOT NULL, - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `departmentItemTypeIdx1_idx` (`departmentFk`,`itemTypeFk`), KEY `departmentItemTypeIdx2_idx` (`itemTypeFk`), @@ -28353,6 +28300,22 @@ CREATE TABLE `device` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `deviceLog` +-- + +DROP TABLE IF EXISTS `deviceLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `deviceLog` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `android_id` varchar(100) COLLATE utf8_unicode_ci NOT NULL, + `userFk` int(11) DEFAULT NULL, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `deviceProduction` -- @@ -28368,9 +28331,11 @@ CREATE TABLE `deviceProduction` ( `serialNumber` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, `departmentFk` int(11) DEFAULT NULL, `isOutOfService` tinyint(1) NOT NULL DEFAULT '0', + `android_id` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `device_id_UNIQUE` (`id`), UNIQUE KEY `sn_UNIQUE` (`imei`), + UNIQUE KEY `serial_number_UN` (`serialNumber`), KEY `deviceProductionModelsFgn` (`modelFk`), KEY `departmentFgn` (`departmentFk`), CONSTRAINT `departmentFgn` FOREIGN KEY (`departmentFk`) REFERENCES `department` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, @@ -28439,11 +28404,12 @@ CREATE TABLE `dms` ( `contentType` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, `file` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL, `hasFile` tinyint(4) NOT NULL DEFAULT '0', - `workerFk` int(11) DEFAULT NULL, + `workerFk` int(10) unsigned DEFAULT NULL, `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `warehouseFk` smallint(5) unsigned NOT NULL DEFAULT '60', PRIMARY KEY (`id`), UNIQUE KEY `emp_id` (`companyFk`,`hardCopyNumber`,`warehouseFk`), + UNIQUE KEY `dms_hardCopyNumber_IDX` (`hardCopyNumber`,`warehouseFk`,`companyFk`) USING BTREE, KEY `trabajador_id` (`workerFk`), KEY `warehouse_id` (`warehouseFk`), KEY `dms_dmsTypeFk_idx` (`dmsTypeFk`), @@ -28456,9 +28422,9 @@ CREATE TABLE `dms` ( /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -28474,10 +28440,9 @@ BEGIN IF NEW.hasFile THEN SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber FROM dms - WHERE companyFk = NEW.companyFk - AND warehouseFk = NEW.warehouseFk ; + WHERE warehouseFk = NEW.warehouseFk; - SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1) ; + SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1); END IF; SELECT code INTO vDmsTypeCode @@ -28512,8 +28477,7 @@ BEGIN SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber FROM dms - WHERE companyFk = NEW.companyFk - AND warehouseFk = NEW.warehouseFk; + WHERE warehouseFk = NEW.warehouseFk; SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1); END IF; @@ -28588,6 +28552,7 @@ CREATE TABLE `dua` ( `companyFk` smallint(5) unsigned NOT NULL DEFAULT '442', `ASIEN` double 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`), @@ -29144,26 +29109,6 @@ CREATE TABLE `entryObservation` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; --- --- Table structure for table `entryShelving__` --- - -DROP TABLE IF EXISTS `entryShelving__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `entryShelving__` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `entryFk` int(11) NOT NULL DEFAULT '204539', - `shelvingFk` varchar(10) CHARACTER SET utf8 NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `shelvingFk_UNIQUE` (`shelvingFk`), - KEY `entryShelving_fk1_idx` (`entryFk`), - KEY `entryShelving_fk2_idx` (`shelvingFk`), - CONSTRAINT `entryShelving_fk1` FOREIGN KEY (`entryFk`) REFERENCES `entry` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `entryShelving_fk2` FOREIGN KEY (`shelvingFk`) REFERENCES `shelving` (`code`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='relaciona matriculas con entradas'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Table structure for table `entrySplit` -- @@ -29210,6 +29155,24 @@ CREATE TABLE `envialiaAgency` ( UNIQUE KEY `id_UNIQUE` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`envialiaAgency_bd` BEFORE DELETE ON `envialiaAgency` FOR EACH ROW +BEGIN + CALL util.debugAdd("envialiaAgency", OLD.id); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; -- -- Table structure for table `envialiaCity` @@ -29228,6 +29191,24 @@ CREATE TABLE `envialiaCity` ( KEY `postalCode` (`postalCode`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`envialiaCity_bd` BEFORE DELETE ON `envialiaCity` FOR EACH ROW +BEGIN + CALL util.debugAdd("envialiaCity", OLD.id); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; -- -- Table structure for table `envialiaConfig` @@ -29386,10 +29367,11 @@ CREATE TABLE `expedition` ( `itemFk` int(11) DEFAULT NULL COMMENT 'Este campo hace referencia al artículo que habria que facturar si las cajas no fueran incluidos.\\nSe debería llamar packageItemFk', `counter` smallint(5) unsigned NOT NULL, `checked` tinyint(4) NOT NULL DEFAULT '0', - `workerFk` int(11) DEFAULT NULL, + `workerFk` int(10) unsigned DEFAULT NULL, `externalId` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, `packagingFk` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, `itemPackingTypeFk` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, + `hostFk` varchar(6) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`), KEY `index1` (`agencyModeFk`), KEY `index2` (`isBox`), @@ -29397,9 +29379,11 @@ CREATE TABLE `expedition` ( KEY `index4` (`ticketFk`), KEY `expedition_fk3_idx` (`packagingFk`), KEY `expedition_itemPackingTypeFk` (`itemPackingTypeFk`), + KEY `workerFk` (`workerFk`), CONSTRAINT `expedition_fk1` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON UPDATE CASCADE, CONSTRAINT `expedition_fk2` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `expedition_fk3` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE, + CONSTRAINT `expedition_ibfk_1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`), CONSTRAINT `expedition_itemPackingTypeFk` FOREIGN KEY (`itemPackingTypeFk`) REFERENCES `itemPackingType` (`code`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -29647,7 +29631,7 @@ CREATE TABLE `expeditionScan` ( `expeditionFk` int(11) NOT NULL, `scanned` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `palletFk` int(11) NOT NULL, - `workerFk` int(11) DEFAULT NULL, + `workerFk` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `expeditionFk_UNIQUE` (`expeditionFk`), KEY `expeditionScan_fk1_idx` (`expeditionFk`), @@ -29725,6 +29709,31 @@ SET character_set_client = utf8; ) ENGINE=MyISAM */; SET character_set_client = @saved_cs_client; +-- +-- Temporary table structure for view `expeditionSticker__` +-- + +DROP TABLE IF EXISTS `expeditionSticker__`; +/*!50001 DROP VIEW IF EXISTS `expeditionSticker__`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE TABLE `expeditionSticker__` ( + `expeditionFk` tinyint NOT NULL, + `ticketFk` tinyint NOT NULL, + `addressFk` tinyint NOT NULL, + `clientFk` tinyint NOT NULL, + `street` tinyint NOT NULL, + `postalCode` tinyint NOT NULL, + `city` tinyint NOT NULL, + `nickname` tinyint NOT NULL, + `routeFk` tinyint NOT NULL, + `beachFk` tinyint NOT NULL, + `zona` tinyint NOT NULL, + `province` tinyint NOT NULL, + `phone` tinyint NOT NULL +) ENGINE=MyISAM */; +SET character_set_client = @saved_cs_client; + -- -- Temporary table structure for view `expeditionTimeExpended` -- @@ -30239,8 +30248,8 @@ CREATE TABLE `inventoryFailure` ( `quantity` int(11) NOT NULL, `value` decimal(10,2) NOT NULL, `warehouseFk` smallint(6) unsigned NOT NULL, - `throwerFk` int(11) DEFAULT NULL, - `guiltyFk` int(11) DEFAULT NULL, + `throwerFk` int(10) unsigned DEFAULT NULL, + `guiltyFk` int(10) unsigned DEFAULT NULL, `causeFk` int(11) DEFAULT NULL, `explanation` varchar(250) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`), @@ -30344,7 +30353,7 @@ CREATE TABLE `invoiceIn` ( `serialNumber` mediumint(11) unsigned DEFAULT NULL COMMENT 'insertado por Trigger', `serial` char(1) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'R', `supplierFk` int(11) NOT NULL, - `issued` date NOT NULL COMMENT 'Fecha de emision de la factura', + `issued` date DEFAULT NULL COMMENT 'Fecha de emision de la factura', `supplierRef` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, `isBooked` tinyint(1) NOT NULL DEFAULT '0', `currencyFk` tinyint(3) unsigned NOT NULL DEFAULT '1', @@ -30390,9 +30399,9 @@ CREATE TABLE `invoiceIn` ( /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -30425,7 +30434,7 @@ DELIMITER ;; WHERE supplierRef = NEW.supplierRef AND supplierFk = NEW.supplierFk AND YEAR(issued) = YEAR(NEW.issued) - AND id = NEW.id + AND id <> NEW.id ) THEN CALL util.throw('reference duplicated'); END IF; @@ -30503,13 +30512,23 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `invoiceIn_au` AFTER UPDATE ON `invoiceIn` FOR EACH ROW BEGIN - IF NEW.issued != OLD.issued - OR - NEW.currencyFk != OLD.currencyFk - THEN - - -- CALL vn2008.recibidaIvaDivisaUpdate(NEW.id); - + IF NEW.issued != OLD.issued + OR NEW.currencyFk != OLD.currencyFk THEN + + UPDATE invoiceInTax iit + JOIN invoiceIn ii ON ii.id = iit.invoiceInFk + LEFT JOIN referenceRate rr ON rr.dated = ii.issued + AND rr.currencyFk = ii.currencyFk + SET iit.taxableBase = IF(iit.foreignValue IS NULL, iit.taxableBase, iit.foreignValue / rr.value) + WHERE ii.id = NEW.id; + + UPDATE invoiceInDueDay iidd + JOIN invoiceIn ii ON ii.id = iidd.invoiceInFk + LEFT JOIN referenceRate rr ON rr.dated = ii.issued + AND rr.currencyFk = ii.currencyFk + SET iidd.amount = IF(iidd.foreignValue IS NULL, iidd.amount, iidd.foreignValue / rr.value) + WHERE ii.id = NEW.id; + END IF; END */;; @@ -30704,6 +30723,33 @@ SET character_set_client = utf8; ) ENGINE=MyISAM */; SET character_set_client = @saved_cs_client; +-- +-- Table structure for table `invoiceInLog` +-- + +DROP TABLE IF EXISTS `invoiceInLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `invoiceInLog` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `originFk` mediumint(8) unsigned NOT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, + `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `description` text CHARACTER SET utf8, + `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `oldInstance` text COLLATE utf8_unicode_ci, + `newInstance` text COLLATE utf8_unicode_ci, + `changedModelId` int(11) DEFAULT NULL, + `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `originFk` (`originFk`), + KEY `userFk` (`userFk`), + CONSTRAINT `invoiceInLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `invoiceInLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `invoiceInSage` -- @@ -30862,18 +30908,15 @@ CREATE TABLE `invoiceOut` ( `dued` datetime DEFAULT NULL, `bankFk` int(11) DEFAULT NULL, `clientFk` int(11) DEFAULT '0', - `Id_Remesa__` int(11) DEFAULT NULL, - `Remesar__` tinyint(1) NOT NULL DEFAULT '0', - `taxableBase7` decimal(12,2) DEFAULT '0.00', - `taxableBase16` decimal(12,2) DEFAULT '0.00', - `equ1` decimal(12,2) DEFAULT '0.00', - `equ4` decimal(12,2) DEFAULT '0.00', - `vat7` decimal(12,2) DEFAULT '0.00', - `vat16` decimal(12,2) DEFAULT '0.00', - `workerFk` int(11) DEFAULT '0', + `taxableBase7__` decimal(12,2) DEFAULT '0.00', + `taxableBase16__` decimal(12,2) DEFAULT '0.00', + `equ1__` decimal(12,2) DEFAULT '0.00', + `equ4__` decimal(12,2) DEFAULT '0.00', + `vat7__` decimal(12,2) DEFAULT '0.00', + `vat16__` decimal(12,2) DEFAULT '0.00', + `workerFk__` int(11) DEFAULT '0', `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `companyFk` smallint(5) unsigned NOT NULL DEFAULT '442', - `liquidacion__` smallint(6) DEFAULT '0', `hasPdf` tinyint(3) unsigned NOT NULL DEFAULT '0', `booked` date DEFAULT NULL, `cplusInvoiceType477Fk` int(10) unsigned NOT NULL DEFAULT '1', @@ -30884,8 +30927,7 @@ CREATE TABLE `invoiceOut` ( UNIQUE KEY `Id_Factura` (`ref`), KEY `Id_Banco` (`bankFk`), KEY `Id_Cliente` (`clientFk`), - KEY `Id_Remesa` (`Id_Remesa__`), - KEY `Id_Trabajador` (`workerFk`), + KEY `Id_Trabajador` (`workerFk__`), KEY `empresa_id` (`companyFk`), KEY `Fecha` (`issued`), KEY `Facturas_ibfk_2_idx` (`cplusInvoiceType477Fk`), @@ -31085,7 +31127,7 @@ CREATE TABLE `item` ( `minPrice` double DEFAULT '0', `isToPrint` tinyint(1) NOT NULL DEFAULT '0', `isDeliveryNote__` tinyint(1) NOT NULL DEFAULT '0', - `taxClassFk` tinyint(4) unsigned NOT NULL DEFAULT '1', + `taxClassFk__` tinyint(4) unsigned NOT NULL DEFAULT '1', `family` varchar(3) CHARACTER SET utf8 NOT NULL DEFAULT 'VT', `box` tinyint(1) NOT NULL DEFAULT '0', `category` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, @@ -31142,7 +31184,7 @@ CREATE TABLE `item` ( KEY `Color` (`inkFk`), KEY `id_origen` (`originFk`), KEY `Codintrastat` (`intrastatFk`), - KEY `iva_group_id` (`taxClassFk`), + KEY `iva_group_id` (`taxClassFk__`), KEY `tipo_id` (`typeFk`), KEY `producer_id` (`producerFk`), KEY `ArticlesIsActive_idx` (`isActive`), @@ -31157,7 +31199,7 @@ CREATE TABLE `item` ( CONSTRAINT `item_family` FOREIGN KEY (`family`) REFERENCES `itemFamily` (`code`) ON UPDATE CASCADE, CONSTRAINT `item_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `origin` (`id`) ON UPDATE CASCADE, CONSTRAINT `item_ibfk_2` FOREIGN KEY (`intrastatFk`) REFERENCES `intrastat` (`id`) ON UPDATE CASCADE, - CONSTRAINT `item_ibfk_4` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE, + CONSTRAINT `item_ibfk_4` FOREIGN KEY (`taxClassFk__`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE, CONSTRAINT `item_ibfk_5` FOREIGN KEY (`typeFk`) REFERENCES `itemType` (`id`) ON UPDATE CASCADE, CONSTRAINT `item_ibfk_6` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `itemsupplyResponseFk` FOREIGN KEY (`supplyResponseFk`) REFERENCES `edi`.`supplyResponse` (`ID`) ON DELETE SET NULL ON UPDATE CASCADE, @@ -31223,21 +31265,21 @@ DELIMITER ;; BEGIN CALL hedera.image_ref('catalog', NEW.image); - INSERT INTO vn.itemTaxCountry(itemFk, countryFk, taxClassFk) - SELECT NEW.id, 1, NEW.taxClassFk; + INSERT INTO vn.itemTaxCountry(itemFk, countryFk) + SELECT NEW.id, 1; - INSERT INTO vn.itemTaxCountry(itemFk, countryFk, taxClassFk) - SELECT NEW.id, 5, NEW.taxClassFk; + INSERT INTO vn.itemTaxCountry(itemFk, countryFk) + SELECT NEW.id, 5; - INSERT INTO vn.itemTaxCountry(itemFk, countryFk, taxClassFk) - SELECT NEW.id, 30, NEW.taxClassFk; -/* + INSERT INTO vn.itemTaxCountry(itemFk, countryFk) + SELECT NEW.id, 30; + /* IF NEW.typeFk IS NOT NULL THEN INSERT INTO vn.itemTag (itemFk, tagFk, priority) SELECT NEW.id, tagFk, priority FROM vn.itemTypeTag WHERE itemTypeFk = NEW.typeFk; - END IF; -*/ + END IF;*/ + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -31331,57 +31373,10 @@ CREATE TABLE `itemBotanical` ( KEY `genusFgn_idx` (`genusFk`), KEY `specieFgn_idx` (`specieFk`), CONSTRAINT `itemBotanicalItemFkFk` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `itemBotanical_FK` FOREIGN KEY (`specieFk`) REFERENCES `specie` (`id`) ON DELETE SET NULL ON UPDATE CASCADE + CONSTRAINT `itemBotanical_FK` FOREIGN KEY (`specieFk`) REFERENCES `specie` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `itemBotanical_FK_1` FOREIGN KEY (`genusFk`) REFERENCES `genus` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Sustituye a antiguo NomBotanic de Articles'; /*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`itemBotanical_beforeInsert` BEFORE INSERT ON `itemBotanical` FOR EACH ROW -BEGIN -/** - * Hay una versión en salix que machacará toda esta función/procedimiento avisa - * a jgallego de los cambios que quieres hacer. - */ - /*IF (NEW.botanical >= '') THEN - CALL util.throw('no se puede modificar el nombre botanico, use los campos genero y especie'); - END IF;*/ -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`itemBotanical_beforeUpdate` BEFORE UPDATE ON `itemBotanical` FOR EACH ROW -BEGIN -/** - * Hay una versión en salix que machacará toda esta función/procedimiento avisa - * a jgallego de los cambios que quieres hacer. - - IF (NEW.botanical >= '') THEN - CALL util.throw('no se puede modificar el nombre botanico, use los campos genero y especie'); - END IF; */ -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -- -- Temporary table structure for view `itemBotanicalWithGenus` @@ -31541,6 +31536,19 @@ BEGIN IF NEW.itemFk IN (95, 98) THEN SET NEW.cm3 = 0; END IF; + + IF !(NEW.cm3delivery <=> OLD.cm3delivery) THEN + INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) + SELECT r.id + FROM vn.itemCost ic + JOIN vn.sale s ON s.itemFk = ic.itemFk + JOIN vn.ticket t ON t.id = s.ticketFk AND t.warehouseFk = ic.warehouseFk + JOIN vn.route r ON r.id = t.routeFk + WHERE r.isOk = FALSE + AND ic.itemFk = NEW.itemFk + AND r.created >= CURDATE() + GROUP BY r.id; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -31629,7 +31637,8 @@ SET @saved_cs_client = @@character_set_client; SET character_set_client = utf8; /*!50001 CREATE TABLE `itemInk` ( `longName` tinyint NOT NULL, - `inkFk` tinyint NOT NULL + `inkFk` tinyint NOT NULL, + `color` tinyint NOT NULL ) ENGINE=MyISAM */; SET character_set_client = @saved_cs_client; @@ -31859,6 +31868,23 @@ CREATE TABLE `itemRepo` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Temporary table structure for view `itemSearch` +-- + +DROP TABLE IF EXISTS `itemSearch`; +/*!50001 DROP VIEW IF EXISTS `itemSearch`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE TABLE `itemSearch` ( + `itemFk` tinyint NOT NULL, + `concept` tinyint NOT NULL, + `quantity` tinyint NOT NULL, + `nickname` tinyint NOT NULL, + `shipped` tinyint NOT NULL +) ENGINE=MyISAM */; +SET character_set_client = @saved_cs_client; + -- -- Table structure for table `itemShelving` -- @@ -32590,7 +32616,7 @@ CREATE TABLE `itemType` ( `order` int(11) DEFAULT '0', `temperature` tinyint(1) unsigned NOT NULL DEFAULT '0', `categoryFk` int(10) unsigned NOT NULL, - `workerFk` int(11) NOT NULL, + `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, `f11` tinyint(4) NOT NULL DEFAULT '0', @@ -32614,6 +32640,7 @@ CREATE TABLE `itemType` ( `warehouseFk` smallint(6) unsigned NOT NULL DEFAULT '60', `compression` decimal(5,2) DEFAULT '1.00', `itemPackingTypeFk` varchar(1) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'H', + `temperatureFk` varchar(10) CHARACTER SET utf8 DEFAULT NULL, PRIMARY KEY (`code`), UNIQUE KEY `tipo_id_UNIQUE` (`id`), UNIQUE KEY `Tipo_UNIQUE` (`name`,`categoryFk`), @@ -32622,10 +32649,12 @@ CREATE TABLE `itemType` ( KEY `Tipos_fk3_idx` (`making`), KEY `tipos_fk4_idx` (`roleCodeFk__`), KEY `warehouseFk5_idx` (`warehouseFk`), + KEY `temperatureFk` (`temperatureFk`), CONSTRAINT `Tipos_fk3` FOREIGN KEY (`making`) REFERENCES `confectionType` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `Trabajador` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, CONSTRAINT `itemType_ibfk_1` FOREIGN KEY (`categoryFk`) REFERENCES `itemCategory` (`id`) ON UPDATE CASCADE, CONSTRAINT `itemType_ibfk_2` FOREIGN KEY (`roleCodeFk__`) REFERENCES `account`.`role` (`name`) ON UPDATE CASCADE, + CONSTRAINT `temperatureFk` FOREIGN KEY (`temperatureFk`) REFERENCES `temperature` (`code`), CONSTRAINT `warehouseFk5` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Protege la tabla tipos de updates para los 4 parámetros de los compradores, en funcion del valor del campo CodigoRojo de tblContadores.'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -32808,6 +32837,28 @@ SET character_set_client = utf8; ) ENGINE=MyISAM */; SET character_set_client = @saved_cs_client; +-- +-- Temporary table structure for view `lastPurchases` +-- + +DROP TABLE IF EXISTS `lastPurchases`; +/*!50001 DROP VIEW IF EXISTS `lastPurchases`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE TABLE `lastPurchases` ( + `landed` tinyint NOT NULL, + `warehouseFk` tinyint NOT NULL, + `warehouse` tinyint NOT NULL, + `longName` tinyint NOT NULL, + `subName` tinyint NOT NULL, + `entryFk` tinyint NOT NULL, + `stickers` tinyint NOT NULL, + `packing` tinyint NOT NULL, + `ref` tinyint NOT NULL, + `itemFk` tinyint NOT NULL +) ENGINE=MyISAM */; +SET character_set_client = @saved_cs_client; + -- -- Temporary table structure for view `lastTopClaims` -- @@ -32874,7 +32925,7 @@ CREATE TABLE `machine` ( `use` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, `productionYear` int(11) DEFAULT NULL, `photo` blob, - `workerFk` int(11) DEFAULT NULL, + `workerFk` int(10) unsigned DEFAULT NULL, `companyFk` smallint(5) unsigned NOT NULL DEFAULT '442', `ppeFk` int(11) DEFAULT NULL, `supplierFk` int(11) DEFAULT NULL, @@ -32882,8 +32933,8 @@ CREATE TABLE `machine` ( UNIQUE KEY `plate` (`plate`), UNIQUE KEY `serialNumber` (`serialNumber`), KEY `machine_FK` (`ppeFk`), - KEY `machine_FK_1` (`workerFk`), KEY `machine_FK_2` (`supplierFk`), + KEY `machine_FK_1` (`workerFk`), CONSTRAINT `machine_FK` FOREIGN KEY (`ppeFk`) REFERENCES `ppe` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `machine_FK_1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, CONSTRAINT `machine_FK_2` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON DELETE SET NULL ON UPDATE CASCADE @@ -32925,12 +32976,12 @@ CREATE TABLE `machineDetail` ( `dated` date NOT NULL, `action` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `value` decimal(10,2) DEFAULT NULL, - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, `dmsFk` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `machineDetail_FK` (`machineFk`), - KEY `machineDetail_FK_1` (`workerFk`), KEY `machineDetail_FK_2` (`dmsFk`), + KEY `machineDetail_FK_1` (`workerFk`), CONSTRAINT `machineDetail_FK` FOREIGN KEY (`machineFk`) REFERENCES `machine` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `machineDetail_FK_1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, CONSTRAINT `machineDetail_FK_2` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE SET NULL ON UPDATE CASCADE @@ -32956,6 +33007,27 @@ CREATE TABLE `machineDms` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!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, + `inTimed` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `outTimed` datetime DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `machineWorker_FK_1` (`machineFk`), + 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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_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 `mail` -- @@ -32965,6 +33037,7 @@ DROP TABLE IF EXISTS `mail`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `mail` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `receiver` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `sender` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `replyTo` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, `subject` varchar(100) COLLATE utf8_unicode_ci NOT NULL, @@ -32981,6 +33054,31 @@ CREATE TABLE `mail` ( KEY `creation_idx` (`creationDate`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`mail_beforeInsert` +BEFORE INSERT ON `mail` FOR EACH ROW +BEGIN + + IF NEW.sender IS NOT NULL THEN + + SET NEW.receiver = NEW.sender; + + END IF; + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; -- -- Table structure for table `mailTemplates` @@ -33100,7 +33198,7 @@ DROP TABLE IF EXISTS `medicalReview`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `medicalReview` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, `centerFk` int(11) NOT NULL, `date` date DEFAULT NULL, `time` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL, @@ -33223,7 +33321,7 @@ DROP TABLE IF EXISTS `mobileAppVersionControl`; CREATE TABLE `mobileAppVersionControl` ( `id` int(11) NOT NULL AUTO_INCREMENT, `appName` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `version` int(11) NOT NULL DEFAULT '0', + `version` varchar(45) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Tabla para llevar el control de las Versions de las aplicaciones móvil '; /*!40101 SET character_set_client = @saved_cs_client */; @@ -33454,11 +33552,11 @@ DROP TABLE IF EXISTS `packageEquivalent`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `packageEquivalent` ( - `packageFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `packagingFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL, `equivalentFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`packageFk`,`equivalentFk`), + PRIMARY KEY (`packagingFk`,`equivalentFk`), KEY `packageEquivalent_fk2_idx` (`equivalentFk`), - CONSTRAINT `packageEquivalent_fk1` FOREIGN KEY (`packageFk`) REFERENCES `packaging` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `packageEquivalent_fk1` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `packageEquivalent_fk2` FOREIGN KEY (`equivalentFk`) REFERENCES `packaging` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='recoge los modelos de cubos que se han de sustituir a efectos de presentar informes resumidos'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -33505,9 +33603,12 @@ CREATE TABLE `packaging` ( `cmrName` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, `freightItemFk` int(11) DEFAULT NULL, `hasCompressionVariations` tinyint(1) DEFAULT '0' COMMENT 'Floramondo puede servirlos no llenos del todo', + `conveyorBuildingClassFk` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `packaging_fk1` (`itemFk`), KEY `packaging_fk2_idx` (`freightItemFk`), + KEY `packaging_FK` (`conveyorBuildingClassFk`), + CONSTRAINT `packaging_FK` FOREIGN KEY (`conveyorBuildingClassFk`) REFERENCES `conveyorBuildingClass` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `packaging_fk1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE, CONSTRAINT `packaging_fk2` FOREIGN KEY (`freightItemFk`) REFERENCES `item` (`id`) ON DELETE SET NULL ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; @@ -33524,10 +33625,30 @@ CREATE TABLE `packagingConfig` ( `id` int(11) NOT NULL AUTO_INCREMENT, `upperGap` int(11) NOT NULL, `previousPreparationMinimumSize` int(11) NOT NULL, + `defaultConveyorBuildingClass` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Altura mínima para preparar pedidos en preparacion previa'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `packingSite` +-- + +DROP TABLE IF EXISTS `packingSite`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `packingSite` ( + `code` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `hostFk` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `printerFk` tinyint(3) unsigned DEFAULT NULL, + PRIMARY KEY (`code`), + KEY `packingSite_FK` (`hostFk`), + KEY `packingSite_FK_1` (`printerFk`), + CONSTRAINT `packingSite_FK` FOREIGN KEY (`hostFk`) REFERENCES `vn2008`.`config_host` (`config_host_id`), + CONSTRAINT `packingSite_FK_1` FOREIGN KEY (`printerFk`) REFERENCES `vn2008`.`Impresoras` (`Id_Impresora`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `parking` -- @@ -33676,9 +33797,10 @@ BEGIN DECLARE cuenta_banco,cuenta_proveedor DOUBLE; DECLARE vNewBookEntry INT; DECLARE bolCASH BOOLEAN; + DECLARE isSupplierActive BOOLEAN; -- PAK 10/02/15 No se asientan los pagos directamente, salvo en el caso de las cajas de CASH - SELECT (cash = 1) INTO bolCASH FROM bank WHERE bank.id = NEW.bankFk ; + SELECT (at2.code = 'cash') INTO bolCASH FROM vn.bank b JOIN vn.accountingType at2 ON at2.id = b.cash WHERE b.id = NEW.bankFk ; IF bolCASH THEN @@ -33710,6 +33832,15 @@ BEGIN END IF; SET NEW.dueDated = IFNULL(NEW.dueDated, NEW.received); + + SELECT isActive INTO isSupplierActive + FROM supplier + WHERE id = NEW.supplierFk; + + IF isSupplierActive = FALSE THEN + CALL util.throw('SUPPLIER_INACTIVE'); + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -33823,7 +33954,7 @@ CREATE TABLE `person` ( `fi` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, `birth` date DEFAULT NULL, `readerId` int(11) DEFAULT NULL, - `workerFk` int(11) DEFAULT NULL, + `workerFk` int(10) unsigned DEFAULT NULL, `isDisable` tinyint(1) NOT NULL DEFAULT '0', `isFreelance` tinyint(1) NOT NULL DEFAULT '0', `isSsDiscounted` tinyint(1) NOT NULL DEFAULT '0', @@ -34071,7 +34202,7 @@ CREATE TABLE `ppe` ( `cause` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, `photo` blob, `isInvestmentAsset` tinyint(4) NOT NULL DEFAULT '0', - `workerFk` int(11) DEFAULT NULL, + `workerFk` int(10) unsigned DEFAULT NULL, `companyFk` smallint(5) unsigned NOT NULL DEFAULT '442', `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`), @@ -34160,48 +34291,6 @@ CREATE TABLE `ppePlan` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Plan de amortizacion para la tabla ppe'; /*!40101 SET character_set_client = @saved_cs_client */; --- --- Table structure for table `priceBuilderWarehouse__` --- - -DROP TABLE IF EXISTS `priceBuilderWarehouse__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `priceBuilderWarehouse__` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `warehouseFk` smallint(6) unsigned NOT NULL, - `priceBuilderFk` int(11) NOT NULL, - PRIMARY KEY (`id`), - KEY `priceBuilderWarehouse_fk1_idx` (`warehouseFk`), - KEY `priceBuilderWarehouse_fk2_idx` (`priceBuilderFk`), - CONSTRAINT `priceBuilderWarehouse_fk1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `priceBuilderWarehouse_fk2` FOREIGN KEY (`priceBuilderFk`) REFERENCES `priceBuilder__` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `priceBuilder__` --- - -DROP TABLE IF EXISTS `priceBuilder__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `priceBuilder__` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `itemTypeFk` smallint(5) unsigned NOT NULL COMMENT 'Sirve para definir precios en tarifa2 para grupos de items', - `started` date DEFAULT NULL, - `finished` date DEFAULT NULL, - `price` decimal(10,3) NOT NULL, - `userFk` int(10) unsigned DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `priceBuilder_fk1_idx` (`itemTypeFk`), - KEY `priceBuilder_fk2_idx` (`userFk`), - CONSTRAINT `priceBuilder_fk1` FOREIGN KEY (`itemTypeFk`) REFERENCES `itemType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `priceBuilder_fk2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Table structure for table `priceFixed` -- @@ -34293,7 +34382,7 @@ CREATE TABLE `printServerQueue` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `printerFk` tinyint(3) unsigned DEFAULT NULL, `priorityFk` tinyint(3) unsigned DEFAULT NULL, - `labelReportFk` tinyint(3) unsigned DEFAULT '0', + `labelReportFk` tinyint(3) unsigned DEFAULT NULL, `statusFk` tinyint(3) unsigned DEFAULT '1', `started` datetime DEFAULT NULL, `finished` datetime DEFAULT NULL, @@ -34303,13 +34392,15 @@ CREATE TABLE `printServerQueue` ( `param3` text COLLATE utf8_unicode_ci, `error` text COLLATE utf8_unicode_ci, `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `reportFk` tinyint(3) DEFAULT NULL, + `reportFk__` tinyint(3) unsigned DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `Id_Impresora_2` (`printerFk`,`priorityFk`,`labelReportFk`,`statusFk`,`param1`,`workerFk`,`param2`), KEY `Id_estado` (`statusFk`), KEY `Id_Impresora` (`printerFk`), KEY `Id_Prioridad` (`priorityFk`), KEY `Id_Trabajador` (`workerFk`), + KEY `printServerQueue_FK` (`labelReportFk`), + CONSTRAINT `printServerQueue_FK` FOREIGN KEY (`labelReportFk`) REFERENCES `labelReport` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `printServerQueue_ibfk_3` FOREIGN KEY (`priorityFk`) REFERENCES `queuePriority` (`id`) ON UPDATE CASCADE, CONSTRAINT `printServerQueue_ibfk_4` FOREIGN KEY (`printerFk`) REFERENCES `vn2008`.`Impresoras` (`Id_Impresora`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; @@ -34471,10 +34562,13 @@ CREATE TABLE `province` ( `warehouseFk` smallint(6) unsigned DEFAULT NULL COMMENT 'warehouse responsable de las rutas', `zoneFk` tinyint(4) DEFAULT NULL, `geoFk` int(11) DEFAULT NULL, + `autonomyFk` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `Paises_Id` (`countryFk`), KEY `warehouse_Id` (`warehouseFk`), KEY `provicne_zone_fk_idx` (`zoneFk`), + KEY `province_FK` (`autonomyFk`), + CONSTRAINT `province_FK` FOREIGN KEY (`autonomyFk`) REFERENCES `autonomy` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `province_ibfk_1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE, CONSTRAINT `province_zone_fk` FOREIGN KEY (`zoneFk`) REFERENCES `vn2008`.`zones` (`zone_id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `warehouse_Id` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE SET NULL ON UPDATE CASCADE @@ -34483,17 +34577,21 @@ CREATE TABLE `province` ( /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`province_beforeInsert` BEFORE INSERT ON `province` FOR EACH ROW BEGIN + SET NEW.geoFk = zoneGeo_new('province', NEW.`name`, - (SELECT geoFk FROM country WHERE id = NEW.countryFk)); + (SELECT geoFk FROM autonomy WHERE id = NEW.autonomyFk)); + + SET NEW.countryFk = (SELECT a.countryFk FROM vn.autonomy a WHERE a.id = NEW.autonomyFk); + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -34503,18 +34601,23 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`province_beforeUpdate` - BEFORE UPDATE ON `province` FOR EACH ROW -BEGIN - -- IF !(OLD.geoFk <=> NEW.geoFk) THEN - -- CALL zoneGeo_throwNotEditable; - -- END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER province_beforeUpdate +BEFORE UPDATE +ON province FOR EACH ROW +BEGIN + + IF !(OLD.autonomyFk <=> NEW.autonomyFk) THEN + + SET NEW.countryFk = (SELECT a.countryFk FROM vn.autonomy a WHERE a.id = NEW.autonomyFk); + + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -34524,18 +34627,18 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`province_afterUpdate` AFTER UPDATE ON `province` FOR EACH ROW BEGIN - IF !(OLD.countryFk <=> NEW.countryFk) THEN + IF !(OLD.autonomyFk <=> NEW.autonomyFk) THEN CALL zoneGeo_setParent(NEW.geoFk, - (SELECT geoFk FROM country WHERE id = NEW.countryFk)); + (SELECT geoFk FROM autonomy WHERE id = NEW.autonomyFk)); END IF; IF !(OLD.`name` <=> NEW.`name`) THEN @@ -34699,7 +34802,7 @@ CREATE TABLE `receipt` ( `amountPaid` decimal(10,2) NOT NULL DEFAULT '0.00', `amountUnpaid` decimal(10,2) NOT NULL DEFAULT '0.00', `payed` datetime DEFAULT NULL, - `workerFk` int(11) DEFAULT NULL, + `workerFk` int(10) unsigned DEFAULT NULL, `bankFk` int(11) DEFAULT '0', `clientFk` int(11) DEFAULT '0', `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, @@ -34956,7 +35059,7 @@ DROP TABLE IF EXISTS `route`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `route` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `workerFk` int(11) DEFAULT NULL, + `workerFk` int(10) unsigned DEFAULT NULL, `created` date NOT NULL, `vehicleFk` int(10) unsigned DEFAULT NULL, `agencyModeFk` int(11) DEFAULT NULL, @@ -34981,6 +35084,7 @@ CREATE TABLE `route` ( KEY `route_ibfk_2_idx` (`workerFk`), KEY `fk_route_1_idx` (`zoneFk`), KEY `asdfasdf_idx` (`invoiceInFk`), + KEY `route_idxIsOk` (`isOk`), CONSTRAINT `fk_route_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `route_fk5` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `route_ibfk_1` FOREIGN KEY (`gestdocFk`) REFERENCES `dms` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, @@ -35093,7 +35197,7 @@ DROP TABLE IF EXISTS `routeComplement`; CREATE TABLE `routeComplement` ( `id` int(11) NOT NULL AUTO_INCREMENT, `dated` date NOT NULL, - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, `price` decimal(10,2) NOT NULL, `routeActionFk` int(11) NOT NULL, PRIMARY KEY (`id`), @@ -35114,6 +35218,7 @@ DROP TABLE IF EXISTS `routeConfig`; CREATE TABLE `routeConfig` ( `id` int(10) unsigned NOT NULL, `kmRate` decimal(10,4) DEFAULT NULL, + `kmTruckRate` decimal(10,4) DEFAULT NULL, `m3Distribution` decimal(10,4) DEFAULT NULL, `m3Management` decimal(10,2) DEFAULT NULL, `m3Palletization` decimal(10,2) DEFAULT NULL, @@ -35132,7 +35237,10 @@ CREATE TABLE `routeConfig` ( `distributionM3Category2` decimal(5,2) DEFAULT NULL, `plusCategory1Concept` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, `plusCategory2Concept` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`) + `defaultCompanyFk` smallint(5) unsigned DEFAULT '442', + PRIMARY KEY (`id`), + KEY `routeConfig_FK` (`defaultCompanyFk`), + CONSTRAINT `routeConfig_FK` FOREIGN KEY (`defaultCompanyFk`) REFERENCES `company` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -35205,7 +35313,7 @@ DROP TABLE IF EXISTS `routeLoadWorker`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `routeLoadWorker` ( `routeFk` int(10) unsigned NOT NULL, - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, PRIMARY KEY (`routeFk`,`workerFk`), KEY `frmWorker_idx` (`workerFk`), CONSTRAINT `frmRutas` FOREIGN KEY (`routeFk`) REFERENCES `route` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, @@ -35240,6 +35348,19 @@ CREATE TABLE `routeLog` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `routeRecalc` +-- + +DROP TABLE IF EXISTS `routeRecalc`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `routeRecalc` ( + `routeFk` int(11) NOT NULL, + PRIMARY KEY (`routeFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Queue of changed volume to recalc route volumen'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `routeUserPercentage` -- @@ -35249,7 +35370,7 @@ DROP TABLE IF EXISTS `routeUserPercentage`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `routeUserPercentage` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, `percentage` decimal(10,2) NOT NULL, `dated` date NOT NULL, PRIMARY KEY (`id`), @@ -35317,11 +35438,11 @@ CREATE TABLE `sale` ( /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER sale_afterInsert AFTER INSERT @@ -35344,7 +35465,16 @@ BEGIN AND (c.itemPackingTypeFk = i.itemPackingTypeFk OR ISNULL(c.itemPackingTypeFk)) SET c.saleTotalCount = c.saleTotalCount + 1; - + + INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) + SELECT r.id + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.route r ON r.id = t.routeFk + WHERE r.isOk = FALSE + AND s.id = NEW.id + AND r.created >= CURDATE() + GROUP BY r.id; END IF; END */;; @@ -35360,18 +35490,18 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER sale_beforeUpdate BEFORE UPDATE ON sale FOR EACH ROW BEGIN - +/* IF (SELECT COUNT(*) from item i WHERE id = NEW.itemFk AND family = 'SER') THEN CALL util.throw('Cannot insert a service item into a ticket'); END IF; - +*/ IF NEW.discount > 100 THEN SET NEW.discount = 0; END IF; @@ -35390,11 +35520,11 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `sale_afterUpdate` AFTER UPDATE ON `sale` @@ -35403,6 +35533,7 @@ BEGIN DECLARE vIsToSendMail BOOL; DECLARE vPickedLines INT; DECLARE vCollectionFk INT; + DECLARE vUserRole VARCHAR(255); IF !(NEW.id <=> OLD.id) OR !(NEW.ticketFk <=> OLD.ticketFk) @@ -35427,11 +35558,16 @@ BEGIN WHERE saleFk = NEW.id; END IF; + SELECT account.myUser_getName() INTO vUserRole; + SELECT account.user_getMysqlRole(vUserRole) INTO vUserRole; + IF !(OLD.quantity <=> NEW.quantity) THEN SELECT COUNT(*) INTO vIsToSendMail FROM vncontrol.inter i JOIN vn.state s ON s.id = i.state_id - WHERE s.code='PACKED' AND i.Id_Ticket = OLD.ticketFk + WHERE s.code='PACKED' + AND i.Id_Ticket = OLD.ticketFk + AND vUserRole IN ('salesPerson', 'salesBoss') LIMIT 1; IF vIsToSendMail THEN @@ -35469,6 +35605,17 @@ BEGIN END IF; + IF !(NEW.quantity <=> OLD.quantity) THEN + INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) + SELECT r.id + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.route r ON r.id = t.routeFk + WHERE r.isOk = FALSE + AND s.id = NEW.id + AND r.created >= CURDATE() + GROUP BY r.id; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -35484,19 +35631,53 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`sale_BEFORE_DELETE` BEFORE DELETE ON `sale` FOR EACH ROW +BEGIN + IF OLD.quantity > 0 THEN + INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) + SELECT r.id + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.route r ON r.id = t.routeFk + WHERE r.isOk = FALSE + AND s.id = OLD.id + AND r.created >= CURDATE() + GROUP BY r.id; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `sale_afterDelete` AFTER DELETE ON `sale` FOR EACH ROW BEGIN DECLARE vIsToSendMail BOOL; + DECLARE vUserRole VARCHAR(255); CALL stock.log_add('sale', NULL, OLD.id); CALL ticket_requestRecalc(OLD.ticketFk); + SELECT account.myUser_getName() INTO vUserRole; + SELECT account.user_getMysqlRole(vUserRole) INTO vUserRole; + SELECT COUNT(*) INTO vIsToSendMail FROM vncontrol.inter i JOIN vn.state s ON s.id = i.state_id - WHERE s.code='PACKED' AND i.Id_Ticket = OLD.ticketFk + WHERE s.code='PACKED' + AND i.Id_Ticket = OLD.ticketFk + AND vUserRole IN ('salesPerson', 'salesBoss') LIMIT 1; IF vIsToSendMail THEN @@ -35686,13 +35867,34 @@ SET character_set_client = utf8; SET character_set_client = @saved_cs_client; -- --- Table structure for table `saleItemShelving` +-- Table structure for table `saleGoal` -- -DROP TABLE IF EXISTS `saleItemShelving`; +DROP TABLE IF EXISTS `saleGoal`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `saleItemShelving` ( +CREATE TABLE `saleGoal` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `rank` smallint(6) NOT NULL, + `walletWeightFrom` int(11) NOT NULL, + `walletWeightTo` int(11) DEFAULT NULL, + `goal` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, + `goalType` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, + `amount` int(11) DEFAULT NULL, + `month` int(11) DEFAULT NULL, + `year` int(11) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `saleItemShelving__` +-- + +DROP TABLE IF EXISTS `saleItemShelving__`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `saleItemShelving__` ( `id` int(11) NOT NULL AUTO_INCREMENT, `saleFk` int(11) NOT NULL, `itemShelvingFk` int(10) unsigned NOT NULL, @@ -35714,7 +35916,7 @@ DROP TABLE IF EXISTS `saleMistake`; CREATE TABLE `saleMistake` ( `id` int(11) NOT NULL AUTO_INCREMENT, `saleFk` int(11) NOT NULL, - `userFk` int(11) NOT NULL, + `userFk` int(10) unsigned NOT NULL, `typeFk` int(11) NOT NULL, `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), @@ -36056,7 +36258,7 @@ CREATE TABLE `sector` ( `isMain` tinyint(1) NOT NULL DEFAULT '0', `itemPackingTypeFk` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, `workerFk` int(11) DEFAULT NULL, - `labelReport` tinyint(3) DEFAULT NULL, + `labelReport__` tinyint(3) DEFAULT NULL, `printerFk` tinyint(3) unsigned DEFAULT NULL, PRIMARY KEY (`id`,`warehouseFk`), UNIQUE KEY `code_UNIQUE` (`code`), @@ -36076,10 +36278,10 @@ DROP TABLE IF EXISTS `sharingCart`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `sharingCart` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, `started` date NOT NULL, `ended` date NOT NULL, - `workerSubstitute` int(11) NOT NULL, + `workerSubstitute` int(10) unsigned NOT NULL, `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `workerFk_UNIQUE` (`workerFk`,`started`,`ended`,`workerSubstitute`), @@ -36175,8 +36377,8 @@ DROP TABLE IF EXISTS `sharingCartDaily`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `sharingCartDaily` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `ownerFk` int(11) NOT NULL, - `substituteFk` int(11) NOT NULL, + `ownerFk` int(10) unsigned NOT NULL, + `substituteFk` int(10) unsigned NOT NULL, `dated` date NOT NULL, `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`), @@ -36196,7 +36398,7 @@ DROP TABLE IF EXISTS `sharingClient`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `sharingClient` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, `started` date NOT NULL, `ended` date NOT NULL, `clientFk` int(11) NOT NULL, @@ -36259,7 +36461,7 @@ CREATE TABLE `shelving` ( `isPrinted` tinyint(4) NOT NULL DEFAULT '0', `priority` int(11) DEFAULT NULL, `parked` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `userFk` int(11) DEFAULT NULL, + `userFk` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`code`), KEY `shelving_fk1_idx` (`parkingFk`), KEY `shelving_fk2_idx` (`userFk`), @@ -36270,9 +36472,34 @@ CREATE TABLE `shelving` ( /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER shelving_beforeInsert BEFORE INSERT ON shelving FOR EACH ROW + +BEGIN + + IF NEW.code = "" THEN + + CALL util.throw('NOT_EMPTY_CODE_ALLOWED'); + + END IF; + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -36289,6 +36516,12 @@ BEGIN WHERE sh.`code` = OLD.`code`; END IF; + + IF NEW.code = "" THEN + + CALL util.throw('NOT_EMPTY_CODE_ALLOWED'); + + END IF; END */;; DELIMITER ; @@ -36312,7 +36545,7 @@ CREATE TABLE `sinister` ( `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `insureRate` decimal(3,2) NOT NULL DEFAULT '0.75', `isBooked` tinyint(4) NOT NULL DEFAULT '0', - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, `companyFk` smallint(5) unsigned NOT NULL, PRIMARY KEY (`id`), KEY `sinister_fk1_idx` (`supplierFk`), @@ -36340,7 +36573,7 @@ CREATE TABLE `sinisterDetail` ( `amountIn` decimal(10,2) DEFAULT NULL, `amountOut` decimal(10,2) DEFAULT NULL, `isConciliated` tinyint(1) NOT NULL DEFAULT '0', - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, `bankFk` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `sinisterDetail_fk1_idx` (`sinisterFk`), @@ -36363,11 +36596,8 @@ CREATE TABLE `smartTag` ( `code` varchar(12) CHARACTER SET utf8 NOT NULL, `shelvingFk` varchar(10) CHARACTER SET utf8 DEFAULT NULL, `level` int(11) DEFAULT NULL, - `ticketFk` int(11) DEFAULT NULL, - KEY `ticket_fk` (`ticketFk`), KEY `smartTag_shelving_fk` (`shelvingFk`), - CONSTRAINT `smartTag_shelving_fk` FOREIGN KEY (`shelvingFk`) REFERENCES `shelving` (`code`) ON UPDATE CASCADE, - CONSTRAINT `smartTag_ticket_fk` FOREIGN KEY (`ticketFk`) REFERENCES `ticketCollection` (`ticketFk`) ON DELETE CASCADE ON UPDATE CASCADE + CONSTRAINT `smartTag_shelving_fk` FOREIGN KEY (`shelvingFk`) REFERENCES `shelving` (`code`) ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -36426,7 +36656,7 @@ CREATE TABLE `solunionCAP` ( CONSTRAINT `solunionCAP` FOREIGN KEY (`creditInsurance`) REFERENCES `creditInsurance` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -36448,8 +36678,8 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -36478,8 +36708,8 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -36501,7 +36731,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; -- -- Table structure for table `sorter` @@ -36604,6 +36834,29 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +-- +-- Table structure for table `specieGeoInvasive` +-- + +DROP TABLE IF EXISTS `specieGeoInvasive`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `specieGeoInvasive` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `genusFk` int(11) NOT NULL, + `specieFk` int(11) NOT NULL, + `zoneGeofk` int(11) NOT NULL, + `isForbidden` tinyint(1) NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + KEY `specieGeoInvasive_FK` (`genusFk`), + KEY `specieGeoInvasive_FK_1` (`specieFk`), + KEY `specieGeoInvasive_FK_2` (`zoneGeofk`), + CONSTRAINT `specieGeoInvasive_FK` FOREIGN KEY (`genusFk`) REFERENCES `genus` (`id`) ON UPDATE CASCADE, + CONSTRAINT `specieGeoInvasive_FK_1` FOREIGN KEY (`specieFk`) REFERENCES `specie` (`id`) ON UPDATE CASCADE, + CONSTRAINT `specieGeoInvasive_FK_2` FOREIGN KEY (`zoneGeofk`) REFERENCES `zoneGeo` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Esta tabla recoge las prohibiciones de comerciar con especies invasoras de acuerdo con el Catálogo de Especies Exóticas Invasoras publicado por el Estado Español'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `starredModule` -- @@ -36613,8 +36866,9 @@ DROP TABLE IF EXISTS `starredModule`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `starredModule` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `workerFk` int(10) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, `moduleFk` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `position` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `starred_workerFk` (`workerFk`), KEY `starred_moduleFk` (`moduleFk`), @@ -36648,7 +36902,9 @@ CREATE TABLE `state` ( `isNotValidated` tinyint(1) DEFAULT '0' COMMENT 'Los tienen que ser validados por un comercial para prepararse', PRIMARY KEY (`id`), UNIQUE KEY `code_UNIQUE` (`code`), - KEY `state_id3` (`semaphore`) + KEY `state_id3` (`semaphore`), + KEY `alertLevel` (`alertLevel`), + CONSTRAINT `state_ibfk_1` FOREIGN KEY (`alertLevel`) REFERENCES `alertLevel` (`id`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -36725,7 +36981,7 @@ CREATE TABLE `supplier` ( `withholdingSageFk` smallint(6) DEFAULT NULL COMMENT 'Tipos de retención SAGE', `transactionTypeSageFk` tinyint(4) DEFAULT NULL COMMENT 'Ti po de transacción SAGE', `isTrucker` tinyint(1) NOT NULL DEFAULT '0', - `workerFk` int(11) DEFAULT NULL COMMENT 'Responsible for approving invoices', + `workerFk` int(10) unsigned DEFAULT NULL COMMENT 'Responsible for approving invoices', `supplierActivityFk` varchar(45) NOT NULL DEFAULT 'flowersPlants', `healthRegister` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`), @@ -36820,6 +37076,29 @@ CREATE TABLE `supplierActivity` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `supplierAddress` +-- + +DROP TABLE IF EXISTS `supplierAddress`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `supplierAddress` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `supplierFk` int(11) DEFAULT NULL, + `nickname` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL, + `street` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `provinceFk` smallint(6) unsigned DEFAULT NULL, + `postalCode` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + `city` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `phone` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, + `mobile` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `supplierAddress_province_fk` (`provinceFk`), + CONSTRAINT `supplierAddress_province_fk` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `supplierContact` -- @@ -36898,7 +37177,7 @@ CREATE TABLE `supplierLog` ( KEY `supplierLog_ibfk_2` (`userFk`), CONSTRAINT `supplierLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `supplier` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `supplierLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -36918,7 +37197,8 @@ SET character_set_client = utf8; `landed` tinyint NOT NULL, `out` tinyint NOT NULL, `in` tinyint NOT NULL, - `almacen` tinyint NOT NULL + `almacen` tinyint NOT NULL, + `cost` tinyint NOT NULL ) ENGINE=MyISAM */; SET character_set_client = @saved_cs_client; @@ -37144,6 +37424,21 @@ CREATE TABLE `taxType` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `temperature` +-- + +DROP TABLE IF EXISTS `temperature`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `temperature` ( + `code` varchar(10) CHARACTER SET utf8 NOT NULL, + `description` text COLLATE utf8_unicode_ci, + `name` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `thermograph` -- @@ -37172,7 +37467,7 @@ CREATE TABLE `ticket` ( `shipped` datetime NOT NULL, `nickname` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, `notes` longtext COLLATE utf8_unicode_ci, - `refFk` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, + `refFk` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, `invoiceOutFk` int(10) unsigned DEFAULT NULL COMMENT 'eliminar', `isBooked` tinyint(1) NOT NULL DEFAULT '0', `addressFk` int(11) NOT NULL DEFAULT '0', @@ -37196,7 +37491,7 @@ CREATE TABLE `ticket` ( `isBoxed` tinyint(2) NOT NULL DEFAULT '0', `isDeleted` tinyint(2) NOT NULL DEFAULT '0', `zoneFk` int(11) DEFAULT NULL, - `collectionFk` int(11) DEFAULT NULL, + `collectionFk__` int(11) DEFAULT NULL, `zonePrice` decimal(10,2) DEFAULT NULL, `zoneBonus` decimal(10,2) DEFAULT NULL, `totalWithVat` decimal(10,2) DEFAULT NULL COMMENT 'cache calculada del total con iva', @@ -37213,15 +37508,15 @@ CREATE TABLE `ticket` ( KEY `warehouse_date` (`warehouseFk`,`shipped`), KEY `Fecha` (`shipped`,`clientFk`), KEY `tickets_zone_fk_idx` (`zoneFk`), - KEY `tickets_fk11_idx` (`collectionFk`), + KEY `tickets_fk11_idx` (`collectionFk__`), + CONSTRAINT `ticket_FK` FOREIGN KEY (`refFk`) REFERENCES `invoiceOut` (`ref`) ON UPDATE CASCADE, CONSTRAINT `ticket_customer_id` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE, CONSTRAINT `ticket_ibfk_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, CONSTRAINT `ticket_ibfk_5` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE, CONSTRAINT `ticket_ibfk_6` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON UPDATE CASCADE, CONSTRAINT `ticket_ibfk_8` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`), CONSTRAINT `ticket_ibfk_9` FOREIGN KEY (`routeFk`) REFERENCES `route` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, - CONSTRAINT `tickets_fk10` FOREIGN KEY (`refFk`) REFERENCES `invoiceOut` (`ref`) ON UPDATE CASCADE, - CONSTRAINT `tickets_fk11` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `tickets_fk11` FOREIGN KEY (`collectionFk__`) REFERENCES `collection` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `tickets_zone_fk` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -37268,16 +37563,7 @@ BEGIN VALUES(NEW.clientFk, IFNULL(vTransferorFirstShipped, CURDATE()), CURDATE()) ON DUPLICATE KEY UPDATE lastShipped = CURDATE(); END IF; - - IF NEW.clientFk = 2067 THEN - -- Fallo que se insertan no se sabe como tickets en este cliente - INSERT INTO vn.mail SET - `sender` = 'jgallego@verdnatura.es', - `replyTo` = 'jgallego@verdnatura.es', - `subject` = 'Creado ticket al cliente 2067', - `body` = CONCAT(account.myUserGetName(), ' ha creado el ticket ', - NEW.id); - END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -37298,6 +37584,17 @@ DELIMITER ;; FOR EACH ROW BEGIN DECLARE vNewTime TIME; + + IF !(NEW.routeFk <=> OLD.routeFk) THEN + INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) + SELECT r.id + FROM vn.route r + WHERE r.isOk = FALSE + AND r.id IN (OLD.routeFk,NEW.routeFk) + AND r.created >= CURDATE() + GROUP BY r.id; + END IF; + IF !(NEW.shipped <=> OLD.shipped) THEN IF YEAR(NEW.shipped) < 2000 THEN SIGNAL SQLSTATE '46000' @@ -37310,6 +37607,14 @@ BEGIN END IF; IF !(NEW.isDeleted <=> OLD.isDeleted) AND NEW.isDeleted THEN + INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) + SELECT r.id + FROM vn.ticket t + JOIN vn.route r ON r.id = t.routeFk + WHERE r.isOk = FALSE + AND t.id = NEW.id + AND r.created >= 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'); SET NEW.routeFk = NULL; @@ -37340,6 +37645,8 @@ BEGIN INSERT IGNORE INTO zoneAgencyMode (agencyModeFk,zoneFk) SELECT r.agencyModeFk, NEW.zoneFk FROM route r WHERE r.id = NEW.routeFk; + + CALL vn.routeUpdateM3(NEW.routeFk); END IF; END */;; DELIMITER ; @@ -37360,6 +37667,10 @@ DELIMITER ;; AFTER UPDATE ON `ticket` FOR EACH ROW BEGIN + /** + * Hay una versión en salix que machacará toda esta función/procedimiento avisa + * a jgallego de los cambios que quieres hacer. + */ IF !(NEW.id <=> OLD.id) OR !(NEW.warehouseFk <=> OLD.warehouseFk) OR !(NEW.shipped <=> OLD.shipped) THEN @@ -37400,9 +37711,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -37410,6 +37721,14 @@ DELIMITER ;; BEFORE DELETE ON `ticket` FOR EACH ROW BEGIN + INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) + SELECT r.id + FROM vn.route r + WHERE r.isOk = FALSE + AND r.id = OLD.routeFk + AND r.created >= CURDATE() + GROUP BY r.id; + DELETE FROM sale WHERE ticketFk = OLD.id; DELETE FROM ticketDms WHERE ticketFk = OLD.id; @@ -37603,6 +37922,28 @@ SET character_set_client = utf8; ) ENGINE=MyISAM */; SET character_set_client = @saved_cs_client; +-- +-- Temporary table structure for view `ticketLabel_Source` +-- + +DROP TABLE IF EXISTS `ticketLabel_Source`; +/*!50001 DROP VIEW IF EXISTS `ticketLabel_Source`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE TABLE `ticketLabel_Source` ( + `level` tinyint NOT NULL, + `Id_Ticket` tinyint NOT NULL, + `Agencia` tinyint NOT NULL, + `Id_Cliente` tinyint NOT NULL, + `Notas` tinyint NOT NULL, + `Sacador` tinyint NOT NULL, + `ncarro` tinyint NOT NULL, + `horaagencia` tinyint NOT NULL, + `fecha` tinyint NOT NULL, + `urgente` tinyint NOT NULL +) ENGINE=MyISAM */; +SET character_set_client = @saved_cs_client; + -- -- Table structure for table `ticketLastState` -- @@ -37649,6 +37990,21 @@ SET character_set_client = utf8; ) ENGINE=MyISAM */; SET character_set_client = @saved_cs_client; +-- +-- Temporary table structure for view `ticketLocation` +-- + +DROP TABLE IF EXISTS `ticketLocation`; +/*!50001 DROP VIEW IF EXISTS `ticketLocation`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE TABLE `ticketLocation` ( + `ticketFk` tinyint NOT NULL, + `longitude` tinyint NOT NULL, + `latitude` tinyint NOT NULL +) ENGINE=MyISAM */; +SET character_set_client = @saved_cs_client; + -- -- Table structure for table `ticketLog` -- @@ -37771,7 +38127,7 @@ CREATE TABLE `ticketPackaging` ( `quantity` int(10) DEFAULT '0', `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `pvp` double DEFAULT NULL, - `workerFk` int(11) DEFAULT NULL, + `workerFk` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), KEY `ticketPackaging_fk1_idx` (`ticketFk`), KEY `ticketPackaging_fk2_idx` (`packagingFk`), @@ -37841,7 +38197,8 @@ SET character_set_client = utf8; `province` tinyint NOT NULL, `itemFk` tinyint NOT NULL, `concept` tinyint NOT NULL, - `quantity` tinyint NOT NULL + `quantity` tinyint NOT NULL, + `litros` tinyint NOT NULL ) ENGINE=MyISAM */; SET character_set_client = @saved_cs_client; @@ -37948,8 +38305,8 @@ CREATE TABLE `ticketRequest` ( `saleFk` int(11) DEFAULT NULL, `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `isOk` tinyint(1) DEFAULT NULL, - `requesterFk` int(11) DEFAULT NULL, - `attenderFk` int(11) DEFAULT NULL, + `requesterFk` int(10) unsigned DEFAULT NULL, + `attenderFk` int(10) unsigned DEFAULT NULL, `ticketFk` int(11) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `Id_Movimiento_UNIQUE` (`saleFk`), @@ -38048,6 +38405,69 @@ CREATE TABLE `ticketService` ( CONSTRAINT `ticketService_ticketServiceType` FOREIGN KEY (`ticketServiceTypeFk`) REFERENCES `ticketServiceType` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Servicios asociadas a un ticket'; /*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`ticketService_ai` AFTER INSERT ON `ticketService` FOR EACH ROW +BEGIN + + CALL ticket_requestRecalc(NEW.ticketFk); + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`ticketService_au` AFTER UPDATE ON `ticketService` FOR EACH ROW +BEGIN + IF !(NEW.price <=> OLD.price) + OR !(NEW.ticketFk <=> OLD.ticketFk) + OR !(NEW.quantity <=> OLD.quantity) THEN + CALL ticket_requestRecalc(NEW.ticketFk); + CALL ticket_requestRecalc(OLD.ticketFk); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`ticketService_ad` AFTER DELETE ON `ticketService` FOR EACH ROW +BEGIN + + CALL ticket_requestRecalc(OLD.ticketFk); + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; -- -- Table structure for table `ticketServiceType` @@ -38192,7 +38612,7 @@ CREATE TABLE `till` ( `in` decimal(10,2) DEFAULT NULL, `out` decimal(10,2) DEFAULT NULL, `bankFk` int(11) DEFAULT '1', - `workerFk` int(11) DEFAULT NULL, + `workerFk` int(10) unsigned DEFAULT NULL, `companyFk` smallint(5) unsigned DEFAULT '442' COMMENT 'kakear', `isLinked` tinyint(4) DEFAULT '0', `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, @@ -38512,7 +38932,7 @@ DROP TABLE IF EXISTS `trainingCourse`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `trainingCourse` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, `trainingCourseTypeFk` int(11) NOT NULL, `centerFk` int(11) DEFAULT NULL, `started` datetime NOT NULL, @@ -38736,12 +39156,15 @@ CREATE TABLE `travelThermograph` ( `temperature` enum('COOL','WARM') COLLATE utf8_unicode_ci NOT NULL, `result` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, `dmsFk` int(11) DEFAULT NULL, + `temperatureFk` varchar(10) CHARACTER SET utf8 DEFAULT NULL COMMENT 'En la versión de Agosto de Salix se empezará a usar este campo y se actualizaran los anteriores mirando temperature.', PRIMARY KEY (`id`), KEY `thermograph_fk_idx` (`thermographFk`), KEY `gestdoc_fk_idx` (`dmsFk`), KEY `travel_id` (`travelFk`), KEY `warehouse_id` (`warehouseFk`), + KEY `travelThermographTemperatureFgn` (`temperatureFk`), CONSTRAINT `travelThermographDmsFgn` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) 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`), CONSTRAINT `travelThermographWarehouseFgn` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE @@ -38757,7 +39180,7 @@ DROP TABLE IF EXISTS `trolley`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `trolley` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `workerFk` int(11) DEFAULT NULL, + `workerFk` int(10) unsigned DEFAULT NULL, `coupled` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), KEY `trolley_FK` (`workerFk`), @@ -38880,6 +39303,7 @@ CREATE TABLE `vehicle` ( `warehouseFk` smallint(6) unsigned DEFAULT NULL, `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, `deliveryPointFk` int(11) DEFAULT NULL, + `isKmTruckRate` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'Computar km como camión en el cálculo de salario de reparto', PRIMARY KEY (`id`), KEY `empresa_id` (`companyFk`), KEY `provinceFk_idx` (`warehouseFk`), @@ -38890,6 +39314,45 @@ CREATE TABLE `vehicle` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `vehicleWarehouse` +-- + +DROP TABLE IF EXISTS `vehicleWarehouse`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `vehicleWarehouse` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `numberPlate` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + `model` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, + `tradeMark` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, + `numberSerial` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `vehicleWarehouse_UN` (`numberPlate`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Registros de vehículos utilizados en almacén'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `vehicleWarehouseTimeControl` +-- + +DROP TABLE IF EXISTS `vehicleWarehouseTimeControl`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `vehicleWarehouseTimeControl` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `workerFk` int(10) unsigned NOT NULL, + `vehicleWarehouseFk` int(10) unsigned DEFAULT NULL, + `timed` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `direction` enum('in','out') COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `vehicleWarehouseTimeControl_worker_idx` (`workerFk`), + KEY `vehicleWarehouseTimeControl_FK` (`vehicleWarehouseFk`), + CONSTRAINT `vehicleWarehouseTimeControl_FK` FOREIGN KEY (`vehicleWarehouseFk`) REFERENCES `vehicleWarehouse` (`id`) ON UPDATE CASCADE, + CONSTRAINT `vehicleWarehouseTimeControl_worker` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_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 `volumeConfig` -- @@ -38898,13 +39361,14 @@ DROP TABLE IF EXISTS `volumeConfig`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `volumeConfig` ( - `espai` decimal(10,2) DEFAULT NULL COMMENT 'metros cúbicos', - `carro` decimal(10,2) DEFAULT NULL COMMENT 'metros cúbicos', + `palletM3` decimal(10,2) DEFAULT NULL COMMENT 'metros cúbicos', + `trolleyM3` decimal(10,2) DEFAULT NULL COMMENT 'metros cúbicos', `dutchCompressionRate` double NOT NULL DEFAULT '1', `standardFlowerBox` int(11) NOT NULL COMMENT 'en litros', `minCompressionRate` decimal(10,2) DEFAULT '0.30' COMMENT 'minimo permitido por la empresa', `ccLength` int(11) NOT NULL DEFAULT '130' COMMENT 'longitud útil para la carga de un CC, en cm', - `ccWidth` int(11) NOT NULL DEFAULT '60' COMMENT 'ancho útil para la carga en un CC, en cm' + `ccWidth` int(11) NOT NULL DEFAULT '60' COMMENT 'ancho útil para la carga en un CC, en cm', + `sorterPallet_m3` decimal(5,1) NOT NULL DEFAULT '2.0' COMMENT 'volumen minimo para extraer pallet del sorter' ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='almacena el valor standard para volumenes convencionales de Verdnatura, en metros cúbicos'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -38953,6 +39417,7 @@ DROP TABLE IF EXISTS `warehouse`; CREATE TABLE `warehouse` ( `id` smallint(6) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL, + `code` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, `isFeedStock` tinyint(1) unsigned NOT NULL DEFAULT '0', `addressName` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, `delay` double NOT NULL DEFAULT '0.004', @@ -39091,7 +39556,7 @@ DROP TABLE IF EXISTS `worker`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `worker` ( - `id` int(11) NOT NULL AUTO_INCREMENT, + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `code` varchar(3) COLLATE utf8_unicode_ci NOT NULL, `firstName` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, `lastName` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, @@ -39106,7 +39571,7 @@ CREATE TABLE `worker` ( `ended__` datetime DEFAULT NULL, `notes__` varchar(254) COLLATE utf8_unicode_ci DEFAULT NULL, `photo` blob, - `fi` varchar(9) COLLATE utf8_unicode_ci DEFAULT NULL, + `fi__` varchar(9) COLLATE utf8_unicode_ci DEFAULT NULL, `address__` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `birthed__` date NOT NULL, `maritalStatus__` enum('soltero/a','casado/a') COLLATE utf8_unicode_ci NOT NULL, @@ -39127,7 +39592,7 @@ CREATE TABLE `worker` ( KEY `sub` (`sub`), KEY `boss_idx` (`bossFk`), CONSTRAINT `Clientes` FOREIGN KEY (`clientFk__`) REFERENCES `client` (`id`) ON UPDATE CASCADE, - CONSTRAINT `worker_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE + CONSTRAINT `worker_ibfk_1` FOREIGN KEY (`id`) REFERENCES `account`.`user` (`id`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -39140,8 +39605,8 @@ DROP TABLE IF EXISTS `workerBosses`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `workerBosses` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `workerFk` int(11) NOT NULL, - `bossFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, + `bossFk` int(10) unsigned NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `workerFk_UNIQUE` (`workerFk`,`bossFk`), KEY `fg_worker_worker_idx` (`workerFk`), @@ -39211,7 +39676,7 @@ DROP TABLE IF EXISTS `workerConfig__`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `workerConfig__` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `defaultWorkerFk` int(11) NOT NULL, + `defaultWorkerFk` int(10) unsigned NOT NULL, PRIMARY KEY (`id`), KEY `defaultWorkerFk` (`defaultWorkerFk`), CONSTRAINT `workerConfig___ibfk_1` FOREIGN KEY (`defaultWorkerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE @@ -39240,7 +39705,7 @@ DROP TABLE IF EXISTS `workerDisableExcluded`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `workerDisableExcluded` ( - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, `dated` date DEFAULT NULL, PRIMARY KEY (`workerFk`), CONSTRAINT `workerDisableExcludedFk1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE @@ -39256,7 +39721,7 @@ DROP TABLE IF EXISTS `workerDistributionCategory`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `workerDistributionCategory` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, `category` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `workerDistributionCategory_workerFk_idx` (`workerFk`), @@ -39324,7 +39789,7 @@ DROP TABLE IF EXISTS `workerIrpf`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `workerIrpf` ( - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, `spouseNif` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, `geographicMobilityDate` date DEFAULT NULL, `disabilityGradeFk` int(11) DEFAULT NULL, @@ -39372,7 +39837,10 @@ CREATE TABLE `workerJourney` ( PRIMARY KEY (`id`), UNIQUE KEY `userFk_UNIQUE` (`userFk`,`dated`), KEY `fk_workerJourney_user_idx` (`userFk`), - CONSTRAINT `fk_workerJourney_user` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE + KEY `workerJourney_businessFk_idx` (`businessFk`), + KEY `workerJourney_dated_idx` (`dated`), + CONSTRAINT `fk_workerJourney_user` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE, + CONSTRAINT `workerJourney_businessFk` FOREIGN KEY (`businessFk`) REFERENCES `postgresql`.`business` (`business_id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -39403,7 +39871,7 @@ DROP TABLE IF EXISTS `workerLog`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `workerLog` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `originFk` int(11) NOT NULL, + `originFk` int(10) unsigned NOT NULL, `userFk` int(10) unsigned NOT NULL, `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, @@ -39429,7 +39897,7 @@ DROP TABLE IF EXISTS `workerMana`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `workerMana` ( - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, `size` int(11) NOT NULL DEFAULT '300', `amount` int(11) NOT NULL DEFAULT '0', `pricesModifierRate` double NOT NULL DEFAULT '0', @@ -39450,7 +39918,7 @@ DROP TABLE IF EXISTS `workerManaExcluded`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `workerManaExcluded` ( - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, PRIMARY KEY (`workerFk`), CONSTRAINT `mana_spellers_excluded_fk1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Usuarios que tienen que estar excluidos del cálculo del maná'; @@ -39498,7 +39966,7 @@ DROP TABLE IF EXISTS `workerRelatives`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `workerRelatives` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, `isDescendant` tinyint(1) DEFAULT '1' COMMENT 'Descendientes - Ascendientes', `disabilityGradeFk` int(11) DEFAULT NULL, `birthed` int(4) NOT NULL, @@ -39523,7 +39991,7 @@ DROP TABLE IF EXISTS `workerShelving`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `workerShelving` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, `shelvingFk` varchar(10) CHARACTER SET utf8 NOT NULL, `collectionFk` int(11) DEFAULT NULL, `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, @@ -39531,10 +39999,10 @@ CREATE TABLE `workerShelving` ( KEY `workerShelving_shelving_fk` (`shelvingFk`), KEY `workerShelving_FK` (`workerFk`), KEY `workerShelving_FK_1` (`collectionFk`), - CONSTRAINT `workerShelving_collection_fk` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`), + CONSTRAINT `workerShelving_FK` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `workerShelving_shelving_fk` FOREIGN KEY (`shelvingFk`) REFERENCES `shelving` (`code`) ON UPDATE CASCADE, CONSTRAINT `workerShelving_worker_fk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='utilizaremos el id para establecer la prioridad de los carros a asignar'; +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='utilizaremos el id para establecer la prioridad de los carros a asignar'; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -39634,13 +40102,13 @@ CREATE TABLE `workerTimeControl` ( /*!40101 SET character_set_client = @saved_cs_client */; -- --- Table structure for table `workerTimeControlConfig` +-- Table structure for table `workerTimeControlConfig_` -- -DROP TABLE IF EXISTS `workerTimeControlConfig`; +DROP TABLE IF EXISTS `workerTimeControlConfig_`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `workerTimeControlConfig` ( +CREATE TABLE `workerTimeControlConfig_` ( `id` int(11) NOT NULL AUTO_INCREMENT, `warehouseFk` smallint(6) unsigned NOT NULL, `host` varchar(45) COLLATE utf8_unicode_ci NOT NULL, @@ -39675,7 +40143,7 @@ DROP TABLE IF EXISTS `workerTimeControlMail`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `workerTimeControlMail` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `workerFk` int(10) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, `year` int(4) NOT NULL, `week` int(2) NOT NULL, `state` enum('SENDED','CONFIRMED','REVISE') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'SENDED', @@ -39723,7 +40191,7 @@ DROP TABLE IF EXISTS `workerTimeControlPin`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `workerTimeControlPin` ( - `workerFk` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, `pin` varchar(255) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`workerFk`), CONSTRAINT `workerFk_.1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE @@ -39822,6 +40290,37 @@ SET character_set_client = utf8; ) ENGINE=MyISAM */; SET character_set_client = @saved_cs_client; +-- +-- Temporary table structure for view `workerWithoutDevice` +-- + +DROP TABLE IF EXISTS `workerWithoutDevice`; +/*!50001 DROP VIEW IF EXISTS `workerWithoutDevice`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE TABLE `workerWithoutDevice` ( + `workerFk` tinyint NOT NULL, + `Trabajador` tinyint NOT NULL, + `Colecciones` tinyint NOT NULL +) ENGINE=MyISAM */; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary table structure for view `workerWithoutTractor` +-- + +DROP TABLE IF EXISTS `workerWithoutTractor`; +/*!50001 DROP VIEW IF EXISTS `workerWithoutTractor`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE TABLE `workerWithoutTractor` ( + `workerFk` tinyint NOT NULL, + `Trabajador` tinyint NOT NULL, + `Colecciones` tinyint NOT NULL, + `created` tinyint NOT NULL +) ENGINE=MyISAM */; +SET character_set_client = @saved_cs_client; + -- -- Table structure for table `workers20190711` -- @@ -39996,7 +40495,7 @@ CREATE TABLE `workingHours` ( CONSTRAINT `user_working_hour` FOREIGN KEY (`userId`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena horas de Entrada y de Salida del personal'; /*!40101 SET character_set_client = @saved_cs_client */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -40017,7 +40516,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; -- -- Table structure for table `zone` @@ -40153,12 +40652,78 @@ CREATE TABLE `zoneExclusion` ( `id` int(11) NOT NULL AUTO_INCREMENT, `zoneFk` int(11) NOT NULL, `dated` date NOT NULL, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `userFk` int(11) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `zoneFk_2` (`zoneFk`,`dated`), KEY `zoneFk` (`zoneFk`), CONSTRAINT `zoneExclusion_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER zoneExclusion_BI +BEFORE INSERT +ON zoneExclusion FOR EACH ROW +BEGIN + + SET NEW.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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER zoneExclusion_BU +BEFORE UPDATE +ON zoneExclusion FOR EACH ROW +BEGIN + + SET NEW.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 */ ; + +-- +-- Table structure for table `zoneFilter` +-- + +DROP TABLE IF EXISTS `zoneFilter`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `zoneFilter` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `zoneFk` int(11) NOT NULL, + `sizeMax` int(11) DEFAULT NULL COMMENT 'altura máxima en cm', + `itemTypeFk` smallint(5) unsigned NOT NULL, + PRIMARY KEY (`id`), + KEY `zoneFilter_FK` (`zoneFk`), + KEY `zoneFilter_FK_1` (`itemTypeFk`), + CONSTRAINT `zoneFilter_FK` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `zoneFilter_FK_1` FOREIGN KEY (`itemTypeFk`) REFERENCES `itemType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='recoge los parámetros para filtrar determinados productos según la zona'; +/*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `zoneGeo` @@ -40169,7 +40734,7 @@ DROP TABLE IF EXISTS `zoneGeo`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `zoneGeo` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `type` set('country','province','town','postCode') CHARACTER SET utf8 NOT NULL, + `type` set('country','province','town','postCode','autonomy') CHARACTER SET utf8 NOT NULL, `name` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, `parentFk` int(10) unsigned DEFAULT NULL, `path` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, @@ -40317,6 +40882,7 @@ CREATE TABLE `zoneWarehouse` ( PRIMARY KEY (`id`), UNIQUE KEY `zoneFk` (`zoneFk`,`warehouseFk`), KEY `warehouseFk` (`warehouseFk`), + CONSTRAINT `zoneWarehouse_fk_warehouse` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, CONSTRAINT `zoneWarehouse_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; @@ -40412,14 +40978,14 @@ DELIMITER ;; /*!50003 SET @saved_cs_client = @@character_set_client */ ;; /*!50003 SET @saved_cs_results = @@character_set_results */ ;; /*!50003 SET @saved_col_connection = @@collation_connection */ ;; -/*!50003 SET character_set_client = utf8mb4 */ ;; -/*!50003 SET character_set_results = utf8mb4 */ ;; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ;; +/*!50003 SET character_set_client = utf8 */ ;; +/*!50003 SET character_set_results = utf8 */ ;; +/*!50003 SET collation_connection = utf8_general_ci */ ;; /*!50003 SET @saved_sql_mode = @@sql_mode */ ;; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; /*!50003 SET @saved_time_zone = @@time_zone */ ;; /*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `printQueue_check` ON SCHEDULE EVERY 10 MINUTE STARTS '2019-11-08 01:00:00' ON COMPLETION PRESERVE ENABLE COMMENT 'Notifica en caso de que el servidor de impresión este parado' DO BEGIN +/*!50106 CREATE*/ /*!50117 DEFINER=`z-sysadmin`@`%`*/ /*!50106 EVENT `printQueue_check` ON SCHEDULE EVERY 10 MINUTE STARTS '2019-11-08 01:00:00' ON COMPLETION PRESERVE ENABLE COMMENT 'Notifica en caso de que el servidor de impresión este parado' DO BEGIN DECLARE vCurrentCount INT; DECLARE vCheckSum INT; @@ -40431,7 +40997,7 @@ DELIMITER ;; SELECT CONCAT(' ', IFNULL(pq.id, ''), ' ', IFNULL(p.path, ''),' - ', IFNULL(ls.name, ''),' + ', IFNULL(lr.name, ''),' ', IFNULL(e.Estado, ''),' ', IFNULL(w.firstname, ''), " ", IFNULL(w.lastName, ''),' ', IFNULL(pq.`error`, ''),' @@ -40486,7 +41052,7 @@ DELIMITER ;; CLOSE vCur; INSERT INTO vn2008.mail (`to`, subject, text) - VALUES ('cau@verdnatura.es, sysadmin@verdnatura.es', + VALUES ('cau@verdnatura.es', 'servidor de impresion parado', CONCAT('Hay ', vCurrentCount, ' lineas bloqueadas', vTableQueue, '')); @@ -40509,6 +41075,24 @@ 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 `route_doRecalc` */;; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8 */ ;; +/*!50003 SET character_set_results = utf8 */ ;; +/*!50003 SET collation_connection = utf8_general_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `route_doRecalc` ON SCHEDULE EVERY 10 SECOND STARTS '2021-07-08 07:32:23' ON COMPLETION PRESERVE ENABLE DO CALL route_doRecalc */ ;; +/*!50003 SET time_zone = @saved_time_zone */ ;; +/*!50003 SET sql_mode = @saved_sql_mode */ ;; +/*!50003 SET character_set_client = @saved_cs_client */ ;; +/*!50003 SET character_set_results = @saved_cs_results */ ;; +/*!50003 SET collation_connection = @saved_col_connection */ ;; /*!50106 DROP EVENT IF EXISTS `sale_checkWithoutComponents` */;; DELIMITER ;; /*!50003 SET @saved_cs_client = @@character_set_client */ ;; @@ -40609,24 +41193,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 `zoneClosure_doRecalc` */;; -DELIMITER ;; -/*!50003 SET @saved_cs_client = @@character_set_client */ ;; -/*!50003 SET @saved_cs_results = @@character_set_results */ ;; -/*!50003 SET @saved_col_connection = @@collation_connection */ ;; -/*!50003 SET character_set_client = utf8 */ ;; -/*!50003 SET character_set_results = utf8 */ ;; -/*!50003 SET collation_connection = utf8_general_ci */ ;; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;; -/*!50003 SET @saved_time_zone = @@time_zone */ ;; -/*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`salix`@`10.0.%.%`*/ /*!50106 EVENT `zoneClosure_doRecalc` ON SCHEDULE AT '2021-05-25 10:32:44' ON COMPLETION NOT PRESERVE DISABLE DO CALL zoneClosure_recalc */ ;; -/*!50003 SET time_zone = @saved_time_zone */ ;; -/*!50003 SET sql_mode = @saved_sql_mode */ ;; -/*!50003 SET character_set_client = @saved_cs_client */ ;; -/*!50003 SET character_set_results = @saved_cs_results */ ;; -/*!50003 SET collation_connection = @saved_col_connection */ ;; /*!50106 DROP EVENT IF EXISTS `zoneGeo_doCalc` */;; DELIMITER ;; /*!50003 SET @saved_cs_client = @@character_set_client */ ;; @@ -41146,13 +41712,13 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `clientGetDebt`(vClient INT, vDate DATE) RETURNS decimal(10,2) +CREATE DEFINER=`root`@`%` FUNCTION `clientGetDebt`(`vClient` INT, `vDate` DATE) RETURNS decimal(10,2) READS SQL DATA BEGIN /** @@ -41179,23 +41745,14 @@ BEGIN SET vDateIni = TIMESTAMPADD(MONTH, -2, CURDATE()); SET vDateEnd = TIMESTAMP(vDate, '23:59:59'); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - (INDEX (ticketFk)) - ENGINE = MEMORY - SELECT id ticketFk - FROM ticket - WHERE clientFk = vClient - AND refFk IS NULL - AND shipped BETWEEN vDateIni AND vDateEnd; - - CALL vn.ticketGetTotal; SELECT IFNULL(SUM(t.amount), 0) INTO vDebt FROM ( - SELECT SUM(IFNULL(total,0)) amount - FROM tmp.ticketTotal + SELECT SUM(IFNULL(totalWithVat,0)) amount + FROM ticket + WHERE clientFk = vClient + AND refFk IS NULL + AND shipped BETWEEN vDateIni AND vDateEnd UNION ALL SELECT SUM(amountPaid) amount FROM receipt @@ -41213,10 +41770,6 @@ BEGIN AND `status` = 'ok' ) t; - DROP TEMPORARY TABLE IF EXISTS - tmp.ticket, - tmp.ticketTotal; - RETURN vDebt; END ;; DELIMITER ; @@ -41716,9 +42269,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -41777,6 +42330,47 @@ BEGIN RETURN curRate; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `deviceProductionUser_accessGranted` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `deviceProductionUser_accessGranted`(vUserFK INT(10) , android_id VARCHAR(50)) RETURNS tinyint(1) + DETERMINISTIC +BEGIN + /* + * Comprueba si el usuario puede entrar en la aplicacion de almacen con ese movil + * + * */ + + DECLARE vIsGranted BOOLEAN; + DECLARE vDeviceProductionFk INT(11) DEFAULT NULL; + + SELECT dp.id INTO vDeviceProductionFk + FROM vn.deviceProduction dp + WHERE dp.android_id = android_id; + + IF vDeviceProductionFk THEN + + SELECT COUNT(*) INTO vIsGranted + FROM vn.deviceProductionUser dpu + WHERE dpu.userFk = vUserFK + AND dpu.deviceProductionFk = vDeviceProductionFk; + + RETURN vIsGranted; + END IF; + RETURN TRUE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -42191,6 +42785,50 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `expedition_checkRoute` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `expedition_checkRoute`(vPalletFk INT,vExpeditionFk INT) RETURNS tinyint(1) + DETERMINISTIC +BEGIN +/** +* Comprueba si las expediciones del pallet son todas +* de la misma ruta. +* +* @param vExpeditionFk numero de expedition a comprobar +* @param vPalletFk numero de pallet +* @return vHasDistinctRoutes +*/ + DECLARE vRouteFk INT; + DECLARE vHasDistinctRoutes BOOL; + + SELECT t.routeFk INTO vRouteFk + FROM vn.expedition e + JOIN vn.ticket t ON e.ticketFk = t.id + WHERE e.id = vExpeditionFk; + + SELECT COUNT(*) > 0 INTO vHasDistinctRoutes + FROM vn.expeditionScan es + JOIN vn.expedition e ON es.expeditionFk = e.id + JOIN vn.ticket t ON e.ticketFk = t.id + WHERE es.palletFk = vPalletFk + AND t.routeFk <> vRouteFk; + + RETURN vHasDistinctRoutes; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP FUNCTION IF EXISTS `floramondoNewItemFk__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -42570,7 +43208,7 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP FUNCTION IF EXISTS `getInventoryDate` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -42590,7 +43228,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 DROP FUNCTION IF EXISTS `getNewItemId` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -42886,7 +43524,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 DROP FUNCTION IF EXISTS `getUser` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -42911,7 +43549,7 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP FUNCTION IF EXISTS `getUserId` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -42936,7 +43574,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 DROP FUNCTION IF EXISTS `getWorkerCode` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -43164,45 +43802,6 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `hasZone__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `hasZone__`(vLanded DATE, vAddress INT, vAgencyModeFk INT) RETURNS tinyint(1) - DETERMINISTIC -BEGIN - DECLARE vHasZone BOOLEAN DEFAULT FALSE; - - SELECT COUNT(*), id zoneFk, isIncluded INTO vHasZone, @trash, @trash FROM ( - SELECT z.id, - TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, - vLanded landed, - zi.isIncluded - FROM zoneGeo zgSon - JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt - JOIN zoneIncluded zi ON zi.geoFk = zgFather.id - JOIN zone z ON z.id = zi.zoneFk - JOIN zoneCalendar zc ON zc.zoneFk = z.id - AND zc.delivered = vLanded - AND z.agencyModeFk = vAgencyModeFk - AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) - WHERE zi.isIncluded - ORDER BY z.id, landed ASC, zgFather.depth DESC) t - GROUP BY id - HAVING isIncluded > 0 LIMIT 1; - RETURN vHasZone; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP FUNCTION IF EXISTS `invoiceOutAmount` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -43707,6 +44306,7 @@ BEGIN DECLARE vDiameter INT; DECLARE vPackageFk VARCHAR(50); + DECLARE vCoeficient DOUBLE DEFAULT 1.08; SELECT MAX(LEFT(value,3)) INTO vDiameter FROM vn.itemTag it @@ -43714,7 +44314,7 @@ BEGIN WHERE it.itemFk = vItemFk AND t.overwrite = 'diameter'; - SELECT 8000 + (FLOOR(vc.ccLength / vDiameter) * FLOOR(vc.ccWidth / vDiameter)) + SELECT 8000 + FLOOR(vc.ccLength * vc.ccWidth / (vCoeficient * PI() * (vDiameter / 2) * (vDiameter / 2))) INTO vPackageFk FROM vn.volumeConfig vc; @@ -43771,6 +44371,76 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `machineWorker_Worker` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `machineWorker_Worker`(vWorkerFk VARCHAR(10)) RETURNS varchar(20) CHARSET utf8 COLLATE utf8_unicode_ci + READS SQL DATA +BEGIN +/** + * Comprueba si existen registros en las últimas 12 horas 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 REGISTERED/UNREGISTERED en caso de que haya registros + */ + + IF (SELECT COUNT(*) + FROM machineWorker m + WHERE m.workerFk = vWorkerFk + AND m.inTimed >= TIMESTAMPADD(HOUR , -12,NOW()) AND ISNULL(m.outTimed)) + THEN + RETURN "REGISTERED"; + ELSE + RETURN "UNREGISTERED"; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `machine_checkPlate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `machine_checkPlate`(vPlate VARCHAR(10)) RETURNS tinyint(1) + READS SQL DATA +BEGIN +/** + * Comprueba si existe matrícula + * + * @param vPlate matrícula del vehículo + * @return Devuelve TRUE en caso de que exista + * + */ + + IF (SELECT COUNT(*) + FROM machine m + WHERE m.plate = vPlate + ) THEN + RETURN TRUE; + ELSE + RETURN FALSE; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP FUNCTION IF EXISTS `messageSend` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -43882,7 +44552,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 DROP FUNCTION IF EXISTS `myWorker_getId__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -44235,6 +44905,266 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `smartTag_nextLevel` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `smartTag_nextLevel`(vShelvingFk VARCHAR(10)) RETURNS int(2) + DETERMINISTIC +BEGIN + + DECLARE vLevel INT; + + SELECT count(*) + 1 INTO vLevel + FROM smartTag st + WHERE st.shelvingFk = vShelvingFk COLLATE utf8_general_ci; + + RETURN vLevel; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `specie_IsForbidden` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `specie_IsForbidden`(vItemFk INT, vAddressFk INT) RETURNS tinyint(1) + READS SQL DATA +BEGIN + + DECLARE vIsForbbiden BOOL; + DECLARE vLeft INT; + + SELECT zg.lft INTO vLeft + FROM vn.address a + JOIN vn.zoneGeo zg ON zg.name = a.postalCode + WHERE a.id = vAddressFk; + + SELECT sgi.isForbidden INTO vIsForbbiden + FROM vn.specieGeoInvasive sgi + JOIN vn.zoneGeo zg ON zg.id = sgi.zoneGeofk + JOIN vn.itemBotanical ib ON ib.genusFk = sgi.genusFk AND sgi.specieFk IN ('sp.',ib.specieFk) + WHERE vLeft BETWEEN zg.lft AND zg.rgt + AND ib.itemFk = vItemFk + ORDER BY zg.`depth` DESC + LIMIT 1; + + RETURN IFNULL(vIsForbbiden, FALSE); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `testCIF` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `testCIF`(vCIF VARCHAR(9)) RETURNS varchar(10) CHARSET utf8 COLLATE utf8_unicode_ci + DETERMINISTIC +BEGIN + + DECLARE vLetraInicial VARCHAR(1); + DECLARE vLetraFinal VARCHAR(1); + DECLARE vParteNumerica VARCHAR(7); + DECLARE vSuma INT DEFAULT 0; + DECLARE vNumero INT DEFAULT 0; + DECLARE i INT DEFAULT 0; + DECLARE vResult BOOL DEFAULT FALSE; + + SET vLetraInicial = SUBSTR(vCIF, 1, 1); + SET vLetraFinal = SUBSTR(vCIF, 9, 1); + SET vParteNumerica = SUBSTR(vCIF, 2, 7); + + WHILE i < 7 DO + + SET i = i + 1; + + SET vNumero = CAST(SUBSTR(vParteNumerica, i, 1) AS DECIMAL(1,0)); + + IF i MOD 2 THEN + + SET vNumero = vNumero * 2; + SET vNumero = vNumero MOD 10 + FLOOR(vNumero/10); + + END IF; + + SET vSuma = vSuma + vNumero; + + END WHILE; + + SET vSuma = vSuma MOD 10; + + IF vSuma > 0 THEN + + SET vSuma = 10 - vSuma; + + END IF; + + -- Comprobación de dígito de control + IF CAST(vLetraFinal AS DECIMAL(1,0)) = vSuma THEN + + SET vResult = TRUE; + + END IF; + + IF vSuma = 0 THEN + + SET vSuma = 10; + + END IF; + + IF CHAR(64 + vSuma) = vLetraFinal THEN + + SET vResult = TRUE; + + END IF; + + -- Sólo se aceptan letras como caracter inicial + IF ASCII(vLetraInicial) < 65 OR ASCII(vLetraInicial) > 87 THEN -- Ha de ser entre la A y la W + + SET vResult = FALSE; + + END IF; + + RETURN vResult; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `testNIE` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `testNIE`(vNIE VARCHAR(9)) RETURNS tinyint(1) + DETERMINISTIC +BEGIN + + DECLARE vIndice INT; + DECLARE vNumero VARCHAR(7); + DECLARE vOperador VARCHAR(9); + DECLARE vParteNumerica DECIMAL(8,0); + DECLARE vLetraInicial VARCHAR(1); + DECLARE vLetraFinal VARCHAR(1); + DECLARE vLetrasFinalesPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE"; + DECLARE vLetraInicialEsIncorrecta BOOL DEFAULT FALSE; + + SET vLetraInicial = SUBSTR(vNIE, 1, 1); + SET vLetraFinal = SUBSTR(vNIE, 9, 1); + SET vNumero = SUBSTR(vNIE, 2, 7); + + CASE vLetraInicial + + WHEN 'X' THEN + + SET vOperador = "0"; + + WHEN 'Y' THEN + + SET vOperador = "1"; + + WHEN 'Z' THEN + + SET vOperador = "2"; + + ELSE + + SET vLetraInicialEsIncorrecta = TRUE; + + END CASE; + + SET vOperador = CONCAT(vOperador, vNumero); + SET vParteNumerica = CAST(vOperador AS DECIMAL(8,0)); + SET vIndice = Round(vParteNumerica Mod 23, 0) + 1; + + IF SUBSTR(vLetrasFinalesPosibles, vIndice, 1) = vLetraFinal AND vLetraInicialEsIncorrecta = FALSE THEN + + RETURN TRUE; + + ELSE + + RETURN FALSE; + + END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `testNIF` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `testNIF`(vNIF VARCHAR(9)) RETURNS tinyint(1) + DETERMINISTIC +BEGIN + + DECLARE vIndice INT; + DECLARE vParteNumerica DECIMAL(8,0); + DECLARE vLetra VARCHAR(1); + DECLARE vLetrasPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE"; + + SET vLetra = SUBSTRING(vNIF, 9, 1); + + SET vParteNumerica = CAST(SUBSTRING(vNIF, 1, 8) AS DECIMAL(8,0)); + + SET vIndice = Round(vParteNumerica MOD 23, 0) + 1; + + If SUBSTRING(vLetrasPosibles, vIndice, 1) = vLetra Then + + RETURN TRUE; + + ELSE + + RETURN FALSE; + + END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP FUNCTION IF EXISTS `ticketGetTotal` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -44282,15 +45212,16 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` FUNCTION `ticketPositionInPath`(vTicketId INT) RETURNS varchar(10) CHARSET utf8 + DETERMINISTIC BEGIN - + DECLARE vRestTicketsMaxOrder INT; DECLARE vRestTicketsMinOrder INT; DECLARE vRestTicketsPacking INT; @@ -44937,6 +45868,71 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `vehicleWarehouseTimeControl_checkRegister` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `vehicleWarehouseTimeControl_checkRegister`(vWorkerFk VARCHAR(10)) RETURNS tinyint(1) + READS SQL DATA +BEGIN +/** + * Comprueba si existen registros + * @return Devuelve TRUE en caso de que haya registros + */ + + IF (SELECT COUNT(*) + FROM vn.vehicleWarehouseTimeControl vwt + WHERE vwt.workerFk = vWorkerFk + AND vwt.timed >= TIMESTAMPADD(HOUR , -12,NOW())) + 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 DROP FUNCTION IF EXISTS `vehicleWarehouse_checkNumberPlate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `vehicleWarehouse_checkNumberPlate`(vNumberPlate VARCHAR(10)) RETURNS tinyint(1) + READS SQL DATA +BEGIN +/** + * Comprueba si existe matrícula + * @return Devuelve TRUE en caso de que exista + */ + + IF (SELECT COUNT(*) + FROM vn.vehicleWarehouse + WHERE numberPlate = vNumberPlate + ) 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 DROP FUNCTION IF EXISTS `workerIsBoss` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -45558,17 +46554,17 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `agencyVolume` */; +/*!50003 DROP PROCEDURE IF EXISTS `agencyVolume__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `agencyVolume`(vDated DATE, vAgency INT) +CREATE DEFINER=`root`@`%` PROCEDURE `agencyVolume__`(vDated DATE, vAgency INT) BEGIN SELECT ELT(it.temperature + 1,'Calientes','Frios','Secos') AS Temp, @@ -45861,6 +46857,54 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `bankPolicy_notifyExpired` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `bankPolicy_notifyExpired`() +BEGIN +/** +* +* Manda correo cuando caduca un seguro +* de los leasing +* +*/ + INSERT INTO mail (sender,replyTo,subject,body) + SELECT 'administracion@verdnatura.es' sender, + 'noreply@verdnatura.es' replyTo, + CONCAT( + 'El seguro de la poliza ', + b.id, + ' ', + b.bank, + ' ha finalizado.' + ) subject, + CONCAT( + 'El seguro de la poliza ', + b.id, + ' ', + b.bank, + ' ha finalizado.' + ) body + FROM vn.bankPolicy bp + LEFT JOIN vn.supplier s + ON s.id = bp.supplierFk + LEFT JOIN vn.bank b + ON b.id = bp.bankFk + WHERE bp.insuranceExpired = CURDATE(); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `buyUltimate` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -45871,13 +46915,13 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `buyUltimate`(vWarehouseFk SMALLINT, vDate DATE) +CREATE DEFINER=`root`@`%` PROCEDURE `buyUltimate`(vWarehouseFk SMALLINT, vDated DATE) BEGIN /** - * Calcula las últimas compras realizadas hasta una fecha + * Calcula las �ltimas compras realizadas hasta una fecha * - * @param vWarehouseFk Id del almacén - * @param vDate Compras hasta fecha + * @param vWarehouseFk Id del almacén + * @param vDated Compras hasta fecha * @return tmp.buyUltimate */ CALL cache.last_buy_refresh (FALSE); @@ -45891,12 +46935,19 @@ BEGIN FROM cache.last_buy WHERE warehouse_id = vWarehouseFk OR vWarehouseFk IS NULL; - CALL vn.buyUltimateFromInterval(vWarehouseFk, CURDATE(), vDate); + CALL buyUltimateFromInterval(vWarehouseFk, CURDATE(), vDated); REPLACE INTO tmp.buyUltimate SELECT itemFk, buyFk, warehouseFk FROM tmp.buyUltimateFromInterval - WHERE warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL; + WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL) + AND landed <= vDated; + + INSERT IGNORE INTO tmp.buyUltimate + SELECT itemFk, buyFk, warehouseFk + FROM tmp.buyUltimateFromInterval + WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL) + AND landed > vDated; DROP TEMPORARY TABLE tmp.buyUltimateFromInterval; END ;; @@ -45909,19 +46960,19 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `buyUltimateFromInterval`(vWarehouseFk SMALLINT, vStarted DATE, vEnded DATE) BEGIN /** - * Calcula las últimas compras realizadas + * Calcula las últimas compras realizadas * desde un rango de fechas. * - * @param vWarehouseFk Id del almacén si es NULL se actualizan todos + * @param vWarehouseFk Id del almacén si es NULL se actualizan todos * @param vStarted Fecha inicial * @param vEnded Fecha fin * @return tmp.buyUltimateFromInterval @@ -45936,7 +46987,8 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimateFromInterval; CREATE TEMPORARY TABLE tmp.buyUltimateFromInterval - (INDEX (itemFk), INDEX(buyFk)) ENGINE = MEMORY + (PRIMARY KEY (itemFk, warehouseFk), INDEX(buyFk), INDEX(landed), INDEX(warehouseFk), INDEX(itemFk)) + ENGINE = MEMORY SELECT b.itemFk, t.warehouseInFk warehouseFk, @@ -45951,6 +47003,37 @@ BEGIN AND NOT b.isIgnored AND b.quantity > 0 GROUP BY itemFk, warehouseInFk; + + INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed) + SELECT + b.itemFk, + t.warehouseInFk warehouseFk, + b.id buyFk, + t.landed + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed > vEnded + AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) + AND b.price2 > 0 + AND NOT b.isIgnored + GROUP BY itemFk, warehouseInFk; + + INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed) + SELECT + b.itemFk, + t.warehouseInFk warehouseFk, + b.id buyFk, + t.landed + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed BETWEEN vStarted AND vEnded + AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) + AND b.quantity = 0 + GROUP BY itemFk, warehouseInFk; + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -45961,9 +47044,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -46024,14 +47107,7 @@ BEGIN SET ic.grams = b.weight * 1000 / b.packing WHERE ic.itemFk = vItemFk AND ic.warehouseFk = vWarehouse; - /* - IF vSize IS NULL AND vPackageFk > '' THEN - INSERT INTO vn.mail(`subject`,`body`,`sender`) - VALUES (CONCAT('Articulo sin medida ', vItemFk), - CONCAT('Se ha añadido el artículo ', vItemFk, ' sin medida a la entrada ', vEntryFk, - ' con el cubo ', vPackageFk), - 'ekt@verdnatura.es'); - END IF;*/ + END IF; SELECT isFeedStock INTO vIsFeedStock @@ -46171,6 +47247,103 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `buy_getVolume` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `buy_getVolume`() +BEGIN +/** + * Cálculo de volumen en líneas de compra + * @table tmp.buy(buyFk) + */ + SELECT ELT(it.temperature + 1,'Calientes','Frios','Secos') Temp, + CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * + item_getVolume(b.itemFk, b.packageFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) carros , + CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * + item_getVolume(b.itemFk, b.packageFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) espais + FROM buy b + JOIN tmp.buy tb ON tb.buyFk = b.id + JOIN volumeConfig vc + JOIN item i ON i.id = b.itemFk + JOIN itemType it ON it.id = i.typeFk + GROUP BY Temp; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `buy_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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` 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.agencyFk 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 DROP PROCEDURE IF EXISTS `buy_getVolumeByEntry` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `buy_getVolumeByEntry`(vEntryFk INT) +BEGIN + + DROP TEMPORARY TABLE IF EXISTS tmp.buy; + CREATE TEMPORARY TABLE tmp.buy (buyFk INT NOT NULL, PRIMARY KEY (buyFk)) ENGINE = MEMORY; + + INSERT INTO tmp.buy + SELECT b.id + FROM buy b + JOIN entry e ON e.id = b.entryFk + WHERE e.id = vEntryFk; + + CALL buy_getVolume(); + DROP TEMPORARY TABLE tmp.buy; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `buy_notifyPassport` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -46829,9 +48002,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -46897,7 +48070,7 @@ proc: BEGIN origin VARCHAR(3), price DECIMAL(10,2), priceKg DECIMAL(10,2), - KEY `itemFk` (`itemFk`) + PRIMARY KEY `itemFk` (`itemFk`) ) ENGINE = MEMORY DEFAULT CHARSET=utf8; OPEN cTravelTree; @@ -46961,14 +48134,16 @@ proc: BEGIN LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible JOIN origin o ON o.id = i.originFk JOIN ( - SELECT MAX(price) price, itemFk, priceKg - FROM tmp.ticketComponentPrice - WHERE warehouseFk = vWarehouseFk - GROUP BY itemFk + SELECT * + FROM (SELECT price, itemFk, priceKg + FROM tmp.ticketComponentPrice + WHERE warehouseFk = vWarehouseFk + ORDER BY (rate = 2) DESC) sub + GROUP BY itemFk ) bl ON bl.itemFk = tl.itemFk WHERE tl.zoneFk = vZoneFk AND tl.warehouseFk = vWarehouseFk - GROUP BY tl.itemFk; - -- on duplicatekey update + GROUP BY tl.itemFk + ON DUPLICATE KEY UPDATE available = available + VALUES(available); END LOOP; @@ -47009,7 +48184,6 @@ proc: BEGIN * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, `grouping`, price, priceKg) */ DECLARE vClientFk INT; - DECLARE vGeneralInflationCoefficient INT DEFAULT 1; DECLARE vMinimumDensityWeight INT DEFAULT 167; DECLARE vBoxVolume BIGINT; DECLARE vSpecialPriceComponent INT DEFAULT 10; @@ -47029,6 +48203,12 @@ proc: BEGIN DECLARE vRangeLogifloraDays INT DEFAULT 3; DECLARE vVisibleCache INT; DECLARE vRappelComponent INT DEFAULT 44; + DECLARE vIsZonePremium BOOL; + DECLARE vFrenchDiscount DECIMAL(3,2) DEFAULT 0.12; + + SELECT (COUNT(*) > 0) INTO vIsZonePremium + FROM vn.zoneFilter zf + WHERE zf.zoneFk = vZoneFk; SELECT vc.standardFlowerBox * 1000 INTO vBoxVolume FROM vn.volumeConfig vc; @@ -47050,7 +48230,6 @@ proc: BEGIN IF (NOT vIsLogifloraAllowed AND vVNHWarehouseFk != vWarehouseFk) OR (vn.isLogifloraDay(vShipped, vWarehouseFk) = FALSE) - OR (vIsFrenchVNHBuyer = FALSE AND NOW() BETWEEN '2021-05-21' AND '2021-05-25 12:00') -- Eliminar al pasar la fecha THEN @@ -47098,6 +48277,19 @@ proc: BEGIN AND IFNULL(sub.itemFk,0) = 0 AND IFNULL(v.visible ,0) = 0); + END IF; + + -- Eliminem productes de la oferta que no deuen vore les zones PREMIUM + IF vIsZonePremium THEN + + DELETE tl.* + FROM tmp.ticketLot tl + JOIN item i ON i.id = tl.itemFk + LEFT JOIN vn.zoneFilter zf ON zf.itemTypeFk = i.typeFk + AND zf.zoneFk = vZoneFk + AND i.`size` <= zf.sizeMax + WHERE zf.id IS NULL ; + END IF; @@ -47159,18 +48351,19 @@ proc: BEGIN tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue FROM tmp.ticketComponentCalculate tcc JOIN buy b ON b.id = tcc.buyFk; - - -- French Offer: revisar a partir de Mayo 2021 + + -- Promo Francia IF vIsFrenchVNHBuyer THEN - - INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) - SELECT tcc.warehouseFk, - tcc.itemFk, - vFrenchOffer, - - tcc.rate3 + b.buyingValue + b.freightValue + b.packageValue + b.comissionValue + ((b.buyingValue + b.freightValue + b.packageValue + b.comissionValue) * 0.06) - FROM tmp.ticketComponentCalculate tcc - JOIN buy b ON b.id = tcc.buyFk; - + + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + vFrenchOffer, + - vFrenchDiscount * (b.buyingValue + b.freightValue + b.packageValue + b.comissionValue) / ( 1 - vFrenchDiscount) + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk; + END IF; DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentBase; @@ -47241,7 +48434,7 @@ proc: BEGIN SELECT tcc.warehouseFK, tcc.itemFk, vDeliveryComponent, - vGeneralInflationCoefficient * ROUND(ic.cm3delivery * (IFNULL(zo.price,5000) - IFNULL(zo.bonus,0)) / vBoxVolume, 4) cost + z.inflation * ROUND(ic.cm3delivery * (IFNULL(zo.price,5000) - IFNULL(zo.bonus,0)) / vBoxVolume, 4) cost FROM tmp.ticketComponentCalculate tcc JOIN item i ON i.id = tcc.itemFk JOIN tmp.zoneOption zo ON zo.zoneFk = vZoneFk @@ -47284,7 +48477,7 @@ proc: BEGIN INSERT INTO tmp.ticketComponent SELECT tcc.warehouseFk, tcc.itemFk, - vRappelComponent, + IFNULL(c.componentFk ,vRappelComponent), SUM(tcc.cost) * ((1/(1-c.rappel/100)) -1) sumCost FROM tmp.ticketComponentCopy tcc JOIN vn.clientChain cc ON cc.clientFk = vClientFk @@ -47332,6 +48525,14 @@ proc: BEGIN AND tcc.packing > 0 AND tcc.available >= tcc.packing) GROUP BY tcs.warehouseFk, tcs.itemFk; + IF vIsZonePremium THEN + + DELETE + FROM tmp.ticketComponentRate + WHERE rate = 1; + + END IF; + INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) SELECT tcc.warehouseFk, @@ -47584,7 +48785,7 @@ BEGIN DELETE FROM vn.awb WHERE created < TIMESTAMPADD(YEAR,-2,CURDATE()); -- Borra los ficheros gestDoc - INSERT INTO vn.printServerQueue(priorityFk, reportFk)VALUES(1,11); + INSERT INTO vn.printServerQueue(priorityFk, labelReportFk)VALUES(1,11); DROP TEMPORARY TABLE IF EXISTS tmp.thermographToDelete; DROP TEMPORARY TABLE IF EXISTS tmp.entryToDelete; @@ -47743,6 +48944,7 @@ CREATE DEFINER=`root`@`%` PROCEDURE `clientCreate`( vProvinceFk SMALLINT(5), vCompanyFk SMALLINT(5), vPhone VARCHAR(11), + vEmail VARCHAR(255), vUserFk INT) BEGIN /** @@ -47762,6 +48964,7 @@ BEGIN street, fi, phone, + email, provinceFk, city, postcode, @@ -47778,6 +48981,7 @@ BEGIN vAddress, TRIM(vFi), vPhone, + vEmail, vProvinceFk, vCity, vPostcode, @@ -47852,9 +49056,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -47863,6 +49067,7 @@ BEGIN /** * Congela diariamente aquellos clientes que son morosos sin recobro, * pero que no sean trabajadores, + * y que el riesgo no sea menor que cero * hasta que no se gire la remesa no se congelan a los clientes de giro */ @@ -47873,7 +49078,16 @@ BEGIN WHERE invoiceFk LIKE 'REMESA%' AND payed > util.firstDayOfMonth(CURDATE()) limit 1; - + + DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; + CREATE TEMPORARY TABLE tmp.clientGetDebt + SELECT clientFk + FROM bs.defaulter + WHERE created = CURDATE() + AND amount; + + CALL clientGetDebt(CURDATE()); + UPDATE client c JOIN bi.defaulters d ON d.client = c.id AND d.date = CURDATE() JOIN config ON TRUE @@ -47881,14 +49095,18 @@ BEGIN LEFT JOIN worker w ON w.id = u.id LEFT JOIN recovery r ON r.clientFk = c.id AND r.finished IS NULL LEFT JOIN payMethod pm ON pm.id = c.payMethodFk + LEFT JOIN tmp.risk rk ON rk.clientFk = c.id SET c.isFreezed = TRUE, d.frozened = CURDATE(), u.active = FALSE - WHERE d.amount > config.defaultersMaxAmount + WHERE (d.amount > config.defaultersMaxAmount + AND IFNULL(rk.risk,0) >= 0) AND c.typeFk = 'normal' AND r.id IS NULL AND w.id IS NULL AND (vIsRemittanced OR pm.code <> 'bankDraft'); + + DROP TEMPORARY TABLE tmp.clientGetDebt; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47918,19 +49136,7 @@ BEGIN DECLARE vEnded DATETIME; SET vEnded = TIMESTAMP(IFNULL(vDate, CURDATE()), '23:59:59'); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - (INDEX (ticketFk)) - ENGINE = MEMORY - SELECT id ticketFk, c.clientFk - FROM ticket t - JOIN tmp.clientGetDebt c ON c.clientFk = t.clientFk - WHERE refFk IS NULL - AND shipped BETWEEN vStarted AND vEnded; - CALL ticketGetTotal(); - DROP TEMPORARY TABLE IF EXISTS tClientRisk; CREATE TEMPORARY TABLE tClientRisk ENGINE = MEMORY @@ -47955,9 +49161,11 @@ BEGIN GROUP BY t.clientFk; INSERT INTO tClientRisk - SELECT t.clientFk, total - FROM tmp.ticketTotal tt - JOIN tmp.ticket t ON t.ticketFk = tt.ticketFk; + SELECT t.clientFk, totalWithVat + FROM ticket t + JOIN tmp.clientGetDebt c ON c.clientFk = t.clientFk + WHERE refFk IS NULL + AND shipped BETWEEN vStarted AND vEnded; DROP TEMPORARY TABLE IF EXISTS tmp.risk; CREATE TEMPORARY TABLE tmp.risk @@ -48100,85 +49308,6 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `clientGetDebt__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `clientGetDebt__`(vDate DATE) -BEGIN -/** - * Calcula el riesgo para los clientes activos - * - * @table tmp.clientGetDebt(clientFk) - * @param vDate Fecha maxima de los registros - * @return tmp.risk - */ - DECLARE vStarted DATETIME DEFAULT TIMESTAMPADD(DAY, - DAYOFMONTH(CURDATE()) - 5, CURDATE()); - DECLARE vEnded DATETIME; - - SET vEnded = TIMESTAMP(IFNULL(vDate, CURDATE()), '23:59:59'); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - (INDEX (ticketFk)) - ENGINE = MEMORY - SELECT id ticketFk, c.clientFk - FROM ticket t - JOIN tmp.clientGetDebt c ON c.clientFk = t.clientFk - WHERE refFk IS NULL - AND shipped BETWEEN vStarted AND vEnded; - - CALL ticketGetTotal(); - - DROP TEMPORARY TABLE IF EXISTS tClientRisk; - CREATE TEMPORARY TABLE tClientRisk - ENGINE = MEMORY - SELECT cr.customer_id clientFk, SUM(cr.amount) amount - FROM bi.customer_risk cr - JOIN tmp.clientGetDebt c ON c.clientFk = cr.customer_id - GROUP BY cr.customer_id; - - INSERT INTO tClientRisk - SELECT c.clientFk, SUM(r.amountPaid) - FROM receipt r - JOIN tmp.clientGetDebt c ON c.clientFk = r.clientFk - WHERE r.payed > vEnded - GROUP BY c.clientFk; - - INSERT INTO tClientRisk - SELECT t.clientFk, CAST(-SUM(t.amount) / 100 AS DECIMAL(10,2)) - FROM hedera.tpvTransaction t - JOIN tmp.clientGetDebt c ON c.clientFk = t.clientFk - WHERE t.receiptFk IS NULL - AND t.status = 'ok' - GROUP BY t.clientFk; - - INSERT INTO tClientRisk - SELECT t.clientFk, total - FROM tmp.ticketTotal tt - JOIN tmp.ticket t ON t.ticketFk = tt.ticketFk; - - DROP TEMPORARY TABLE IF EXISTS tmp.risk; - CREATE TEMPORARY TABLE tmp.risk - (PRIMARY KEY (clientFk)) - ENGINE = MEMORY - SELECT clientFk, SUM(amount) risk - FROM client c - JOIN tClientRisk cr ON cr.clientFk = c.id - WHERE c.isActive - GROUP BY c.id; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `clientGreugeSpray` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -48838,7 +49967,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `clonTravelComplete` */; +/*!50003 DROP PROCEDURE IF EXISTS `clonTravelComplete__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -48848,8 +49977,9 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `clonTravelComplete`(IN `vTravelFk` INT, IN `vDateStart` DATE, IN `vDateEnd` DATE, IN `vRef` VARCHAR(255)) +CREATE DEFINER=`root`@`%` PROCEDURE `clonTravelComplete__`(IN `vTravelFk` INT, IN `vDateStart` DATE, IN `vDateEnd` DATE, IN `vRef` VARCHAR(255)) BEGIN +-- DEPRECATED usar travel_cloneWithEntries. jgallego /* * Clona un travel, junto con sus entradas y compras * @param vTravelFk travel a clonar @@ -49073,6 +50203,77 @@ BEGIN END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `cmr_sendOverview` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `cmr_sendOverview`() +BEGIN +/** + * Insert the monthly CMR summary in vn.mail on the 5th of each month. + */ + + SET SESSION group_concat_max_len = 1000000; +-- IF (DAY(CURDATE()) = 5) THEN + INSERT INTO + vn.mail (sender, + replyTo, + subject, + body) + SELECT + c2.email, + 'cmr@verdnatura.es', + 'Resumen CMR', + CONCAT('
+

Resumen Mensual CMR

+ + + + + + + + + ', GROUP_CONCAT('' ORDER BY c.id SEPARATOR '' ), ' +
+ Estimado cliente,
+ A continuación le enviamos el resumen menual de CMR ',UPPER(MONTHNAME(CURDATE() - INTERVAL 1 MONTH)),' ', YEAR(CURDATE() - INTERVAL 1 MONTH), '.

+ Le rogamos que nos devuelva el resumen firmado a cmr@verdnatura.es
+

+
CMRTicket
', c.id, ' ', c.ticketFk, '
+ +

+ Saludos cordiales, Dpto administración. +

') + FROM vn.cmr c + JOIN vn.address a ON c.addressToFk = a.id + JOIN vn.client c2 ON a.clientFk = c2.id + WHERE c.state = 'Pending' + AND MONTH(c.created) = MONTH(CURDATE() - INTERVAL 1 MONTH) + AND YEAR(c.created) = YEAR(CURDATE() - INTERVAL 1 MONTH) + AND c2.email IS NOT NULL -- No cogemos los CMRs dirigidos a 'Verdnatura' + GROUP BY c2.id; + + -- Actualizamos el estado a 'Enviado' + UPDATE vn.cmr c + SET c.state = 'Sent' + WHERE c.state = 'Pending' + AND MONTH(c.created) = MONTH(CURDATE() - INTERVAL 1 MONTH) + AND YEAR(c.created) = YEAR(CURDATE() - INTERVAL 1 MONTH); +-- END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -49272,9 +50473,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -49301,7 +50502,7 @@ BEGIN LIMIT 1; IF IFNULL(vCollectionFk,0) = 0 THEN - +CALL util.debugAdd("vCollectionFk",vn.getUser()); INSERT INTO vn.collection(workerFk, itemPackingTypeFk) VALUES(vn.getUser(), vItemPackingTypeFk); @@ -49411,7 +50612,7 @@ CREATE DEFINER=`root`@`%` PROCEDURE `collectionSticker_print`(vCollectionFk INT, BEGIN DECLARE vLabelReport INT; - SELECT labelReport INTO vLabelReport + SELECT labelReportFk INTO vLabelReport FROM vn.sector WHERE id = vSectorFk; @@ -49423,7 +50624,7 @@ BEGIN WHERE collectionFk = vCollectionFk ON DUPLICATE KEY UPDATE labelCount = labelCount + 1; - INSERT INTO vn.printServerQueue(reportFk, param1, workerFk) + INSERT INTO vn.printServerQueue(labelReportFk, param1, workerFk) SELECT vLabelReport, vCollectionFk, getUser(); END IF; @@ -49708,20 +50909,64 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `collection_get`(vWorkerFk INT) BEGIN - SELECT c.id AS collectionFk, date(c.created) AS created - FROM vn.collection c - LEFT JOIN vn.state s ON c.stateFk = s.id - WHERE c.workerFk = vWorkerFk AND s.code = 'ON_PREPARATION'; + SELECT c.id AS collectionFk, date(c.created) AS created + FROM vn.collection c + LEFT JOIN vn.state s ON c.stateFk = s.id + WHERE c.workerFk = vWorkerFk AND s.code = 'ON_PREPARATION' + AND created >= TIMESTAMPADD(HOUR , -6,NOW()); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `collection_getTickets` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `collection_getTickets`(vParamFk INT) +BEGIN + + DECLARE vAlertLevel INT; + DECLARE vItemPackingTypeFk VARCHAR(1); + + -- Si los sacadores son los de pruebas, pinta los colores + SELECT itemPackingTypeFk INTO vItemPackingTypeFk + FROM vn.collection + WHERE id = vParamFk; + + SELECT t.id ticketFk, + IF (!(vItemPackingTypeFk <=> 'V'), cc.code,CONCAT(SUBSTRING('ABCDEFGH',tc.wagon, 1),'-',tc.`level` )) `level`, + am.name as agencyName, + t.warehouseFk , + w.id as salesPersonFk, + IFNULL(tob.description,'')as observaciones + FROM vn.ticket t + LEFT JOIN vn.ticketCollection tc ON t.id = tc.ticketFk + LEFT JOIN vn.collectionColors cc ON cc.wagon = tc.wagon AND cc.shelve = tc.`level` + LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN vn.client c ON c.id = t.clientFk + LEFT JOIN vn.worker w ON w.id = c.salesPersonFk + LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id AND tob.observationTypeFk = 1 + WHERE tc.collectionFk = vParamFk OR (t.id = vParamFk AND t.id>2000000); + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -49742,8 +50987,19 @@ CREATE DEFINER=`root`@`%` PROCEDURE `collection_increaseQuantity`( vSaleFk INT, vQuantity INT) BEGIN + + DECLARE vDescription VARCHAR(100); DECLARE vOriginalQuantity INT; + DECLARE vConcept VARCHAR(100); + DECLARE vOrigin INT; + + SELECT concept INTO vConcept FROM vn.sale WHERE id = vSaleFk; + SELECT ticketFk INTO vOrigin FROM vn.sale WHERE id = vSaleFk; + SELECT CONCAT("Cambio cantidad ",vConcept," a ", vQuantity) INTO vDescription; + INSERT INTO vn.ticketLog (originFk, userFk, action , description) + VALUES(vOrigin, vn.getUser(), 'update', vDescription); + SELECT quantity INTO vOriginalQuantity FROM vn.sale WHERE id = vSaleFk; UPDATE `vn`.`sale` SET `quantity` = vQuantity,`originalQuantity` = vOriginalQuantity WHERE (`id` = vSaleFk); @@ -49814,7 +51070,1059 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `collection_new` */; +/*!50003 DROP PROCEDURE IF EXISTS `collection_newSmartTag` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `collection_newSmartTag`(vSectorFk INT) +proc:BEGIN + + DECLARE vIsPreviousPrepared BOOLEAN; + DECLARE vCollectionFk INT; + DECLARE vWarehouseFk INT; + DECLARE vMaxTickets INT; + DECLARE vStateFk INT; + DECLARE vFirstTicketFk INT; + DECLARE vHour INT; + DECLARE vMinute INT; + DECLARE vWorker INT; + DECLARE vWorkerCode VARCHAR(3); + DECLARE vWagon INT; + DECLARE vWagonCounter INT; + DECLARE vShelve INT; + DECLARE vTicket INT; + DECLARE vTicketToSplit INT; + DECLARE myUserIsSalesPersonRole BOOLEAN; + DECLARE vPrintedTickets INT; + DECLARE vMaxTicketPrinted INT; + DECLARE vItemPackingTypeFk VARCHAR(1); + DECLARE hasAssignedTickets BOOLEAN; + DECLARE vMaxNotReadyCollections INT DEFAULT 0; + DECLARE vNotReadyCollections INT; + DECLARE vSectorCode VARCHAR(20); + DECLARE vWagons INT; + + SELECT w.code, w.id INTO vWorkerCode, vWorker + FROM vn.worker w + WHERE w.id = vn.getUser(); + +-- Si hay colecciones sin terminar, sale del proceso + SELECT count(*) INTO vNotReadyCollections + FROM vn.collection c + WHERE c.workerFk = vn.getUser() + AND c.saleTotalCount > c.salePickedCount + 1 + AND c.created > TIMESTAMPADD(HOUR , -5,NOW()); + + IF vMaxNotReadyCollections < vNotReadyCollections THEN + + LEAVE proc; + + END IF; + + -- Establecemos el almacén y si es un sector de preparación previa, así como el estado para los tickets que se vayan preparando + SELECT isPreviousPrepared, warehouseFk, itemPackingTypeFk, code + INTO vIsPreviousPrepared, vWarehouseFk, vItemPackingTypeFk, vSectorCode + FROM vn.sector + WHERE id = vSectorFk; + + -- Cogemos el numero de wagons del trabajador + SELECT COUNT(ws.id) + FROM workerShelving ws + WHERE ws.workerFk = vWorker + AND ws.collectionFk IS NULL + INTO vWagons; + + SET vMaxTicketPrinted = 8 * vWagons; + SET vMaxTickets = 3 * vWagons; + + + IF vIsPreviousPrepared THEN + + LEAVE proc; -- Hasta que tengamos el altillo, vamos a cancelar esta opcion + + SELECT id INTO vStateFk + FROM vn.state + WHERE `code` = 'PREVIOUS_PREPARATION'; + ELSE + + SELECT id INTO vStateFk + FROM vn.state + WHERE `code` = 'ON_PREPARATION'; + + END IF; + + -- Averiguamos si es comercial el usuario + SELECT FALSE -- (r.name = 'salesPerson') + INTO myUserIsSalesPersonRole + FROM account.user u + JOIN account.role r ON r.id = u.role + WHERE u.id = vn.getUser(); + + -- Se obtiene nº de colección y el buffer con los pedidos preparables + INSERT INTO vn.collection + SET workerFk = account.myUser_getId(), + itemPackingTypeFk = vItemPackingTypeFk; + + SELECT LAST_INSERT_ID() INTO vCollectionFk; + + UPDATE workerShelving + SET collectionFk = vCollectionFk + WHERE workerFk = vWorker + AND collectionFk IS NULL; + + CALL vn.productionControl(vWarehouseFk, 0); + + -- 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 hasAssignedTickets + FROM tmp.productionBuffer pb + JOIN vn.state s ON s.id = pb.state + WHERE s.code = 'PICKER_DESIGNED' + AND pb.workerCode = vWorkerCode + AND LENGTH(pb.problem) = 0; + + IF hasAssignedTickets THEN + + UPDATE vn.collection + SET itemPackingTypeFk = NULL + WHERE id = vCollectionFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketToSplit; + CREATE TEMPORARY TABLE tmp.ticketToSplit + SELECT pb.ticketFk + FROM tmp.productionBuffer pb + JOIN vn.state s ON s.id = pb.state + WHERE s.code = 'PICKER_DESIGNED' + AND pb.workerCode = vWorkerCode + AND LENGTH(pb.problem) = 0 + ORDER BY HH, + mm, + s.`order` DESC, + pb.m3 DESC; + + WHILE (SELECT COUNT(*) FROM tmp.ticketToSplit) DO + + SELECT MIN(ticketFk) INTO vTicketToSplit + FROM tmp.ticketToSplit; + + CALL vn.ticket_splitItemPackingType(vTicketToSplit); + + INSERT INTO vn.ticketCollection(ticketFk, collectionFk) + SELECT ticketFk, vCollectionFk + FROM tmp.ticketIPT; + + DELETE FROM tmp.ticketToSplit + WHERE ticketFk = vTicketToSplit; + + DROP TEMPORARY TABLE tmp.ticketIPT; + + END WHILE; + + CALL vn.productionControl(vWarehouseFk, 0); + + ELSE + + SELECT COUNT(*) INTO vPrintedTickets + FROM tmp.productionBuffer pb + JOIN vn.state s ON s.id = pb.state + JOIN vn.agencyMode am ON am.id = pb.agencyModeFk + JOIN vn.agency a ON a.id = am.agencyFk + WHERE pb.shipped = CURDATE() + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) + AND s.isPreparable + AND (pb.H > 0 AND vItemPackingTypeFk = 'H' AND ISNULL(pb.collectionH) + OR pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV) + OR pb.F > 0 AND vItemPackingTypeFk = 'F' AND ISNULL(pb.collectionF) + OR pb.P > 0 AND vItemPackingTypeFk = 'P' AND ISNULL(pb.collectionP)); + + SET vMaxTicketPrinted = vMaxTicketPrinted - vPrintedTickets; + -- AutoPRINT + + IF vMaxTicketPrinted > 0 THEN + + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT s2.id, pb.ticketFk, vn.getUser() + FROM tmp.productionBuffer pb + JOIN vn.agencyMode am ON am.id = pb.agencyModeFk + JOIN vn.agency a ON a.id = am.agencyFk + JOIN vn.state s ON s.id = pb.state + JOIN vn.state s2 ON s2.code = 'PRINTED_AUTO' + JOIN vn.ticket t ON t.id = pb.ticketFk + WHERE pb.shipped = CURDATE() + AND LENGTH(pb.problem) = 0 + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) + AND s.isPrintable + AND (pb.m3 > 0.05 OR s.isOK) + AND (pb.H > 0 AND vItemPackingTypeFk = 'H' AND ISNULL(pb.collectionH) + OR pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV) + OR pb.F > 0 AND vItemPackingTypeFk = 'F' AND ISNULL(pb.collectionF) + OR pb.P > 0 AND vItemPackingTypeFk = 'P' AND ISNULL(pb.collectionP)) + AND t.created < TIMESTAMPADD(MINUTE, -10, NOW()) + ORDER BY HH, + mm, + s.`order` DESC, + pb.m3 DESC + LIMIT vMaxTicketPrinted; + + END IF; + + -- Se seleccionan los primeros tickets, asignando colección para dejarlos bloqueados a otros sacadores. + -- Se splitan los tickets preparables, para que solo tengan un tipo de empaquetado + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketToSplit; + CREATE TEMPORARY TABLE tmp.ticketToSplit + SELECT pb.ticketFk + FROM tmp.productionBuffer pb + JOIN vn.agencyMode am ON am.id = pb.agencyModeFk + JOIN vn.agency a ON a.id = am.agencyFk + JOIN vn.ticketStateToday tst ON tst.ticket = pb.ticketFk + JOIN vn.state s ON s.id = tst.state + WHERE ( pb.H > 0 AND vItemPackingTypeFk = 'H' AND ISNULL(pb.collectionH) + OR pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV) + OR pb.F > 0 AND vItemPackingTypeFk = 'F' AND ISNULL(pb.collectionF) + OR pb.P > 0 AND vItemPackingTypeFk = 'P' AND ISNULL(pb.collectionP)) + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) + AND LENGTH(pb.problem) = 0 + AND s.isPreparable + AND NOT myUserIsSalesPersonRole + ORDER BY pb.HH, pb.mm, s.`order` DESC + LIMIT vMaxTickets; + + WHILE (SELECT COUNT(*) FROM tmp.ticketToSplit) DO + + SELECT MIN(ticketFk) INTO vTicketToSplit + FROM tmp.ticketToSplit; + + CALL vn.ticket_splitItemPackingType(vTicketToSplit); + + INSERT INTO vn.ticketCollection(ticketFk, collectionFk) + SELECT ticketFk, vCollectionFk + FROM tmp.ticketIPT + WHERE itemPackingTypeFk = vItemPackingTypeFk; + + DELETE FROM tmp.ticketToSplit + WHERE ticketFk = vTicketToSplit; + + DROP TEMPORARY TABLE tmp.ticketIPT; + + END WHILE; + + END IF; + + -- Creamos una tabla temporal con los datos que necesitamos para depurar la colección + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + SELECT pb.ticketFk, + pb.`lines`, + pb.m3 * 1000 liters, + 0 as height, + 0 as shelve, + 0 as wagon, + pb.productionOrder, + pb.HH, + pb.mm + FROM tmp.productionBuffer pb + JOIN vn.ticketCollection tc ON tc.ticketFk = pb.ticketFk + WHERE tc.collectionFk = vCollectionFk + LIMIT vMaxTickets; + + -- Es importante que el primer ticket se coja en todos los casos + SET vFirstTicketFk = 0; + + SELECT ticketFk, HH, mm + INTO vFirstTicketFk, vHour, vMinute + FROM tmp.ticket + ORDER BY productionOrder DESC, HH, mm + LIMIT 1; + + -- Hay que excluir aquellos que no tengan la misma hora de preparación + DELETE + FROM tmp.ticket + WHERE HH != vHour + OR mm != vMinute; + + -- En el caso de pedidos de más volumen de un carro, la colección será monoticket. Pero si el primer pedido + -- no es monoticket, excluimos a los de más de un carro + IF (SELECT (t.liters > vc.trolleyM3 * 1000) + FROM tmp.ticket t + JOIN vn.volumeConfig vc + WHERE t.ticketFk = vFirstTicketFk) THEN + + DELETE + FROM tmp.ticket + WHERE ticketFk != vFirstTicketFk; + + ELSE + + DELETE t.* + FROM tmp.ticket t + JOIN vn.volumeConfig vc + WHERE t.liters > vc.trolleyM3 * 1000; + + END IF; + + -- Elimina los tickets bloqueados que no se van a preparar + DELETE tc.* + FROM vn.ticketCollection tc + LEFT JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND t.ticketFk IS NULL; + + /* + * + * Construccion del tren + * + */ + + -- Establece altura máxima por pedido, porque las plantas no se pueden recostar. + UPDATE tmp.ticket t + JOIN + ( SELECT MAX(i.size) maxHeigth, + tc.ticketFk + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + JOIN vn.item i ON i.id = s.itemFk + WHERE i.itemPackingTypeFk = 'V' + AND tc.collectionFk = vCollectionFk + GROUP BY tc.ticketFk) sub ON sub.ticketFk = t.ticketFk + SET t.height = IFNULL(sub.maxHeigth,0); + + -- Vamos a generar una tabla con todas las posibilidades de asignacion de pedido + DROP TEMPORARY TABLE IF EXISTS tmp.wagonsVolumetry; + CREATE TEMPORARY TABLE tmp.wagonsVolumetry + SELECT cv.`level` as shelve, + 1 as wagon, + cv.`lines`, + cv.liters, + cv.height + FROM vn.collectionVolumetry cv; + + SET vWagonCounter = 1; + + WHILE vWagonCounter < vWagons DO + + SET vWagonCounter = vWagonCounter + 1; + + INSERT INTO tmp.wagonsVolumetry(shelve, wagon, `lines`, liters, height) + SELECT cv.`level` as shelve, + vWagonCounter as wagon, + cv.`lines`, + cv.liters, + cv.height + FROM vn.collectionVolumetry cv + WHERE cv.itemPackingTypeFk = IFNULL(vItemPackingTypeFk, 'H'); + + END WHILE; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketShelve; + CREATE TEMPORARY TABLE tmp.ticketShelve + SELECT ticketFk, shelve, wagon, linesDif, LitersDif, heightDif + FROM ( + SELECT t.ticketFk, + wv.shelve, + wv.wagon, + t.productionOrder, + CAST(wv.`lines` AS SIGNED) - t.`lines` as linesDif, + CAST(wv.liters AS SIGNED) - t.liters as litersDif, + CAST(wv.height AS SIGNED) - t.height as heightDif + FROM tmp.wagonsVolumetry wv + JOIN tmp.ticket t + ) sub + WHERE linesDif >= 0 + AND litersDif >= 0 + AND heightDif >= 0 + ORDER BY productionOrder DESC, linesDif, LitersDif, heightDif ; + + -- Insertamos una opcion virtual para carro completo. Todo ticket tiene que poder entrar en un carro completo.... + INSERT INTO tmp.ticketShelve(ticketFk, shelve, wagon, linesDif, LitersDif, heightDif) + SELECT t.ticketFk, 0, wv.wagon, 999, 999,999 + FROM tmp.ticket t + JOIN tmp.wagonsVolumetry wv + GROUP BY t.ticketFk, wv.wagon; + + SET vWagonCounter = 0; + + WHILE vWagonCounter < vWagons DO + + SET vWagonCounter = vWagonCounter + 1; + + -- Asignamos la primera balda util al primer pedido + IF vWagonCounter = 1 THEN + + SELECT shelve INTO vShelve + FROM tmp.ticketShelve + WHERE ticketFk = vFirstTicketFk + AND wagon = vWagonCounter + ORDER BY heightDif, litersDif, linesDif + LIMIT 1; + + ELSE + + SELECT shelve, ticketFk INTO vShelve, vFirstTicketFk + FROM tmp.ticketShelve + WHERE wagon = vWagonCounter + ORDER BY heightDif, litersDif, linesDif + LIMIT 1; + + END IF; + + IF vShelve > 0 THEN + + UPDATE tmp.ticket + SET shelve = vShelve, + wagon = vWagonCounter + WHERE ticketFk = vFirstTicketFk; + + DELETE FROM tmp.ticketShelve + WHERE ticketFk = vFirstTicketFk + OR (shelve = vShelve AND wagon = vWagonCounter); + + WHILE (SELECT COUNT(*) FROM tmp.ticketShelve WHERE wagon = vWagonCounter) DO + + SELECT ticketFk, shelve + INTO vTicket, vShelve + FROM tmp.ticketShelve + WHERE wagon = vWagonCounter + LIMIT 1; + + UPDATE tmp.ticket + SET shelve = vShelve, + wagon = vWagonCounter + WHERE ticketFk = vTicket; + + DELETE FROM tmp.ticketShelve + WHERE ticketFk = vTicket + OR (shelve = vShelve AND wagon = vWagonCounter); + + END WHILE; + + ELSE + + UPDATE tmp.ticket + SET shelve = 1, wagon = vWagonCounter + WHERE ticketFk = vFirstTicketFk; + + DELETE FROM tmp.ticketShelve + WHERE ticketFk = vFirstTicketFk + AND wagon != vWagonCounter; + + END IF; + + END WHILE; + + -- Eliminamos los que se han quedado sin balda + DELETE FROM tmp.ticket WHERE shelve = 0; + + -- Elimina los tickets bloqueados que no se van a preparar + DELETE tc.* + FROM vn.ticketCollection tc + LEFT JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND t.ticketFk IS NULL; + + -- Elimina los tickets que ya estan en otra coleccion + DELETE tc.* + FROM vn.ticketCollection tc + JOIN vn.ticketCollection tc2 ON tc2.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND tc2.collectionFk != vCollectionFk; + + -- Actualiza el estado de la colección + UPDATE vn.collection c + JOIN vn.state st ON st.code = 'ON_PREPARATION' + SET c.stateFk = st.id + WHERE c.id = vCollectionFk; + + -- Asigna las bandejas y las smartTags + SET @wagon := 0; + UPDATE vn.ticketCollection tc + JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk + JOIN (SELECT @wagon:=@wagon+1 as wagon, ws.shelvingFk + FROM workerShelving ws + WHERE ws.collectionFk = vCollectionFk) sub ON sub.wagon = t.wagon + JOIN smartTag s ON s.shelvingFk = sub.shelvingFk AND s.`level` = t.shelve + SET tc.`level` = t.shelve, tc.wagon = t.wagon, tc.smartTagFk = s.code; + + -- Actualiza el estado de los tickets + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT vStateFk, ticketFk, account.myUser_getId() + FROM vn.ticketCollection tc + WHERE tc.collectionFk = vCollectionFk; + + -- Aviso para la preparacion previa + INSERT INTO vn.ticketDown(ticketFk, collectionFk) + SELECT tc.ticketFk, tc.collectionFk + FROM vn.ticketCollection tc + WHERE tc.collectionFk = vCollectionFk; + + IF (SELECT count(*) FROM vn.ticketCollection WHERE collectionFk = vCollectionFk) THEN + + CALL vn.salesMerge_byCollection(vCollectionFk); + + UPDATE vn.collection c + JOIN (SELECT count(*) saleTotalCount , + sum(s.isPicked != 0) salePickedCount + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND s.quantity > 0 + ) sub + SET c.saleTotalCount = sub.saleTotalCount, + c.salePickedCount = sub.salePickedCount + WHERE c.id = vCollectionFk; + + SELECT vCollectionFk; + + ELSE + + DELETE FROM vn.collection WHERE id = vCollectionFk; + -- SELECT NULL; + + END IF; + + DROP TEMPORARY TABLE tmp.ticketToSplit; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `collection_newSmartTag2` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `collection_newSmartTag2`(vSectorFk INT) +proc:BEGIN + + DECLARE vIsPreviousPrepared BOOLEAN; + DECLARE vCollectionFk INT; + DECLARE vWarehouseFk INT; + DECLARE vMaxTickets INT; + DECLARE vStateFk INT; + DECLARE vFirstTicketFk INT; + DECLARE vHour INT; + DECLARE vMinute INT; + DECLARE vWorker INT; + DECLARE vWorkerCode VARCHAR(3); + DECLARE vWagon INT; + DECLARE vWagonCounter INT; + DECLARE vShelve INT; + DECLARE vTicket INT; + DECLARE vTicketToSplit INT; + DECLARE myUserIsSalesPersonRole BOOLEAN; + DECLARE vPrintedTickets INT; + DECLARE vMaxTicketPrinted INT; + DECLARE vItemPackingTypeFk VARCHAR(1); + DECLARE hasAssignedTickets BOOLEAN; + DECLARE vMaxNotReadyCollections INT DEFAULT 0; + DECLARE vNotReadyCollections INT; + DECLARE vSectorCode VARCHAR(20); + DECLARE vWagons INT; + + /* SELECT w.code, w.id INTO vWorkerCode, vWorker + FROM vn.worker w + WHERE w.id = vn.getUser(); + */ + + SELECT 'VLC', 19263 INTO vWorkerCode, vWorker; + +-- Si hay colecciones sin terminar, sale del proceso + SELECT count(*) INTO vNotReadyCollections + FROM vn.collection c + WHERE c.workerFk = 19263 + AND c.saleTotalCount > c.salePickedCount + 1 + AND c.created > TIMESTAMPADD(HOUR , -5,NOW()); + + IF vMaxNotReadyCollections < vNotReadyCollections THEN + + LEAVE proc; + + END IF; + + -- Establecemos el almacén y si es un sector de preparación previa, así como el estado para los tickets que se vayan preparando + SELECT isPreviousPrepared, warehouseFk, itemPackingTypeFk, code + INTO vIsPreviousPrepared, vWarehouseFk, vItemPackingTypeFk, vSectorCode + FROM vn.sector + WHERE id = vSectorFk; + + -- Cogemos el numero de wagons del trabajador + SELECT COUNT(ws.id) + FROM vn.workerShelving ws + WHERE ws.workerFk = vWorker + AND ws.collectionFk IS NULL + INTO vWagons; + + SET vMaxTicketPrinted = 6 * vWagons; + SET vMaxTickets = 3 * vWagons; + + + IF vIsPreviousPrepared THEN + + LEAVE proc; -- Hasta que tengamos el altillo, vamos a cancelar esta opcion + + SELECT id INTO vStateFk + FROM vn.state + WHERE `code` = 'PREVIOUS_PREPARATION'; + ELSE + + SELECT id INTO vStateFk + FROM vn.state + WHERE `code` = 'ON_PREPARATION'; + + END IF; + + -- Averiguamos si es comercial el usuario + SELECT FALSE -- (r.name = 'salesPerson') + INTO myUserIsSalesPersonRole + FROM account.user u + JOIN account.role r ON r.id = u.role + WHERE u.id = 19263; + + -- Se obtiene nº de colección y el buffer con los pedidos preparables + INSERT INTO vn.collection + SET workerFk = 19263, + itemPackingTypeFk = vItemPackingTypeFk; + + SELECT LAST_INSERT_ID() INTO vCollectionFk; + + + UPDATE workerShelving + SET collectionFk = vCollectionFk + WHERE workerFk = vWorker + AND collectionFk IS NULL; + + CALL vn.productionControl(vWarehouseFk, 0); + + -- 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 hasAssignedTickets + FROM tmp.productionBuffer pb + JOIN vn.state s ON s.id = pb.state + WHERE s.code = 'PICKER_DESIGNED' + AND pb.workerCode = vWorkerCode + AND LENGTH(pb.problem) = 0; + + IF hasAssignedTickets THEN + + UPDATE vn.collection + SET itemPackingTypeFk = NULL + WHERE id = vCollectionFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketToSplit; + CREATE TEMPORARY TABLE tmp.ticketToSplit + SELECT pb.ticketFk + FROM tmp.productionBuffer pb + JOIN vn.state s ON s.id = pb.state + WHERE s.code = 'PICKER_DESIGNED' + AND pb.workerCode = vWorkerCode + AND LENGTH(pb.problem) = 0 + ORDER BY HH, + mm, + s.`order` DESC, + pb.m3 DESC; + + WHILE (SELECT COUNT(*) FROM tmp.ticketToSplit) DO + + SELECT MIN(ticketFk) INTO vTicketToSplit + FROM tmp.ticketToSplit; + + CALL vn.ticket_splitItemPackingType(vTicketToSplit); + + INSERT INTO vn.ticketCollection(ticketFk, collectionFk) + SELECT ticketFk, vCollectionFk + FROM tmp.ticketIPT; + + DELETE FROM tmp.ticketToSplit + WHERE ticketFk = vTicketToSplit; + + DROP TEMPORARY TABLE tmp.ticketIPT; + + END WHILE; + + CALL vn.productionControl(vWarehouseFk, 0); + + ELSE + + SELECT COUNT(*) INTO vPrintedTickets + FROM tmp.productionBuffer pb + JOIN vn.state s ON s.id = pb.state + JOIN vn.agencyMode am ON am.id = pb.agencyModeFk + JOIN vn.agency a ON a.id = am.agencyFk + WHERE pb.shipped = CURDATE() + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) + AND s.isPreparable + AND (pb.H > 0 AND vItemPackingTypeFk = 'H' AND ISNULL(pb.collectionH) + OR pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV) + OR pb.F > 0 AND vItemPackingTypeFk = 'F' AND ISNULL(pb.collectionF) + OR pb.P > 0 AND vItemPackingTypeFk = 'P' AND ISNULL(pb.collectionP)); + + SET vMaxTicketPrinted = vMaxTicketPrinted - vPrintedTickets; + -- AutoPRINT + + IF vMaxTicketPrinted > 0 THEN + + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT s2.id, pb.ticketFk, 19263 + FROM tmp.productionBuffer pb + JOIN vn.agencyMode am ON am.id = pb.agencyModeFk + JOIN vn.agency a ON a.id = am.agencyFk + JOIN vn.state s ON s.id = pb.state + JOIN vn.state s2 ON s2.code = 'PRINTED_AUTO' + JOIN vn.ticket t ON t.id = pb.ticketFk + WHERE pb.shipped = CURDATE() + AND LENGTH(pb.problem) = 0 + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) + AND s.isPrintable + AND (pb.m3 > 0.05 OR s.isOK) + AND (pb.H > 0 AND vItemPackingTypeFk = 'H' AND ISNULL(pb.collectionH) + OR pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV) + OR pb.F > 0 AND vItemPackingTypeFk = 'F' AND ISNULL(pb.collectionF) + OR pb.P > 0 AND vItemPackingTypeFk = 'P' AND ISNULL(pb.collectionP)) + AND t.created < TIMESTAMPADD(MINUTE, -10, NOW()) + ORDER BY HH, + mm, + s.`order` DESC, + pb.m3 DESC + LIMIT vMaxTicketPrinted; + + END IF; + + -- Se seleccionan los primeros tickets, asignando colección para dejarlos bloqueados a otros sacadores. + -- Se splitan los tickets preparables, para que solo tengan un tipo de empaquetado + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketToSplit; + CREATE TEMPORARY TABLE tmp.ticketToSplit + SELECT pb.ticketFk + FROM tmp.productionBuffer pb + JOIN vn.agencyMode am ON am.id = pb.agencyModeFk + JOIN vn.agency a ON a.id = am.agencyFk + JOIN vn.ticketStateToday tst ON tst.ticket = pb.ticketFk + JOIN vn.state s ON s.id = tst.state + WHERE ( pb.H > 0 AND vItemPackingTypeFk = 'H' AND ISNULL(pb.collectionH) + OR pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV) + OR pb.F > 0 AND vItemPackingTypeFk = 'F' AND ISNULL(pb.collectionF) + OR pb.P > 0 AND vItemPackingTypeFk = 'P' AND ISNULL(pb.collectionP)) + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) + AND LENGTH(pb.problem) = 0 + AND s.isPreparable + AND NOT myUserIsSalesPersonRole + ORDER BY pb.HH, pb.mm, s.`order` DESC + LIMIT vMaxTickets; + + WHILE (SELECT COUNT(*) FROM tmp.ticketToSplit) DO + + SELECT MIN(ticketFk) INTO vTicketToSplit + FROM tmp.ticketToSplit; + + CALL vn.ticket_splitItemPackingType(vTicketToSplit); + + INSERT INTO vn.ticketCollection(ticketFk, collectionFk) + SELECT ticketFk, vCollectionFk + FROM tmp.ticketIPT + WHERE itemPackingTypeFk = vItemPackingTypeFk; + + DELETE FROM tmp.ticketToSplit + WHERE ticketFk = vTicketToSplit; + + DROP TEMPORARY TABLE tmp.ticketIPT; + + END WHILE; + + END IF; + + -- Creamos una tabla temporal con los datos que necesitamos para depurar la colección + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + SELECT pb.ticketFk, + pb.`lines`, + pb.m3 * 1000 liters, + 0 as height, + 0 as shelve, + 0 as wagon, + pb.productionOrder, + pb.HH, + pb.mm + FROM tmp.productionBuffer pb + JOIN vn.ticketCollection tc ON tc.ticketFk = pb.ticketFk + WHERE tc.collectionFk = vCollectionFk + LIMIT vMaxTickets; + + -- Es importante que el primer ticket se coja en todos los casos + SET vFirstTicketFk = 0; + + SELECT ticketFk, HH, mm + INTO vFirstTicketFk, vHour, vMinute + FROM tmp.ticket + ORDER BY productionOrder DESC, HH, mm + LIMIT 1; + + -- Hay que excluir aquellos que no tengan la misma hora de preparación + DELETE + FROM tmp.ticket + WHERE HH != vHour + OR mm != vMinute; + + -- En el caso de pedidos de más volumen de un carro, la colección será monoticket. Pero si el primer pedido + -- no es monoticket, excluimos a los de más de un carro + IF (SELECT (t.liters > vc.trolleyM3 * 1000) + FROM tmp.ticket t + JOIN vn.volumeConfig vc + WHERE t.ticketFk = vFirstTicketFk) THEN + + DELETE + FROM tmp.ticket + WHERE ticketFk != vFirstTicketFk; + + ELSE + + DELETE t.* + FROM tmp.ticket t + JOIN vn.volumeConfig vc + WHERE t.liters > vc.trolleyM3 * 1000; + + END IF; + + -- Elimina los tickets bloqueados que no se van a preparar + DELETE tc.* + FROM vn.ticketCollection tc + LEFT JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND t.ticketFk IS NULL; + + /* + * + * Construccion del tren + * + */ + + -- Establece altura máxima por pedido, porque las plantas no se pueden recostar. + UPDATE tmp.ticket t + JOIN + ( SELECT MAX(i.size) maxHeigth, + tc.ticketFk + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + JOIN vn.item i ON i.id = s.itemFk + WHERE i.itemPackingTypeFk = 'V' + AND tc.collectionFk = vCollectionFk + GROUP BY tc.ticketFk) sub ON sub.ticketFk = t.ticketFk + SET t.height = IFNULL(sub.maxHeigth,0); + + -- Vamos a generar una tabla con todas las posibilidades de asignacion de pedido + DROP TEMPORARY TABLE IF EXISTS tmp.wagonsVolumetry; + CREATE TEMPORARY TABLE tmp.wagonsVolumetry + SELECT cv.`level` as shelve, + 1 as wagon, + cv.`lines`, + cv.liters, + cv.height + FROM vn.collectionVolumetry cv; + + SET vWagonCounter = 1; + + WHILE vWagonCounter < vWagons DO + + SET vWagonCounter = vWagonCounter + 1; + + INSERT INTO tmp.wagonsVolumetry(shelve, wagon, `lines`, liters, height) + SELECT cv.`level` as shelve, + vWagonCounter as wagon, + cv.`lines`, + cv.liters, + cv.height + FROM vn.collectionVolumetry cv + WHERE cv.itemPackingTypeFk = IFNULL(vItemPackingTypeFk, 'H'); + + END WHILE; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketShelve; + CREATE TEMPORARY TABLE tmp.ticketShelve + SELECT ticketFk, shelve, wagon, linesDif, LitersDif, heightDif + FROM ( + SELECT t.ticketFk, + wv.shelve, + wv.wagon, + t.productionOrder, + CAST(wv.`lines` AS SIGNED) - t.`lines` as linesDif, + CAST(wv.liters AS SIGNED) - t.liters as litersDif, + CAST(wv.height AS SIGNED) - t.height as heightDif + FROM tmp.wagonsVolumetry wv + JOIN tmp.ticket t + ) sub + WHERE linesDif >= 0 + AND litersDif >= 0 + AND heightDif >= 0 + ORDER BY productionOrder DESC, linesDif, LitersDif, heightDif ; + + -- Insertamos una opcion virtual para carro completo. Todo ticket tiene que poder entrar en un carro completo.... + INSERT INTO tmp.ticketShelve(ticketFk, shelve, wagon, linesDif, LitersDif, heightDif) + SELECT t.ticketFk, 0, wv.wagon, 999, 999,999 + FROM tmp.ticket t + JOIN tmp.wagonsVolumetry wv + GROUP BY t.ticketFk, wv.wagon; + + SET vWagonCounter = 0; + + WHILE vWagonCounter < vWagons DO + + SET vWagonCounter = vWagonCounter + 1; + + -- Asignamos la primera balda util al primer pedido + IF vWagonCounter = 1 THEN + + SELECT shelve INTO vShelve + FROM tmp.ticketShelve + WHERE ticketFk = vFirstTicketFk + AND wagon = vWagonCounter + ORDER BY heightDif, litersDif, linesDif + LIMIT 1; + + ELSE + + SELECT shelve, ticketFk INTO vShelve, vFirstTicketFk + FROM tmp.ticketShelve + WHERE wagon = vWagonCounter + ORDER BY heightDif, litersDif, linesDif + LIMIT 1; + + END IF; + + IF vShelve > 0 THEN + + UPDATE tmp.ticket + SET shelve = vShelve, + wagon = vWagonCounter + WHERE ticketFk = vFirstTicketFk; + + DELETE FROM tmp.ticketShelve + WHERE ticketFk = vFirstTicketFk + OR (shelve = vShelve AND wagon = vWagonCounter); + + WHILE (SELECT COUNT(*) FROM tmp.ticketShelve WHERE wagon = vWagonCounter) DO + + SELECT ticketFk, shelve + INTO vTicket, vShelve + FROM tmp.ticketShelve + WHERE wagon = vWagonCounter + LIMIT 1; + + UPDATE tmp.ticket + SET shelve = vShelve, + wagon = vWagonCounter + WHERE ticketFk = vTicket; + + DELETE FROM tmp.ticketShelve + WHERE ticketFk = vTicket + OR (shelve = vShelve AND wagon = vWagonCounter); + + END WHILE; + + ELSE + + UPDATE tmp.ticket + SET shelve = 1, wagon = vWagonCounter + WHERE ticketFk = vFirstTicketFk; + + DELETE FROM tmp.ticketShelve + WHERE ticketFk = vFirstTicketFk + AND wagon != vWagonCounter; + + END IF; + + END WHILE; + + -- Eliminamos los que se han quedado sin balda + DELETE FROM tmp.ticket WHERE shelve = 0; + + -- Elimina los tickets bloqueados que no se van a preparar + DELETE tc.* + FROM vn.ticketCollection tc + LEFT JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND t.ticketFk IS NULL; + + -- Elimina los tickets que ya estan en otra coleccion + DELETE tc.* + FROM vn.ticketCollection tc + JOIN vn.ticketCollection tc2 ON tc2.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND tc2.collectionFk != vCollectionFk; + + -- Actualiza el estado de la colección + UPDATE vn.collection c + JOIN vn.state st ON st.code = 'ON_PREPARATION' + SET c.stateFk = st.id + WHERE c.id = vCollectionFk; + + -- Asigna las bandejas y las smartTags + SET @wagon := 0; + UPDATE vn.ticketCollection tc + JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk + JOIN (SELECT @wagon:=@wagon+1 as wagon, ws.shelvingFk + FROM workerShelving ws + WHERE ws.collectionFk = vCollectionFk) sub ON sub.wagon = t.wagon + JOIN smartTag s ON s.shelvingFk = sub.shelvingFk AND s.`level` = t.shelve + SET tc.`level` = t.shelve, tc.wagon = t.wagon, tc.smartTagFk = s.code; + + -- Actualiza el estado de los tickets + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT vStateFk, ticketFk, 19263 + FROM vn.ticketCollection tc + WHERE tc.collectionFk = vCollectionFk; + + -- Aviso para la preparacion previa + INSERT INTO vn.ticketDown(ticketFk, collectionFk) + SELECT tc.ticketFk, tc.collectionFk + FROM vn.ticketCollection tc + WHERE tc.collectionFk = vCollectionFk; + + IF (SELECT count(*) FROM vn.ticketCollection WHERE collectionFk = vCollectionFk) THEN + + CALL vn.salesMerge_byCollection(vCollectionFk); + + UPDATE vn.collection c + JOIN (SELECT count(*) saleTotalCount , + sum(s.isPicked != 0) salePickedCount + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND s.quantity > 0 + ) sub + SET c.saleTotalCount = sub.saleTotalCount, + c.salePickedCount = sub.salePickedCount + WHERE c.id = vCollectionFk; + + SELECT vCollectionFk; + + ELSE + + DELETE FROM vn.collection WHERE id = vCollectionFk; + -- SELECT NULL; + + END IF; + + DROP TEMPORARY TABLE tmp.ticketToSplit; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `collection_newWithWagon` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -49824,7 +52132,557 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `collection_new`(vSectorFk INT) +CREATE DEFINER=`root`@`%` PROCEDURE `collection_newWithWagon`(vSectorFk INT, vWagons INT) +proc:BEGIN + + DECLARE vIsPreviousPrepared BOOLEAN; + DECLARE vCollectionFk INT; + DECLARE vWarehouseFk INT; + DECLARE vMaxTickets INT; + DECLARE vStateFk INT; + DECLARE vFirstTicketFk INT; + DECLARE vHour INT; + DECLARE vMinute INT; + DECLARE vWorkerCode VARCHAR(3); + DECLARE vWagon INT; + DECLARE vWagonCounter INT; + DECLARE vShelve INT; + DECLARE vTicket INT; + DECLARE vTicketToSplit INT; + DECLARE myUserIsSalesPersonRole BOOLEAN; + DECLARE vPrintedTickets INT; + DECLARE vMaxTicketPrinted INT; + DECLARE vItemPackingTypeFk VARCHAR(1); + DECLARE hasAssignedTickets BOOLEAN; + DECLARE vMaxNotReadyCollections INT DEFAULT 0; + DECLARE vNotReadyCollections INT; + DECLARE vSectorCode VARCHAR(20); +/* + IF vn.getUser() = 18890 THEN + CALL collection_newSmartTag(vSectorFk); + LEAVE proc; + END IF;*/ + + SELECT w.code INTO vWorkerCode + FROM vn.worker w + WHERE w.id = vn.getUser(); + + -- Establecemos el almacén y si es un sector de preparación previa, así como el estado para los tickets que se vayan preparando + SELECT isPreviousPrepared, warehouseFk, itemPackingTypeFk, code + INTO vIsPreviousPrepared, vWarehouseFk, vItemPackingTypeFk, vSectorCode + FROM vn.sector + WHERE id = vSectorFk; + +-- Si está habilitado el modo cazador para las PDA, y el usuario no está registrado, se sale. + + IF (SELECT deviceHuntingMode FROM vn.config) AND vItemPackingTypeFk = 'H' THEN + + IF (SELECT COUNT(*) FROM vn.workerWithoutDevice wwd WHERE wwd.workerFk = account.userGetId()) THEN + + LEAVE proc; + + END IF; + + END IF; + +-- Si está habilitado el modo cazador para las motos, y el usuario no está registrado, se sale. + + IF (SELECT tractorHuntingMode FROM vn.config) AND vItemPackingTypeFk = 'H' THEN + + IF (SELECT COUNT(*) FROM vn.workerWithoutTractor wwt WHERE wwt.workerFk = account.userGetId()) THEN + + INSERT INTO tmp.kk(userFk) VALUES(vn.getUser()); + + LEAVE proc; + + END IF; + + END IF; + +-- Si hay colecciones sin terminar, sale del proceso + SELECT count(*) INTO vNotReadyCollections + FROM vn.collection c + WHERE c.workerFk = vn.getUser() + AND c.saleTotalCount > c.salePickedCount + 1 + AND c.created > TIMESTAMPADD(HOUR , -5,NOW()); + + IF vMaxNotReadyCollections < vNotReadyCollections THEN + + LEAVE proc; + + END IF; + +/* + IF LENGTH(vSectorCode) = 2 THEN + + SELECT CAST(SUBSTRING(vSectorCode,2,1) AS UNSIGNED) INTO vWagons; + + END IF; +*/ + SET vMaxTicketPrinted = 8 * vWagons; + SET vMaxTickets = 4 * vWagons; + + + IF vIsPreviousPrepared THEN + + LEAVE proc; -- Hasta que tengamos el altillo, vamos a cancelar esta opcion + + SELECT id INTO vStateFk + FROM vn.state + WHERE `code` = 'PREVIOUS_PREPARATION'; + ELSE + + SELECT id INTO vStateFk + FROM vn.state + WHERE `code` = 'ON_PREPARATION'; + + END IF; + + -- Averiguamos si es comercial el usuario + SELECT FALSE -- (r.name = 'salesPerson') + INTO myUserIsSalesPersonRole + FROM account.user u + JOIN account.role r ON r.id = u.role + WHERE u.id = vn.getUser(); + + -- Se obtiene nº de colección y el buffer con los pedidos preparables + INSERT INTO vn.collection + SET workerFk = account.myUser_getId(), + itemPackingTypeFk = vItemPackingTypeFk; + + SELECT LAST_INSERT_ID() INTO vCollectionFk; + + CALL vn.productionControl(vWarehouseFk, 0); + + -- 05/08/2021 PAK Jose Frau pide que los tickets de recogida en Algemesí sólo se saquen si están asignados. + DELETE pb.* + FROM tmp.productionBuffer pb + JOIN vn.state s ON s.id = pb.state + WHERE pb.agency = 'REC_ALGEMESI' + AND s.code != 'PICKER_DESIGNED'; + + -- 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 hasAssignedTickets + FROM tmp.productionBuffer pb + JOIN vn.state s ON s.id = pb.state + WHERE s.code = 'PICKER_DESIGNED' + AND pb.workerCode = vWorkerCode + AND LENGTH(pb.problem) = 0; + + IF hasAssignedTickets THEN + + UPDATE vn.collection + SET itemPackingTypeFk = NULL + WHERE id = vCollectionFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketToSplit; + CREATE TEMPORARY TABLE tmp.ticketToSplit + SELECT pb.ticketFk + FROM tmp.productionBuffer pb + JOIN vn.state s ON s.id = pb.state + WHERE s.code = 'PICKER_DESIGNED' + AND pb.workerCode = vWorkerCode + AND LENGTH(pb.problem) = 0 + ORDER BY HH, + mm, + s.`order` DESC, + pb.m3 DESC; + + WHILE (SELECT COUNT(*) FROM tmp.ticketToSplit) DO + + SELECT MIN(ticketFk) INTO vTicketToSplit + FROM tmp.ticketToSplit; + + CALL vn.ticket_splitItemPackingType(vTicketToSplit); + + INSERT INTO vn.ticketCollection(ticketFk, collectionFk) + SELECT ticketFk, vCollectionFk + FROM tmp.ticketIPT; + + DELETE FROM tmp.ticketToSplit + WHERE ticketFk = vTicketToSplit; + + DROP TEMPORARY TABLE tmp.ticketIPT; + + END WHILE; + + CALL vn.productionControl(vWarehouseFk, 0); + + ELSE + + SELECT COUNT(*) INTO vPrintedTickets + FROM tmp.productionBuffer pb + JOIN vn.state s ON s.id = pb.state + JOIN vn.agencyMode am ON am.id = pb.agencyModeFk + JOIN vn.agency a ON a.id = am.agencyFk + WHERE pb.shipped = CURDATE() + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) + AND s.isPreparable + AND (pb.H > 0 AND vItemPackingTypeFk = 'H' AND ISNULL(pb.collectionH) + OR pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV) + OR pb.F > 0 AND vItemPackingTypeFk = 'F' AND ISNULL(pb.collectionF) + OR pb.P > 0 AND vItemPackingTypeFk = 'P' AND ISNULL(pb.collectionP)); + + SET vMaxTicketPrinted = vMaxTicketPrinted - vPrintedTickets; + -- AutoPRINT + + IF vMaxTicketPrinted > 0 THEN + + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT s2.id, pb.ticketFk, vn.getUser() + FROM tmp.productionBuffer pb + JOIN vn.agencyMode am ON am.id = pb.agencyModeFk + JOIN vn.agency a ON a.id = am.agencyFk + JOIN vn.state s ON s.id = pb.state + JOIN vn.state s2 ON s2.code = 'PRINTED_AUTO' + JOIN vn.ticket t ON t.id = pb.ticketFk + WHERE pb.shipped = CURDATE() + AND LENGTH(pb.problem) = 0 + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) + AND s.isPrintable + AND (pb.m3 > 0.05 OR s.isOK) + AND (pb.H > 0 AND vItemPackingTypeFk = 'H' AND ISNULL(pb.collectionH) + OR pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV) + OR pb.F > 0 AND vItemPackingTypeFk = 'F' AND ISNULL(pb.collectionF) + OR pb.P > 0 AND vItemPackingTypeFk = 'P' AND ISNULL(pb.collectionP)) + AND t.created < TIMESTAMPADD(MINUTE, -10, NOW()) + ORDER BY HH, + mm, + s.`order` DESC, + pb.m3 DESC + LIMIT vMaxTicketPrinted; + + END IF; + + -- Se seleccionan los primeros tickets, asignando colección para dejarlos bloqueados a otros sacadores. + -- Se splitan los tickets preparables, para que solo tengan un tipo de empaquetado + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketToSplit; + CREATE TEMPORARY TABLE tmp.ticketToSplit + SELECT pb.ticketFk + FROM tmp.productionBuffer pb + JOIN vn.agencyMode am ON am.id = pb.agencyModeFk + JOIN vn.agency a ON a.id = am.agencyFk + JOIN vn.ticketStateToday tst ON tst.ticket = pb.ticketFk + JOIN vn.state s ON s.id = tst.state + WHERE ( pb.H > 0 AND vItemPackingTypeFk = 'H' AND ISNULL(pb.collectionH) + OR pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV) + OR pb.F > 0 AND vItemPackingTypeFk = 'F' AND ISNULL(pb.collectionF) + OR pb.P > 0 AND vItemPackingTypeFk = 'P' AND ISNULL(pb.collectionP)) + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) + AND LENGTH(pb.problem) = 0 + AND s.isPreparable + AND NOT myUserIsSalesPersonRole + ORDER BY pb.HH, pb.mm, s.`order` DESC + LIMIT vMaxTickets; + + WHILE (SELECT COUNT(*) FROM tmp.ticketToSplit) DO + + SELECT MIN(ticketFk) INTO vTicketToSplit + FROM tmp.ticketToSplit; + + CALL vn.ticket_splitItemPackingType(vTicketToSplit); + + INSERT INTO vn.ticketCollection(ticketFk, collectionFk) + SELECT ticketFk, vCollectionFk + FROM tmp.ticketIPT + WHERE itemPackingTypeFk = vItemPackingTypeFk; + + DELETE FROM tmp.ticketToSplit + WHERE ticketFk = vTicketToSplit; + + DROP TEMPORARY TABLE tmp.ticketIPT; + + END WHILE; + + END IF; + + -- Creamos una tabla temporal con los datos que necesitamos para depurar la colección + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + SELECT pb.ticketFk, + pb.`lines`, + pb.m3 * 1000 liters, + 0 as height, + 0 as shelve, + 0 as wagon, + pb.productionOrder, + pb.HH, + pb.mm + FROM tmp.productionBuffer pb + JOIN vn.ticketCollection tc ON tc.ticketFk = pb.ticketFk + WHERE tc.collectionFk = vCollectionFk + LIMIT vMaxTickets; + + -- Es importante que el primer ticket se coja en todos los casos + SET vFirstTicketFk = 0; + + SELECT ticketFk, HH, mm + INTO vFirstTicketFk, vHour, vMinute + FROM tmp.ticket + ORDER BY productionOrder DESC, HH, mm + LIMIT 1; + + -- Hay que excluir aquellos que no tengan la misma hora de preparación + DELETE + FROM tmp.ticket + WHERE HH != vHour + OR mm != vMinute; + + -- En el caso de pedidos de más volumen de un carro, la colección será monoticket. Pero si el primer pedido + -- no es monoticket, excluimos a los de más de un carro + IF (SELECT (t.liters > vc.trolleyM3 * 1000) + FROM tmp.ticket t + JOIN vn.volumeConfig vc + WHERE t.ticketFk = vFirstTicketFk) THEN + + DELETE + FROM tmp.ticket + WHERE ticketFk != vFirstTicketFk; + + ELSE + + DELETE t.* + FROM tmp.ticket t + JOIN vn.volumeConfig vc + WHERE t.liters > vc.trolleyM3 * 1000; + + END IF; + + -- Elimina los tickets bloqueados que no se van a preparar + DELETE tc.* + FROM vn.ticketCollection tc + LEFT JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND t.ticketFk IS NULL; + + /* + * + * Construccion del tren + * + */ + + -- Establece altura máxima por pedido, porque las plantas no se pueden recostar. + UPDATE tmp.ticket t + JOIN + ( SELECT MAX(i.size) maxHeigth, + tc.ticketFk + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + JOIN vn.item i ON i.id = s.itemFk + WHERE i.itemPackingTypeFk = 'V' + AND tc.collectionFk = vCollectionFk + GROUP BY tc.ticketFk) sub ON sub.ticketFk = t.ticketFk + SET t.height = IFNULL(sub.maxHeigth,0); + + -- Vamos a generar una tabla con todas las posibilidades de asignacion de pedido + DROP TEMPORARY TABLE IF EXISTS tmp.wagonsVolumetry; + CREATE TEMPORARY TABLE tmp.wagonsVolumetry + SELECT cv.`level` as shelve, + 1 as wagon, + cv.`lines`, + cv.liters, + cv.height + FROM vn.collectionVolumetry cv; + + SET vWagonCounter = 1; + + WHILE vWagonCounter < vWagons DO + + SET vWagonCounter = vWagonCounter + 1; + + INSERT INTO tmp.wagonsVolumetry(shelve, wagon, `lines`, liters, height) + SELECT cv.`level` as shelve, + vWagonCounter as wagon, + cv.`lines`, + cv.liters, + cv.height + FROM vn.collectionVolumetry cv + WHERE cv.itemPackingTypeFk = IFNULL(vItemPackingTypeFk, 'H'); + + END WHILE; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketShelve; + CREATE TEMPORARY TABLE tmp.ticketShelve + SELECT ticketFk, shelve, wagon, linesDif, LitersDif, heightDif + FROM ( + SELECT t.ticketFk, + wv.shelve, + wv.wagon, + t.productionOrder, + CAST(wv.`lines` AS SIGNED) - t.`lines` as linesDif, + CAST(wv.liters AS SIGNED) - t.liters as litersDif, + CAST(wv.height AS SIGNED) - t.height as heightDif + FROM tmp.wagonsVolumetry wv + JOIN tmp.ticket t + ) sub + WHERE linesDif >= 0 + AND litersDif >= 0 + AND heightDif >= 0 + ORDER BY productionOrder DESC, linesDif, LitersDif, heightDif ; + + -- Insertamos una opcion virtual para carro completo. Todo ticket tiene que poder entrar en un carro completo.... + INSERT INTO tmp.ticketShelve(ticketFk, shelve, wagon, linesDif, LitersDif, heightDif) + SELECT t.ticketFk, 0, wv.wagon, 999, 999,999 + FROM tmp.ticket t + JOIN tmp.wagonsVolumetry wv + GROUP BY t.ticketFk, wv.wagon; + + SET vWagonCounter = 0; + + WHILE vWagonCounter < vWagons DO + + SET vWagonCounter = vWagonCounter + 1; + + -- Asignamos la primera balda util al primer pedido + IF vWagonCounter = 1 THEN + + SELECT shelve INTO vShelve + FROM tmp.ticketShelve + WHERE ticketFk = vFirstTicketFk + AND wagon = vWagonCounter + ORDER BY heightDif, litersDif, linesDif + LIMIT 1; + + ELSE + + SELECT shelve, ticketFk INTO vShelve, vFirstTicketFk + FROM tmp.ticketShelve + WHERE wagon = vWagonCounter + ORDER BY heightDif, litersDif, linesDif + LIMIT 1; + + END IF; + + IF vShelve > 0 THEN + + UPDATE tmp.ticket + SET shelve = vShelve, + wagon = vWagonCounter + WHERE ticketFk = vFirstTicketFk; + + DELETE FROM tmp.ticketShelve + WHERE ticketFk = vFirstTicketFk + OR (shelve = vShelve AND wagon = vWagonCounter); + + WHILE (SELECT COUNT(*) FROM tmp.ticketShelve WHERE wagon = vWagonCounter) DO + + SELECT ticketFk, shelve + INTO vTicket, vShelve + FROM tmp.ticketShelve + WHERE wagon = vWagonCounter + LIMIT 1; + + UPDATE tmp.ticket + SET shelve = vShelve, + wagon = vWagonCounter + WHERE ticketFk = vTicket; + + DELETE FROM tmp.ticketShelve + WHERE ticketFk = vTicket + OR (shelve = vShelve AND wagon = vWagonCounter); + + END WHILE; + + ELSE + + UPDATE tmp.ticket + SET shelve = 1, wagon = vWagonCounter + WHERE ticketFk = vFirstTicketFk; + + DELETE FROM tmp.ticketShelve + WHERE ticketFk = vFirstTicketFk + AND wagon != vWagonCounter; + + END IF; + + END WHILE; + + -- Eliminamos los que se han quedado sin balda + DELETE FROM tmp.ticket WHERE shelve = 0; + + -- Elimina los tickets bloqueados que no se van a preparar + DELETE tc.* + FROM vn.ticketCollection tc + LEFT JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND t.ticketFk IS NULL; + + -- Elimina los tickets que ya estan en otra coleccion + DELETE tc.* + FROM vn.ticketCollection tc + JOIN vn.ticketCollection tc2 ON tc2.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND tc2.collectionFk != vCollectionFk; + + -- Actualiza el estado de la colección + UPDATE vn.collection c + JOIN vn.state st ON st.code = 'ON_PREPARATION' + SET c.stateFk = st.id + WHERE c.id = vCollectionFk; + + -- Asigna las bandejas + UPDATE vn.ticketCollection tc + JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk + SET tc.level = t.shelve, tc.wagon = t.wagon; + + -- Actualiza el estado de los tickets + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT vStateFk, ticketFk, account.myUser_getId() + FROM vn.ticketCollection tc + WHERE tc.collectionFk = vCollectionFk; + + -- Aviso para la preparacion previa + INSERT INTO vn.ticketDown(ticketFk, collectionFk) + SELECT tc.ticketFk, tc.collectionFk + FROM vn.ticketCollection tc + WHERE tc.collectionFk = vCollectionFk; + + IF (SELECT count(*) FROM vn.ticketCollection WHERE collectionFk = vCollectionFk) THEN + + CALL vn.salesMerge_byCollection(vCollectionFk); + + UPDATE vn.collection c + JOIN (SELECT count(*) saleTotalCount , + sum(s.isPicked != 0) salePickedCount + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND s.quantity > 0 + ) sub + SET c.saleTotalCount = sub.saleTotalCount, + c.salePickedCount = sub.salePickedCount + WHERE c.id = vCollectionFk; + + SELECT vCollectionFk; + + ELSE + + DELETE FROM vn.collection WHERE id = vCollectionFk; + -- SELECT NULL; + + END IF; + + DROP TEMPORARY TABLE tmp.ticketToSplit; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `collection_new__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `collection_new__`(vSectorFk INT) proc:BEGIN DECLARE vIsPreviousPrepared BOOLEAN; @@ -50317,517 +53175,6 @@ proc:BEGIN DROP TEMPORARY TABLE tmp.ticketIPT; DROP TEMPORARY TABLE IF EXISTS tmp.ticketToSplit; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `collection_newWithWagon` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `collection_newWithWagon`(vSectorFk INT, vWagons INT) -proc:BEGIN - - DECLARE vIsPreviousPrepared BOOLEAN; - DECLARE vCollectionFk INT; - DECLARE vWarehouseFk INT; - DECLARE vMaxTickets INT; - DECLARE vStateFk INT; - DECLARE vFirstTicketFk INT; - DECLARE vHour INT; - DECLARE vMinute INT; - DECLARE vWorkerCode VARCHAR(3); - DECLARE vWagon INT; - DECLARE vWagonCounter INT; - DECLARE vShelve INT; - DECLARE vTicket INT; - DECLARE vTicketToSplit INT; - DECLARE myUserIsSalesPersonRole BOOLEAN; - DECLARE vPrintedTickets INT; - DECLARE vMaxTicketPrinted INT; - DECLARE vItemPackingTypeFk VARCHAR(1); - DECLARE hasAssignedTickets BOOLEAN; - DECLARE vMaxNotReadyCollections INT DEFAULT 0; - DECLARE vNotReadyCollections INT; - DECLARE vSectorCode VARCHAR(20); - - SELECT w.code INTO vWorkerCode - FROM vn.worker w - WHERE w.id = vn.getUser(); - --- Si hay colecciones sin terminar, sale del proceso - SELECT count(*) INTO vNotReadyCollections - FROM vn.collection c - WHERE c.workerFk = vn.getUser() - AND c.saleTotalCount > c.salePickedCount + 1 - AND c.created > TIMESTAMPADD(HOUR , -5,NOW()); - - IF vMaxNotReadyCollections < vNotReadyCollections THEN - - LEAVE proc; - - END IF; - - -- Establecemos el almacén y si es un sector de preparación previa, así como el estado para los tickets que se vayan preparando - SELECT isPreviousPrepared, warehouseFk, itemPackingTypeFk, code - INTO vIsPreviousPrepared, vWarehouseFk, vItemPackingTypeFk, vSectorCode - FROM vn.sector - WHERE id = vSectorFk; - - IF LENGTH(vSectorCode) = 2 THEN - - SELECT CAST(SUBSTRING(vSectorCode,2,1) AS UNSIGNED) INTO vWagons; - - END IF; - - SET vMaxTicketPrinted = 8 * vWagons; - SET vMaxTickets = 4 * vWagons; - - - IF vIsPreviousPrepared THEN - - LEAVE proc; -- Hasta que tengamos el altillo, vamos a cancelar esta opcion - - SELECT id INTO vStateFk - FROM vn.state - WHERE `code` = 'PREVIOUS_PREPARATION'; - ELSE - - SELECT id INTO vStateFk - FROM vn.state - WHERE `code` = 'ON_PREPARATION'; - - END IF; - - -- Averiguamos si es comercial el usuario - SELECT FALSE -- (r.name = 'salesPerson') - INTO myUserIsSalesPersonRole - FROM account.user u - JOIN account.role r ON r.id = u.role - WHERE u.id = vn.getUser(); - - -- Se obtiene nº de colección y el buffer con los pedidos preparables - INSERT INTO vn.collection - SET workerFk = account.myUser_getId(), - itemPackingTypeFk = vItemPackingTypeFk; - - SELECT LAST_INSERT_ID() INTO vCollectionFk; - - CALL vn.productionControl(vWarehouseFk, 0); - - -- 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 hasAssignedTickets - FROM tmp.productionBuffer pb - JOIN vn.state s ON s.id = pb.state - WHERE s.code = 'PICKER_DESIGNED' - AND pb.workerCode = vWorkerCode - AND LENGTH(pb.problem) = 0; - - IF hasAssignedTickets THEN - - UPDATE vn.collection - SET itemPackingTypeFk = NULL - WHERE id = vCollectionFk; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketToSplit; - CREATE TEMPORARY TABLE tmp.ticketToSplit - SELECT pb.ticketFk - FROM tmp.productionBuffer pb - JOIN vn.state s ON s.id = pb.state - WHERE s.code = 'PICKER_DESIGNED' - AND pb.workerCode = vWorkerCode - AND LENGTH(pb.problem) = 0 - ORDER BY HH, - mm, - s.`order` DESC, - pb.m3 DESC; - - WHILE (SELECT COUNT(*) FROM tmp.ticketToSplit) DO - - SELECT MIN(ticketFk) INTO vTicketToSplit - FROM tmp.ticketToSplit; - - CALL vn.ticket_splitItemPackingType(vTicketToSplit); - - INSERT INTO vn.ticketCollection(ticketFk, collectionFk) - SELECT ticketFk, vCollectionFk - FROM tmp.ticketIPT; - - DELETE FROM tmp.ticketToSplit - WHERE ticketFk = vTicketToSplit; - - DROP TEMPORARY TABLE tmp.ticketIPT; - - END WHILE; - - CALL vn.productionControl(vWarehouseFk, 0); - - ELSE - - SELECT COUNT(*) INTO vPrintedTickets - FROM tmp.productionBuffer pb - JOIN vn.state s ON s.id = pb.state - JOIN vn.agencyMode am ON am.id = pb.agencyModeFk - JOIN vn.agency a ON a.id = am.agencyFk - WHERE pb.shipped = CURDATE() - AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) - AND s.isPreparable - AND (pb.H > 0 AND vItemPackingTypeFk = 'H' AND ISNULL(pb.collectionH) - OR pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV) - OR pb.F > 0 AND vItemPackingTypeFk = 'F' AND ISNULL(pb.collectionF) - OR pb.P > 0 AND vItemPackingTypeFk = 'P' AND ISNULL(pb.collectionP)); - - SET vMaxTicketPrinted = vMaxTicketPrinted - vPrintedTickets; - -- AutoPRINT - - IF vMaxTicketPrinted > 0 THEN - - INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - SELECT s2.id, pb.ticketFk, vn.getUser() - FROM tmp.productionBuffer pb - JOIN vn.agencyMode am ON am.id = pb.agencyModeFk - JOIN vn.agency a ON a.id = am.agencyFk - JOIN vn.state s ON s.id = pb.state - JOIN vn.state s2 ON s2.code = 'PRINTED_AUTO' - JOIN vn.ticket t ON t.id = pb.ticketFk - WHERE pb.shipped = CURDATE() - AND LENGTH(pb.problem) = 0 - AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) - AND s.isPrintable - AND (pb.m3 > 0.05 OR s.isOK) - AND (pb.H > 0 AND vItemPackingTypeFk = 'H' AND ISNULL(pb.collectionH) - OR pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV) - OR pb.F > 0 AND vItemPackingTypeFk = 'F' AND ISNULL(pb.collectionF) - OR pb.P > 0 AND vItemPackingTypeFk = 'P' AND ISNULL(pb.collectionP)) - AND t.created < TIMESTAMPADD(MINUTE, -10, NOW()) - ORDER BY HH, - mm, - s.`order` DESC, - pb.m3 DESC - LIMIT vMaxTicketPrinted; - - END IF; - - -- Se seleccionan los primeros tickets, asignando colección para dejarlos bloqueados a otros sacadores. - -- Se splitan los tickets preparables, para que solo tengan un tipo de empaquetado - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketToSplit; - CREATE TEMPORARY TABLE tmp.ticketToSplit - SELECT pb.ticketFk - FROM tmp.productionBuffer pb - JOIN vn.agencyMode am ON am.id = pb.agencyModeFk - JOIN vn.agency a ON a.id = am.agencyFk - JOIN vn.ticketStateToday tst ON tst.ticket = pb.ticketFk - JOIN vn.state s ON s.id = tst.state - WHERE ( pb.H > 0 AND vItemPackingTypeFk = 'H' AND ISNULL(pb.collectionH) - OR pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV) - OR pb.F > 0 AND vItemPackingTypeFk = 'F' AND ISNULL(pb.collectionF) - OR pb.P > 0 AND vItemPackingTypeFk = 'P' AND ISNULL(pb.collectionP)) - AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) - AND LENGTH(pb.problem) = 0 - AND s.isPreparable - AND NOT myUserIsSalesPersonRole - ORDER BY pb.HH, pb.mm, s.`order` DESC - LIMIT vMaxTickets; - - WHILE (SELECT COUNT(*) FROM tmp.ticketToSplit) DO - - SELECT MIN(ticketFk) INTO vTicketToSplit - FROM tmp.ticketToSplit; - - CALL vn.ticket_splitItemPackingType(vTicketToSplit); - - INSERT INTO vn.ticketCollection(ticketFk, collectionFk) - SELECT ticketFk, vCollectionFk - FROM tmp.ticketIPT - WHERE itemPackingTypeFk = vItemPackingTypeFk; - - DELETE FROM tmp.ticketToSplit - WHERE ticketFk = vTicketToSplit; - - DROP TEMPORARY TABLE tmp.ticketIPT; - - END WHILE; - - END IF; - - -- Creamos una tabla temporal con los datos que necesitamos para depurar la colección - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - SELECT pb.ticketFk, - pb.`lines`, - pb.m3 * 1000 liters, - 0 as height, - 0 as shelve, - 0 as wagon, - pb.productionOrder, - pb.HH, - pb.mm - FROM tmp.productionBuffer pb - JOIN vn.ticketCollection tc ON tc.ticketFk = pb.ticketFk - WHERE tc.collectionFk = vCollectionFk - LIMIT vMaxTickets; - - -- Es importante que el primer ticket se coja en todos los casos - SET vFirstTicketFk = 0; - - SELECT ticketFk, HH, mm - INTO vFirstTicketFk, vHour, vMinute - FROM tmp.ticket - ORDER BY productionOrder DESC, HH, mm - LIMIT 1; - - -- Hay que excluir aquellos que no tengan la misma hora de preparación - DELETE - FROM tmp.ticket - WHERE HH != vHour - OR mm != vMinute; - - -- En el caso de pedidos de más volumen de un carro, la colección será monoticket. Pero si el primer pedido - -- no es monoticket, excluimos a los de más de un carro - IF (SELECT (t.liters > vc.carro * 1000) - FROM tmp.ticket t - JOIN vn.volumeConfig vc - WHERE t.ticketFk = vFirstTicketFk) THEN - - DELETE - FROM tmp.ticket - WHERE ticketFk != vFirstTicketFk; - - ELSE - - DELETE t.* - FROM tmp.ticket t - JOIN vn.volumeConfig vc - WHERE t.liters > vc.carro * 1000; - - END IF; - - -- Elimina los tickets bloqueados que no se van a preparar - DELETE tc.* - FROM vn.ticketCollection tc - LEFT JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk - WHERE tc.collectionFk = vCollectionFk - AND t.ticketFk IS NULL; - - /* - * - * Construccion del tren - * - */ - - -- Establece altura máxima por pedido, porque las plantas no se pueden recostar. - UPDATE tmp.ticket t - JOIN - ( SELECT MAX(i.size) maxHeigth, - tc.ticketFk - FROM vn.ticketCollection tc - JOIN vn.sale s ON s.ticketFk = tc.ticketFk - JOIN vn.item i ON i.id = s.itemFk - WHERE i.itemPackingTypeFk = 'V' - AND tc.collectionFk = vCollectionFk - GROUP BY tc.ticketFk) sub ON sub.ticketFk = t.ticketFk - SET t.height = IFNULL(sub.maxHeigth,0); - - -- Vamos a generar una tabla con todas las posibilidades de asignacion de pedido - DROP TEMPORARY TABLE IF EXISTS tmp.wagonsVolumetry; - CREATE TEMPORARY TABLE tmp.wagonsVolumetry - SELECT cv.`level` as shelve, - 1 as wagon, - cv.`lines`, - cv.liters, - cv.height - FROM vn.collectionVolumetry cv; - - SET vWagonCounter = 1; - - WHILE vWagonCounter < vWagons DO - - SET vWagonCounter = vWagonCounter + 1; - - INSERT INTO tmp.wagonsVolumetry(shelve, wagon, `lines`, liters, height) - SELECT cv.`level` as shelve, - vWagonCounter as wagon, - cv.`lines`, - cv.liters, - cv.height - FROM vn.collectionVolumetry cv - WHERE cv.itemPackingTypeFk = IFNULL(vItemPackingTypeFk, 'H'); - - END WHILE; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketShelve; - CREATE TEMPORARY TABLE tmp.ticketShelve - SELECT ticketFk, shelve, wagon, linesDif, LitersDif, heightDif - FROM ( - SELECT t.ticketFk, - wv.shelve, - wv.wagon, - t.productionOrder, - CAST(wv.`lines` AS SIGNED) - t.`lines` as linesDif, - CAST(wv.liters AS SIGNED) - t.liters as litersDif, - CAST(wv.height AS SIGNED) - t.height as heightDif - FROM tmp.wagonsVolumetry wv - JOIN tmp.ticket t - ) sub - WHERE linesDif >= 0 - AND litersDif >= 0 - AND heightDif >= 0 - ORDER BY productionOrder DESC, linesDif, LitersDif, heightDif ; - - -- Insertamos una opcion virtual para carro completo. Todo ticket tiene que poder entrar en un carro completo.... - INSERT INTO tmp.ticketShelve(ticketFk, shelve, wagon, linesDif, LitersDif, heightDif) - SELECT t.ticketFk, 0, wv.wagon, 999, 999,999 - FROM tmp.ticket t - JOIN tmp.wagonsVolumetry wv - GROUP BY t.ticketFk, wv.wagon; - - SET vWagonCounter = 0; - - WHILE vWagonCounter < vWagons DO - - SET vWagonCounter = vWagonCounter + 1; - - -- Asignamos la primera balda util al primer pedido - IF vWagonCounter = 1 THEN - - SELECT shelve INTO vShelve - FROM tmp.ticketShelve - WHERE ticketFk = vFirstTicketFk - AND wagon = vWagonCounter - ORDER BY heightDif, litersDif, linesDif - LIMIT 1; - - ELSE - - SELECT shelve, ticketFk INTO vShelve, vFirstTicketFk - FROM tmp.ticketShelve - WHERE wagon = vWagonCounter - ORDER BY heightDif, litersDif, linesDif - LIMIT 1; - - END IF; - - IF vShelve > 0 THEN - - UPDATE tmp.ticket - SET shelve = vShelve, - wagon = vWagonCounter - WHERE ticketFk = vFirstTicketFk; - - DELETE FROM tmp.ticketShelve - WHERE ticketFk = vFirstTicketFk - OR (shelve = vShelve AND wagon = vWagonCounter); - - WHILE (SELECT COUNT(*) FROM tmp.ticketShelve WHERE wagon = vWagonCounter) DO - - SELECT ticketFk, shelve - INTO vTicket, vShelve - FROM tmp.ticketShelve - WHERE wagon = vWagonCounter - LIMIT 1; - - UPDATE tmp.ticket - SET shelve = vShelve, - wagon = vWagonCounter - WHERE ticketFk = vTicket; - - DELETE FROM tmp.ticketShelve - WHERE ticketFk = vTicket - OR (shelve = vShelve AND wagon = vWagonCounter); - - END WHILE; - - ELSE - - UPDATE tmp.ticket - SET shelve = 1, wagon = vWagonCounter - WHERE ticketFk = vFirstTicketFk; - - DELETE FROM tmp.ticketShelve - WHERE ticketFk = vFirstTicketFk - AND wagon != vWagonCounter; - - END IF; - - END WHILE; - - -- Eliminamos los que se han quedado sin balda - DELETE FROM tmp.ticket WHERE shelve = 0; - - -- Elimina los tickets bloqueados que no se van a preparar - DELETE tc.* - FROM vn.ticketCollection tc - LEFT JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk - WHERE tc.collectionFk = vCollectionFk - AND t.ticketFk IS NULL; - - -- Elimina los tickets que ya estan en otra coleccion - DELETE tc.* - FROM vn.ticketCollection tc - JOIN vn.ticketCollection tc2 ON tc2.ticketFk = tc.ticketFk - WHERE tc.collectionFk = vCollectionFk - AND tc2.collectionFk != vCollectionFk; - - -- Actualiza el estado de la colección - UPDATE vn.collection c - JOIN vn.state st ON st.code = 'ON_PREPARATION' - SET c.stateFk = st.id - WHERE c.id = vCollectionFk; - - -- Asigna las bandejas - UPDATE vn.ticketCollection tc - JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk - SET tc.level = t.shelve, tc.wagon = t.wagon; - - -- Actualiza el estado de los tickets - INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - SELECT vStateFk, ticketFk, account.myUser_getId() - FROM vn.ticketCollection tc - WHERE tc.collectionFk = vCollectionFk; - - -- Aviso para la preparacion previa - INSERT INTO vn.ticketDown(ticketFk, collectionFk) - SELECT tc.ticketFk, tc.collectionFk - FROM vn.ticketCollection tc - WHERE tc.collectionFk = vCollectionFk; - - IF (SELECT count(*) FROM vn.ticketCollection WHERE collectionFk = vCollectionFk) THEN - - CALL vn.salesMerge_byCollection(vCollectionFk); - - UPDATE vn.collection c - JOIN (SELECT count(*) saleTotalCount , - sum(s.isPicked != 0) salePickedCount - FROM vn.ticketCollection tc - JOIN vn.sale s ON s.ticketFk = tc.ticketFk - WHERE tc.collectionFk = vCollectionFk - AND s.quantity > 0 - ) sub - SET c.saleTotalCount = sub.saleTotalCount, - c.salePickedCount = sub.salePickedCount - WHERE c.id = vCollectionFk; - - SELECT vCollectionFk; - - ELSE - - DELETE FROM vn.collection WHERE id = vCollectionFk; - -- SELECT NULL; - - END IF; - - DROP TEMPORARY TABLE tmp.ticketToSplit; - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51008,6 +53355,44 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `company_getFiscaldata` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `company_getFiscaldata`(workerFk INT) +BEGIN + +DECLARE vCompanyFk INT; + + SELECT IFNULL(uc.companyFk, rc.defaultCompanyFk) + INTO vCompanyFk + FROM vn.routeConfig rc + LEFT JOIN userConfig uc ON uc.userFk = workerFk; + + + SELECT + s.name AS name , + s.NIF AS nif , + s.street AS street , + s.city AS city , + s.postCode AS postCode + + FROM vn.company c + JOIN vn.worker w ON w.id = c.workerManagerFk + JOIN vn.supplier s ON s.id = c.id + WHERE c.id = vCompanyFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `conveyorExpedition_Add` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -51018,60 +53403,54 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `conveyorExpedition_Add`(vDate DATE) +CREATE DEFINER=`root`@`%` PROCEDURE `conveyorExpedition_Add`(vStarted DATETIME, vEnded DATETIME) BEGIN + + DECLARE startingMinute INT; + TRUNCATE vn.conveyorExpedition; INSERT INTO vn.conveyorExpedition( expeditionFk, created, - conveyorBuildingClassFk, length, width, height, - routeFk) + routeFk, + productionMinute, + truck, + criterion, + conveyorBuildingClassFk) SELECT e.id, e.created, - IF(e.itemFk = 94,1,4), 10 * p.depth as depth, 10 * p.width as width, 10 * p.height as height, - IFNULL(t.routeFk,am.agencyFk) routeFk + IFNULL(t.routeFk,am.agencyFk) routeFk, + hour(e.created) * 60 + minute(e.created), + IFNULL(et.description , a.name), + IFNULL(t.routeFk,am.agencyFk) criterion, + IFNULL(p.conveyorBuildingClassFk , pc.defaultConveyorBuildingClass) FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk JOIN vn.packaging p ON p.id = e.packagingFk LEFT JOIN vn.zone z ON z.id = t.zoneFk LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk - WHERE t.warehouseFk IN (60,1) - AND t.shipped BETWEEN vDate AND util.dayend(vDate) - AND p.height < 160 + LEFT JOIN vn.agency a ON a.id = am.agencyFk + LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk + LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk + JOIN vn.packagingConfig pc + WHERE t.warehouseFk IN (60,1,44) + AND e.created BETWEEN vStarted AND vEnded + AND p.height < 140 AND p.width < 60 AND p.depth < 125; - - INSERT INTO vn.conveyorExpedition( expeditionFk, - created, - conveyorBuildingClassFk, - length, - width, - height, - routeFk) - SELECT e.id, - e.created, - 5, - 10 * p.depth as depth, - 10 * p.width as width, - 10 * p.height as height, - IFNULL(t.routeFk,am.agencyFk) routeFk - FROM vn.expedition e - JOIN vn.ticket t ON t.id = e.ticketFk - JOIN vn.packaging p ON p.id = e.packagingFk - LEFT JOIN vn.zone z ON z.id = t.zoneFk - LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk - WHERE t.warehouseFk = 44 - AND t.shipped BETWEEN vDate AND util.dayend(vDate) - AND p.height < 160 - AND p.width < 60 - AND p.depth < 125; + + SELECT MIN(productionMinute) INTO startingMinute + FROM vn.conveyorExpedition ce ; + + UPDATE vn.conveyorExpedition + SET productionMinute = productionMinute - startingMinute; END ;; DELIMITER ; @@ -51398,9 +53777,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -51745,6 +54124,65 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `deviceProductionUser_getWorker` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `deviceProductionUser_getWorker`(vAndroid_id VARCHAR(50)) +BEGIN +/** + * Selecciona si hay registrado un device con un android_id + * + * @param vAndroid_id el número android_id del dispositivo + * + */ + + SELECT account.user_getNameFromId(dpu.userFk) + FROM deviceProductionUser dpu + JOIN deviceProduction dp ON dpu.deviceProductionFk = dp.id + WHERE dp.android_id = vAndroid_id; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `deviceProduction_getnameDevice` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `deviceProduction_getnameDevice`(vAndroid_id VARCHAR(50)) +BEGIN +/** + * Selecciona el id del dispositivo que corresponde al vAndroid_id + * + * @param vAndroid_id el número android_id del dispositivo + * + */ + + SELECT dp.id + FROM deviceProduction dp + WHERE dp.android_id = vAndroid_id; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `duaEntryValueUpdate` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -52688,10 +55126,10 @@ BEGIN `input` = vInput, `period` = DATE_FORMAT(NOW(), '%Y-%m-%d %H:00:00'), `activeTime` = vActiveTime, - `consumption` = IFNULL((vConsumption / 3600) * vActiveTime, 0) + `consumption` = CAST(IFNULL((vConsumption / 3600) * vActiveTime, 0) AS DECIMAL(10,2)) ON DUPLICATE KEY UPDATE `activeTime` = `activeTime` + vActiveTime, - `consumption` = `consumption` + VALUES(`consumption`); + `consumption` = `consumption` + CAST(VALUES(`consumption`) AS DECIMAL(10,2)); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53115,17 +55553,17 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `entryVolume` */; +/*!50003 DROP PROCEDURE IF EXISTS `entryVolume__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `entryVolume`(vEntryFk INT) +CREATE DEFINER=`root`@`%` PROCEDURE `entryVolume__`(vEntryFk INT) BEGIN SELECT ELT(it.temperature + 1,'Calientes','Frios','Secos') AS Temp, @@ -53426,18 +55864,37 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `expeditionPallet_PrintSet`(vPalletFk INT) +CREATE DEFINER=`root`@`%` PROCEDURE `expeditionPallet_PrintSet`(vPalletFk INT,vSectorFk INT) BEGIN + DECLARE vLabel INT; + DECLARE vPrinterFk INT; + UPDATE vn.expeditionPallet SET isPrint = FALSE - WHERE id = vPalletFk; + WHERE id = vPalletFk; + + SELECT labelReportFk + INTO vLabel + FROM sector + WHERE id=vSectorFk; + + SELECT printerFk + INTO vPrinterFk + FROM sector + WHERE id=vSectorFk; + + + INSERT INTO vn2008.Colas +(Id_Cola, Id_Impresora, Id_Prioridad, Id_Informe, Id_Estado, Hora_Inicio, Hora_Fin, Cola, Id_Trabajador, Cola2, Cola3, error) +VALUES(NULL, vPrinterFK, NULL, vLabel, 1, NULL, NULL, vPalletFk, NULL, vSectorFk, NULL, NULL); + END ;; DELIMITER ; @@ -53672,6 +56129,76 @@ BEGIN SET exp.checked = vChecked WHERE exp.id = vExpeditionFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `expedition_getState` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `expedition_getState`(vExpeditionFk INT) +BEGIN + + DECLARE vTicketsPendientes INT; + DECLARE vEtiquetasTotales INT; + DECLARE vEtiquetasEscaneadas INT; + DECLARE vRouteFk INT; + + SELECT t.routeFk INTO vRouteFk + FROM vn.ticket t + JOIN vn.expedition e ON e.ticketFk = t.id + WHERE e.id = vExpeditionFk; + + SELECT COUNT(*) INTO vTicketsPendientes + FROM vn.ticket t + LEFT JOIN vn.expedition e ON e.ticketFk = t.id + WHERE t.routeFk = vRouteFk + AND ISNULL(e.id); + + SELECT COUNT(*) INTO vEtiquetasTotales + FROM vn.expedition e + JOIN vn.ticket t ON t.id = e.ticketFk + WHERE t.routeFk = vRouteFk; + + SELECT COUNT(*) INTO vEtiquetasEscaneadas + FROM vn.expeditionScan es + JOIN vn.expedition e ON e.id = es.expeditionFk + JOIN vn.ticket t ON t.id = e.ticketFk + WHERE t.routeFk = vRouteFk; + + SELECT e.ticketFk ticket, + t.nickname cliente, + a.city ciudad, + p.name provincia, + z.name zonaTicket, + am.name zonaRuta, + t.routeFk ruta, + rm.beachFk ubicacion, + et.ETD , + et.description camion, + vTicketsPendientes AS ticketsPendientes, + vEtiquetasTotales AS etiquetasTotales, + vEtiquetasEscaneadas AS etiquetasEscaneadas + FROM vn.expedition e + JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p ON p.id = a.provinceFk + JOIN vn.`zone`z ON z.id = t.zoneFk + LEFT JOIN vn.route r ON r.id = t.routeFk + LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id + LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk + WHERE e.id = vExpeditionFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53763,13 +56290,39 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `freelance_getInfo` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `freelance_getInfo`(workerFk INT) +BEGIN + SELECT s.name, s.street, s.city, s.nif, s.postCode + FROM route r + JOIN agencyMode am ON r.agencyModeFk = am.id + JOIN agency a ON am.agencyFk = a.id + JOIN supplier s ON a.supplierFk = s.id + WHERE r.workerFk = workerFk + ORDER BY r.id DESC + LIMIT 1; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `fustControl` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -53801,7 +56354,7 @@ BEGIN JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = t.warehouseFk JOIN vn.buy b ON b.id = lb.buy_id JOIN vn.packaging p ON p.id = b.packageFk - LEFT JOIN vn.packageEquivalent pe ON pe.packageFk = p.id + LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id JOIN vn.address a ON a.id = t.addressFk JOIN vn.province p2 ON p2.id = a.provinceFk JOIN vn.country c ON c.id = p2.countryFk @@ -53819,7 +56372,7 @@ BEGIN JOIN vn.warehouse w ON w.id = t.warehouseFk JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk JOIN vn.packaging p ON p.id = tp.packagingFk - LEFT JOIN vn.packageEquivalent pe ON pe.packageFk = p.id + LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id JOIN vn.address a ON a.id = t.addressFk JOIN vn.province p2 ON p2.id = a.provinceFk JOIN vn.country c ON c.id = p2.countryFk @@ -53839,7 +56392,7 @@ BEGIN JOIN vn.warehouse w ON w.id = t.warehouseFk JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk JOIN vn.packaging p ON p.id = tp.packagingFk - LEFT JOIN vn.packageEquivalent pe ON pe.packageFk = p.id + LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id WHERE t.shipped BETWEEN TIMESTAMPADD(DAY, 1, vDateStart ) AND TIMESTAMPADD(DAY, 1, vDateEnd ) AND wa.name = 'VNH' AND p.isPackageReturnable @@ -53859,9 +56412,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -53887,11 +56440,11 @@ BEGIN JOIN vn.warehouse w ON w.id = t.warehouseFk JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk JOIN vn.packaging p ON p.id = tp.packagingFk - LEFT JOIN vn.packageEquivalent pe ON pe.packageFk = p.id + LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id JOIN vn.address a ON a.id = t.addressFk JOIN vn.province p2 ON p2.id = a.provinceFk JOIN vn.country c ON c.id = p2.countryFk - WHERE t.shipped BETWEEN '2021-05-04' AND '2021-05-06' + WHERE t.shipped BETWEEN vFromDated AND util.dayend(vToDated) AND wa.name = 'VNH' AND p.isPackageReturnable AND c.country = 'FRANCIA' @@ -54820,6 +57373,130 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `inventory_repair` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `inventory_repair`() +BEGIN + + DROP TEMPORARY TABLE IF EXISTS tmp.lastEntry; + CREATE TEMPORARY TABLE tmp.lastEntry + (PRIMARY KEY (buyFk)) + SELECT + i.id AS itemFk, + w.id AS warehouseFk, + w.name AS warehouse, + tr.landed, + b.id AS buyFk, + b.entryFk, + b.isIgnored, + b.price2, + b.price3, + b.stickers, + b.packing, + b.grouping, + b.groupingMode, + b.weight, + i.stems, + b.quantity, + b.buyingValue, + b.packageFk , + s.id AS supplierFk, + s.name AS supplier + FROM itemType it + RIGHT JOIN (entry e + LEFT JOIN supplier s ON s.id = e.supplierFk + RIGHT JOIN buy b ON b.entryFk = e.id + LEFT JOIN item i ON i.id = b.itemFk + LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN travel tr ON tr.id = e.travelFk + LEFT JOIN warehouse w ON w.id = tr.warehouseInFk + LEFT JOIN origin o ON o.id = i.originFk + ) ON it.id = i.typeFk + LEFT JOIN edi.ekt ek ON b.ektFk = ek.id + WHERE (b.packageFk = "--" OR b.price2 = 0 OR b.packing = 0 OR b.buyingValue = 0) AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-1,CURDATE())) AND s.name = 'INVENTARIO'; + + DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOk; + CREATE TEMPORARY TABLE tmp.lastEntryOk + (PRIMARY KEY (buyFk)) + SELECT + i.id AS itemFk, + w.id AS warehouseFk, + w.name AS warehouse, + tr.landed, + b.id AS buyFk, + b.entryFk, + b.isIgnored, + b.price2, + b.price3, + b.stickers, + b.packing, + b.grouping, + b.groupingMode, + b.weight, + i.stems, + b.quantity, + b.buyingValue, + b.packageFk , + s.id AS supplierFk, + s.name AS supplier + FROM itemType it + RIGHT JOIN (entry e + LEFT JOIN supplier s ON s.id = e.supplierFk + RIGHT JOIN buy b ON b.entryFk = e.id + LEFT JOIN item i ON i.id = b.itemFk + LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN travel tr ON tr.id = e.travelFk + LEFT JOIN warehouse w ON w.id = tr.warehouseInFk + LEFT JOIN origin o ON o.id = i.originFk + ) ON it.id = i.typeFk + LEFT JOIN edi.ekt ek ON b.ektFk = ek.id + WHERE b.packageFk != "--" AND b.price2 != 0 AND b.packing != 0 AND b.buyingValue > 0 AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-2,CURDATE())) + ORDER BY tr.landed DESC; + + DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOkGroup; + CREATE TEMPORARY TABLE tmp.lastEntryOkGroup + (INDEX (warehouseFk,itemFk)) + SELECT * + FROM tmp.lastEntryOk tmp + GROUP BY tmp.itemFk,tmp.warehouseFk; + + UPDATE buy b + JOIN tmp.lastEntry lt ON lt.buyFk = b.id + JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk + SET b.packageFk = eo.packageFk WHERE b.packageFk = "--"; + + UPDATE buy b + JOIN tmp.lastEntry lt ON lt.buyFk = b.id + JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk + SET b.price2 = eo.price2 WHERE b.price2 = 0 ; + + UPDATE buy b + JOIN tmp.lastEntry lt ON lt.buyFk = b.id + JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk + SET b.packing = eo.packing WHERE b.packing = 0; + + UPDATE buy b + JOIN tmp.lastEntry lt ON lt.buyFk = b.id + JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk + SET b.buyingValue = eo.buyingValue WHERE b.buyingValue = 0; + + DROP TEMPORARY TABLE tmp.lastEntry; + DROP TEMPORARY TABLE tmp.lastEntryOk; + DROP TEMPORARY TABLE tmp.lastEntryOkGroup; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `invoiceExpenceMake` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -54905,7 +57582,7 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `invoiceFromAddress` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -54937,9 +57614,9 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 DROP PROCEDURE IF EXISTS `invoiceFromClient` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -54974,7 +57651,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 DROP PROCEDURE IF EXISTS `invoiceFromTicket` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -55872,17 +58549,68 @@ BEGIN IF !(SELECT COUNT(*) FROM invoiceInDueDay iid WHERE iid.invoiceInFk = vInvoiceInFk) THEN - + INSERT INTO invoiceInDueDay (invoiceInFk, dueDated, amount, foreignValue) SELECT vInvoiceInFk, - IF(payDay, vn2008.next_venc(issued, detalle, payDay),TIMESTAMPADD(DAY, detalle, issued)), + IF(payDay, vn2008.next_venc(created, detalle, payDay),TIMESTAMPADD(DAY, GREATEST(detalle, 2), created)), IF((@cont:=@cont + 1) < cont, TRUNCATE(venc / cont, 2),venc-(TRUNCATE(venc / cont, 2) * (cont - 1))), IF(@cont < cont, TRUNCATE(foreignValue / cont, 2), foreignValue - (TRUNCATE(foreignValue / cont, 2) * (cont - 1))) - FROM ( - SELECT SUM((1 + (ti.PorcentajeIva / 100)*(s.countryFk = s2.countryFk)) * iit.taxableBase)/COUNT(DISTINCT(pdd.detalle)) venc, + FROM ( SELECT SUM((1 + (IFNULL(ti.PorcentajeIva, 0) / 100)*(s.countryFk = s2.countryFk)) * iit.taxableBase)/COUNT(DISTINCT(pdd.detalle)) venc, + SUM(iit.foreignValue)/COUNT(DISTINCT(pdd.detalle)) foreignValue, + s.payDemFk, + ii.companyFk, + COUNT(DISTINCT(pdd.detalle)) cont, + s.payDay, + DATE(ii.created) created + FROM invoiceIn ii + JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id + LEFT JOIN sage.TiposIva AS ti ON ti.CodigoIva= iit.taxTypeSageFk + JOIN supplier s ON s.id = ii.supplierFk + JOIN supplier s2 ON s2.id = ii.companyFk + JOIN vn2008.pay_dem_det pdd ON pdd.id = s.payDemFk + WHERE ii.id = vInvoiceInFk + GROUP BY ii.id + ) sub + JOIN (SELECT @cont:=0) sub2 + JOIN vn2008.pay_dem_det pdd ON pdd.id = sub.payDemFk + GROUP BY detalle; + END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceInDueDay_calculate__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceInDueDay_calculate__`(vInvoiceInFk INT) +BEGIN + + IF !(SELECT COUNT(*) + FROM invoiceInDueDay iid + WHERE iid.invoiceInFk = vInvoiceInFk) THEN + + INSERT INTO invoiceInDueDay (invoiceInFk, + dueDated, + amount, + foreignValue) + SELECT vInvoiceInFk, + IF(payDay, vn2008.next_venc(issued, detalle, payDay),TIMESTAMPADD(DAY, GREATEST(detalle, 2), issued)), + IF((@cont:=@cont + 1) < cont, TRUNCATE(venc / cont, 2),venc-(TRUNCATE(venc / cont, 2) * (cont - 1))), + IF(@cont < cont, TRUNCATE(foreignValue / cont, 2), foreignValue - (TRUNCATE(foreignValue / cont, 2) * (cont - 1))) + FROM ( SELECT SUM((1 + (IFNULL(ti.PorcentajeIva, 0) / 100)*(s.countryFk = s2.countryFk)) * iit.taxableBase)/COUNT(DISTINCT(pdd.detalle)) venc, SUM(iit.foreignValue)/COUNT(DISTINCT(pdd.detalle)) foreignValue, s.payDemFk, ii.companyFk, @@ -55891,18 +58619,18 @@ BEGIN ii.issued FROM invoiceIn ii JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id - JOIN sage.TiposIva AS ti ON ti.CodigoIva= iit.taxTypeSageFk + LEFT JOIN sage.TiposIva AS ti ON ti.CodigoIva= iit.taxTypeSageFk JOIN supplier s ON s.id = ii.supplierFk JOIN supplier s2 ON s2.id = ii.companyFk JOIN vn2008.pay_dem_det pdd ON pdd.id = s.payDemFk WHERE ii.id = vInvoiceInFk GROUP BY ii.id - ) sub + ) sub JOIN (SELECT @cont:=0) sub2 - JOIN vn2008.pay_dem_det pdd ON pdd.id = sub.payDemFk + JOIN vn2008.pay_dem_det pdd ON pdd.id = sub.payDemFk GROUP BY detalle; END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56423,13 +59151,87 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutDelete`(vRef VARCHAR(15)) +BEGIN + DECLARE vAsien INTEGER; + DECLARE vSendMail BOOL; + DECLARE vBody TEXT; + + SELECT ASIEN INTO vAsien + FROM XDiario + WHERE SERIE = SUBSTRING(vRef, 1, 1) + AND FACTURA = SUBSTRING(vRef, 2, LENGTH(vRef)-1) + LIMIT 1; + + SELECT IF(enlazado OR enlazadoSage, TRUE, FALSE), + CONCAT(' + + + + + + + ', + GROUP_CONCAT(CONCAT(' + + + + + + + ' + ) SEPARATOR ' ' + ), + '
FECHASUBCTACONTRACONCEPTOEURODEBEEUROHABER
', IFNULL(FECHA,''), '', IFNULL(SUBCTA,''), '', IFNULL(CONTRA,''), '', IFNULL(CONCEPTO,''), '', IFNULL(EURODEBE,''), '', IFNULL(EUROHABER,''), '
') + INTO vSendMail, vBody + FROM XDiario + WHERE ASIEN = vAsien; + + DELETE FROM XDiario + WHERE ASIEN = vAsien; + + IF vSendMail THEN + INSERT INTO mail(sender, replyTo, `subject`, body) + SELECT 'administracion@verdnatura.es', + 'noreply@verdnatura.es', + CONCAT('Eliminada factura ' ,vRef), + CONCAT('
+

Se ha eliminado el asiento ', vAsien, ' que estaba enlazado en SAGE/CONTAPLUS, vinculado a la factura ', vRef ,'

+ ', vBody, ' +
'); + END IF; + + UPDATE ticket + SET refFk = NULL + WHERE refFk = vRef; + + DELETE + FROM invoiceOut + WHERE ref = vRef; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutDelete__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutDelete__`(vRef VARCHAR(15)) BEGIN UPDATE ticket @@ -56446,17 +59248,17 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutFix_BI_RE_IVA` */; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutFix_BI_RE_IVA__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutFix_BI_RE_IVA`() +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutFix_BI_RE_IVA__`() BEGIN DECLARE done BOOL DEFAULT FALSE; @@ -56822,13 +59624,74 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOut_newFromClient`(vClientFk INT, vSerial CHAR(1), vShipped DATE, vCompanyFk INT, vTaxArea VARCHAR(25), OUT vInvoiceId INT) +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOut_newFromClient`(vClientFk INT, vSerial CHAR(2), vMaxShipped DATE, vCompanyFk INT, vTaxArea VARCHAR(25), vRef VARCHAR(25), OUT vInvoiceId INT) +BEGIN +/** + * Factura los tickets de un cliente hasta una fecha dada + * @param vClientFk Id del cliente a facturar + * @param vSerial Serie de factura + * @param vMaxShipped Fecha hasta la cual cogera tickets para facturar + * @param vCompanyFk Id de la empresa desde la que se factura + * @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; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF vRef 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; + + START TRANSACTION; + CALL invoiceFromClient(vMaxShipped, vClientFk, vCompanyFk); + CALL invoiceOut_new(vSerial, 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); + INSERT INTO printServerQueue(priorityFk, labelReportFk, param1) VALUES(1, 3, vInvoiceId); + END IF; + COMMIT; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceOut_newFromClient__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOut_newFromClient__`(vClientFk INT, vSerial CHAR(1), vShipped DATE, vCompanyFk INT, vTaxArea VARCHAR(25), OUT vInvoiceId INT) BEGIN /** * Factura los tickets de un cliente @@ -56853,13 +59716,13 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOut_newFromTicket`(vTicketFk INT, vSerial CHAR(1), vTaxArea VARCHAR(25), vRef VARCHAR(25), OUT vInvoiceId INT) +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOut_newFromTicket`(vTicketFk INT, vSerial CHAR(2), vTaxArea VARCHAR(25), vRef VARCHAR(25), OUT vInvoiceId INT) BEGIN /** * Factura un ticket @@ -56896,7 +59759,7 @@ BEGIN IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN CALL invoiceOutBooking(vInvoiceId); IF account.myUser_getId() IS NOT NULL THEN - INSERT INTO printServerQueue(priorityFk, reportFk, param1, workerFk) VALUES(1, 3, vInvoiceId, account.myUser_getId()); + INSERT INTO printServerQueue(priorityFk, labelReportFk, param1, workerFk) VALUES(1, 3, vInvoiceId, account.myUser_getId()); END IF; END IF; @@ -57200,9 +60063,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -57262,7 +60125,8 @@ BEGIN c.`grouping` as `grouping`, c.Packing as packing, CONCAT('https://verdnatura.es/vn-image-data/catalog/200x200/', i.image) as urlImage200, - CONCAT('https://verdnatura.es/vn-image-data/catalog/1600x900/', i.image) as urlImage + CONCAT('https://verdnatura.es/vn-image-data/catalog/1600x900/', i.image) as urlImage, + i.itemPackingTypeFk FROM vn.item i LEFT JOIN vn.producer p ON p.id = i.producerFk LEFT JOIN vn.origin o ON o.id = i.originFk @@ -57285,7 +60149,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemDiary` */; +/*!50003 DROP PROCEDURE IF EXISTS `itemDiary__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -57295,7 +60159,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `itemDiary`(IN vItemId INT, IN vWarehouse INT) +CREATE DEFINER=`root`@`%` PROCEDURE `itemDiary__`(IN vItemId INT, IN vWarehouse INT) BEGIN DECLARE vDateInventory DATETIME; DECLARE vCurdate DATE DEFAULT CURDATE(); @@ -57335,7 +60199,7 @@ BEGIN JOIN entry e ON e.id = b.entryFk JOIN travel tr ON tr.id = e.travelFk JOIN supplier s ON s.id = e.supplierFk - JOIN alertLevel al ON al.alertLevel = + JOIN alertLevel al ON al.id = CASE WHEN tr.isReceived != FALSE THEN 3 WHEN tr.isDelivered THEN 1 @@ -57365,7 +60229,7 @@ BEGIN JOIN travel tr ON tr.id = e.travelFk JOIN warehouse w ON w.id = tr.warehouseOutFk JOIN supplier s ON s.id = e.supplierFk - JOIN alertLevel al ON al.alertLevel = + JOIN alertLevel al ON al.id = CASE WHEN tr.isReceived != FALSE THEN 3 WHEN tr.isDelivered THEN 1 @@ -57384,7 +60248,7 @@ BEGIN SELECT t.shipped as date, NULL as `in`, s.quantity as `out`, - al.alertLevel as alertLevel, + al.id as alertLevel, st.name AS stateName, t.nickname as name, t.refFk as reference, @@ -57397,7 +60261,7 @@ BEGIN LEFT JOIN ticketState ts ON ts.ticket = t.id LEFT JOIN state st ON st.code = ts.code JOIN client c ON c.id = t.clientFk - JOIN alertLevel al ON al.alertLevel = + JOIN alertLevel al ON al.id = CASE WHEN t.shipped < vCurdate THEN 3 WHEN t.shipped > vDayEnd THEN 0 @@ -57415,127 +60279,43 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemDiary__` */; +/*!50003 DROP PROCEDURE IF EXISTS `itemFreight_Show` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `itemDiary__`(IN vItemId INT, IN vWarehouse INT) +CREATE DEFINER=`root`@`%` PROCEDURE `itemFreight_Show`(vItemFk INT, vWarehouseFk INT) BEGIN - -- BERNAT WORKING IN THIS FILE - DECLARE vDateInventory DATETIME; - DECLARE vCurdate DATE DEFAULT CURDATE(); - DECLARE vDayEnd DATETIME DEFAULT util.dayEnd(vCurdate); - -- traduccion: date, alertLevel, origin, reference, name, In, Out, Balance - SELECT Fechainventario INTO vDateInventory FROM vn2008.tblContadores; - SET @a = 0; - SELECT DATE(date) AS date, - alertLevel, - stateName, - origin, - reference, - clientFk, - name, - `in`, - `out`, - @a := @a + IFNULL(`in`,0) - IFNULL(`out`,0) as balance, - isPicked, - isTicket - FROM - ( SELECT tr.landed as date, - b.quantity as `in`, - NULL as `out`, - IF(tr.isReceived != FALSE,3, IF(tr.isDelivered,1,0)) as alertLevel, - st.name AS stateName, - s.name as name, - e.ref as reference, - e.id as origin, - s.id as clientFk, - TRUE isPicked, - FALSE AS isTicket - FROM vn.buy b - JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.supplier s ON s.id = e.supplierFk - JOIN vn.alertLevel al ON al.alertLevel = - CASE - WHEN tr.isReceived != FALSE THEN 3 - WHEN tr.isDelivered THEN 1 - ELSE 0 - END - JOIN vn.state st ON st.code = al.code - WHERE tr.landed >= vDateInventory - AND vWarehouse = tr.warehouseInFk - AND b.itemFk = vItemId - AND e.isInventory = 0 - AND e.isRaid = 0 - UNION ALL - - SELECT tr.shipped as date, - NULL as `in`, - b.quantity as `out`, - IF(tr.isReceived != FALSE,3, IF(tr.isDelivered,1,0)) as alertLevel, - st.name AS stateName, - s.name as name, - e.ref as reference, - e.id as origin, - s.id as clientFk, - TRUE isPicked, - FALSE AS isTicket - FROM vn.buy b - JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.warehouse w ON w.id = tr.warehouseOutFk - JOIN vn.supplier s ON s.id = e.supplierFk - JOIN vn.alertLevel al ON al.alertLevel = - CASE - WHEN tr.isReceived != FALSE THEN 3 - WHEN tr.isDelivered THEN 1 - ELSE 0 - END - JOIN vn.state st ON st.code = al.code - WHERE tr.shipped >= vDateInventory - AND vWarehouse =tr.warehouseOutFk - AND s.id <> 4 - AND b.itemFk = vItemId - AND e.isInventory = 0 - AND w.isFeedStock = 0 - AND e.isRaid = 0 - UNION ALL - - SELECT t.shipped as date, - NULL as `in`, - s.quantity as `out`, - al.alertLevel as alertLevel, - st.name AS stateName, - t.nickname as name, - t.refFk as reference, - t.id as origin, - t.clientFk, - stk.id as isPicked, -- TRUE as isPicked - TRUE as isTicket - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - LEFT JOIN vn.ticketState ts ON ts.ticket = t.id - JOIN vn.client c ON c.id = t.clientFk - JOIN vn.alertLevel al ON al.alertLevel = - CASE - WHEN t.shipped < vCurdate THEN 3 - WHEN t.shipped > vDayEnd THEN 0 - ELSE IFNULL(ts.alertLevel, 0) - END - JOIN vn.state st ON st.code = al.code - LEFT JOIN vn.saleTracking stk ON stk.saleFk = s.id AND stk.stateFk = 14 -- comentar - WHERE t.shipped >= vDateInventory - AND s.itemFk = vItemId - AND vWarehouse =t.warehouseFk - ) AS itemDiary - ORDER BY date, isTicket, alertLevel DESC, isPicked DESC, `in` DESC, `out` DESC; + + SELECT cm3 Volumen_Entrada, + cm3delivery Volumen_Salida, + i.compression Compresion_del_Articulo, + it.compression Compresion_del_Tipo, + p.volume Volumen_del_embalaje, + p.width Ancho_del_embalaje, + p.`depth` Largo_del_embalaje, + b.packageFk , + IFNULL(p.height, i.`size`) + 10 Altura, + b.packing Packing_Entrada, + i.packingOut Packing_Salida, + i.id itemFk, + b.id buyFk, + b.entryFk, + w.name warehouseFk + FROM vn.itemCost ic + JOIN vn.item i ON i.id = ic.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + LEFT JOIN cache.last_buy lb ON lb.item_id = ic.itemFk AND lb.warehouse_id = ic.warehouseFk + LEFT JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN vn.packaging p ON p.id = b.packageFk + LEFT JOIN vn.warehouse w ON w.id = ic.warehouseFk + WHERE ic.itemFk = vItemFk + AND ic.warehouseFk = vWarehouseFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57947,14 +60727,19 @@ DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `itemPlacementSupplyStockGetTargetList`(vItemFk INT,vSectorFk INT) BEGIN - DECLARE vWarehouseFk INT; + -- DECLARE vWarehouseFk INT; DECLARE vWarehouseAliasFk INT; - + /* SELECT s.warehouseFk , w.aliasFk INTO vWarehouseFk, vWarehouseAliasFk FROM vn.sector s JOIN vn.warehouse w ON w.id = s.warehouseFk WHERE s.id = vSectorFk; - + */ + SELECT w.aliasFk INTO vWarehouseAliasFk + FROM vn.sector s + JOIN vn.warehouse w ON w.id = s.warehouseFk + WHERE s.id = vSectorFk; + SELECT ish.shelvingFk shelving, p.code parking, sum(ish.visible) as stockTotal, @@ -57963,7 +60748,7 @@ BEGIN FROM vn.itemShelving ish JOIN vn.shelving sh ON sh.code = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk - LEFT JOIN vn.coolerPathDetail cpd ON CAST(cpd.hallway AS DECIMAL(3,0)) = p.column + -- LEFT JOIN vn.coolerPathDetail cpd ON CAST(cpd.hallway AS DECIMAL(3,0)) = p.column JOIN vn.sector sc ON sc.id = p.sectorFk JOIN vn.warehouse w ON w.id = sc.warehouseFk WHERE w.aliasFk = vWarehouseAliasFk @@ -57971,42 +60756,6 @@ BEGIN AND ish.itemFk = vItemFk GROUP BY ish.id ORDER BY ish.priority DESC; - /* - SELECT shelving, parking, sum(visible) as stockTotal,created,`order` - FROM - ( - SELECT `ispss`.`itemShelvingFk` AS `itemShelvingFk`, - `ispss`.`itemFk` AS `itemFk`, - `ispss`.`quantity` AS `quantity`, - `ispss`.`packing` AS `packing`, - `ispss`.`stock` AS `stock`, - `ispss`.`longName` AS `longName`, - `ispss`.`size` AS `size`, - `ispss`.`subName` AS `subName`, - `ispss`.`shelving` AS `shelving`, - `ispss`.`parking` AS `parking`, - `ispss`.`created` AS `created`, - `ispss`.`priority` AS `priority`, - `ispss`.`parkingFk` AS `parkingFk`, - `ispss`.`sectorFk` AS `sectorFk`, - IFNULL(p.pickingOrder,0) as `order` - FROM vn.itemShelvingPlacementSupplyStock ispss - JOIN vn.itemShelving ish ON ish.itemFk = vItemFk - JOIN vn.shelving sh ON sh.code = ish.shelvingFk - JOIN vn.parking p ON p.id = sh.parkingFk - LEFT JOIN vn.coolerPathDetail cpd ON CAST(cpd.hallway AS DECIMAL(3,0)) = p.column - JOIN vn.sector sc ON sc.id = p.sectorFk - JOIN vn.warehouse w ON w.id = sc.warehouseFk - WHERE ispss.itemFk = vItemFk - AND w.aliasFk = vWarehouseAliasFk - -- AND p.sectorFk = vSectorFk - AND stock > 0 - AND ispss.sectorFk IN (SELECT id FROM vn.sector WHERE warehouseFk = vWarehouseFk) - ORDER BY priority DESC - ) sub - GROUP BY shelving - ORDER BY parking ASC; - */ END ;; @@ -58219,7 +60968,7 @@ BEGIN DECLARE vGrouping INT; DECLARE vBox INT; DECLARE vPacking INT; - DECLARE vRoundQuantity INT; + DECLARE vRoundQuantity INT DEFAULT 1; SELECT s.ticketFk, LEAST(s.quantity, vQuantity), s.itemFk,t.shipped,t.warehouseFk INTO vTicketFk, vQuantity, vItemFk,vDate,vWarehouseFk @@ -59327,18 +62076,109 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingRadar_Urgent`(vWorkerFk INT) BEGIN - + DECLARE vCalcVisibleFk INT; + DECLARE vWarehouseFk INT DEFAULT 60; + -- Eliminar cuando tengamos programador de Android - DECLARE vCalcVisibleFk INT; + CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk); + + SELECT * FROM + (SELECT sub.itemFk, + sub.longName, + CONCAT('Hoy saldrán ', CAST(sub2.pendiente AS DECIMAL(10,0)), ' unidades.') `size`, + CONCAT(IF(sub2.itemFk, IF(sub2.pendiente > (sub.upstairs + sub.downstairs),'(1) ','(2) '),'(3) ' ),sub.producer) producer, + sub.upstairs, + sub.downstairs, + sub.visible, + sub.sectorFk, + CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) nicho + FROM (SELECT iss.itemFk, + CONCAT(i.longName,' ',i.size,' ',IFNULL(i.subName,'') ) longName, + '' size, + CONCAT(iss.parkingCode , ' ', iss.shelvingFk) producer, + 0 upstairs, + SUM(IFNULL(iss.visible,0)) downstairs, + IF(it.isPackaging, null, IFNULL(v.visible,0)) visible, + 0 sectorFk + FROM itemShelvingStock iss + JOIN sector s ON s.id = iss.sectorFk + JOIN item i on i.id = iss.itemFk + JOIN itemType it ON it.id = i.typeFk + LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk + WHERE s.warehouseFk = vWarehouseFk + AND it.workerFk = vWorkerFk + GROUP BY itemFk + ) sub LEFT JOIN (SELECT s.itemFk, SUM(s.quantity) pendiente + FROM sale s + LEFT JOIN saleTracking st ON st.saleFk = s.id + JOIN ticket t ON t.id = s.ticketFk + JOIN client c on c.id = t.clientFk + JOIN clientType ct ON ct.id = c.clientTypeFk + WHERE t.shipped BETWEEN CURDATE() AND util.dayend(CURDATE()) + AND ISNULL(st.saleFk) + AND ct.code IN ('normal', 'trust') + GROUP BY s.itemFk + ) sub2 ON sub2.itemFk = sub.itemFk + UNION ALL + SELECT v.item_id , + i.longName, + CONCAT('Hoy saldrán ', CAST(sub5.pendiente AS DECIMAL(10,0)), ' unidades.') `size`, + CONCAT(IF(sub5.pendiente,'(0) ','(3) ')) producer, + 0, + 0, + v.visible, + 0, + v.visible nicho + FROM cache.visible v + JOIN item i ON i.id = v.item_id + JOIN itemType it ON it.id = i.typeFk + LEFT JOIN itemShelvingStock iss ON iss.itemFk = v.item_id + LEFT JOIN (SELECT s.itemFk , SUM(s.quantity) pendiente + FROM sale s + LEFT JOIN saleTracking st ON st.saleFk = s.id + JOIN ticket t ON t.id = s.ticketFk + JOIN client c on c.id = t.clientFk + JOIN clientType ct ON ct.id = c.clientTypeFk + WHERE t.shipped BETWEEN CURDATE() AND util.dayend(CURDATE()) + AND ISNULL(st.saleFk) + AND ct.code IN ('normal', 'trust') + GROUP BY s.itemFk + ) sub5 ON sub5.itemFk = v.item_id + WHERE v.calc_id = vCalcVisibleFk + AND ISNULL(iss.itemFk) + AND it.workerFk = vWorkerFk + ) sub3 + WHERE nicho + ORDER BY producer; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingRadar_Urgent__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingRadar_Urgent__`(vWorkerFk INT) +BEGIN + DECLARE vCalcVisibleFk INT; DECLARE vWarehouseFk INT DEFAULT 60; -- DECLARE vSectorFk INt; -- DECLARE vFatherSectorFk INT; @@ -59382,7 +62222,7 @@ BEGIN JOIN vn.client c on c.id = t.clientFk WHERE t.shipped BETWEEN CURDATE() AND util.dayend(CURDATE()) AND ISNULL(st.saleFk) - AND c.isOfficial + AND (c.clientTypeFk = 1 OR c.clientTypeFk = 5) GROUP BY s.itemFk) sub2 ON sub2.itemFk = sub.itemFk UNION ALL @@ -59407,15 +62247,13 @@ BEGIN JOIN vn.client c on c.id = t.clientFk WHERE t.shipped BETWEEN CURDATE() AND util.dayend(CURDATE()) AND ISNULL(st.saleFk) - AND c.isOfficial + AND (c.clientTypeFk = 1 OR c.clientTypeFk = 5) GROUP BY s.itemFk) sub5 ON sub5.itemFk = v.item_id WHERE v.calc_id = vCalcVisibleFk AND ISNULL(iss.itemFk) AND it.workerFk = vWorkerFk) sub3 WHERE nicho ORDER BY producer; - - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -59665,6 +62503,104 @@ BEGIN AND ish.stars IS NULL ORDER BY p.pickingOrder; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelving_filterBuyer` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemShelving_filterBuyer`(vBuyerFk INT, vWarehouseFk INT) +proc:BEGIN +/** + * Lista de articulos filtrados por comprador + * + * @param vBuyerFk Comprador a filtrar + * @param vWarehouseFk Warehouse + * @return Lista de articulos + */ + DECLARE vCalcVisibleFk INT; + + CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk); + + SELECT * FROM + (SELECT sub.itemFk, + sub.longName, + CONCAT('Hoy saldrán ', CAST(sub2.pendiente AS DECIMAL(10,0)), ' unidades.') `size`, + CONCAT(IF(sub2.itemFk, IF(sub2.pendiente > (sub.upstairs + sub.downstairs),'(1) ','(2) '),'(3) ' ),sub.producer) producer, + sub.upstairs, + sub.downstairs, + sub.visible, + sub.sectorFk, + CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) nicho + FROM (SELECT iss.itemFk, + CONCAT(i.longName,' ',i.size,' ',IFNULL(i.subName,'') ) longName, + '' size, + CONCAT(iss.parkingCode , ' ', iss.shelvingFk) producer, + 0 upstairs, + SUM(IFNULL(iss.visible,0)) downstairs, + IF(it.isPackaging, null, IFNULL(v.visible,0)) visible, + IFNULL(iss.sectorFk,0) sectorFk + FROM itemShelvingStock iss + JOIN sector s ON s.id = iss.sectorFk + JOIN item i on i.id = iss.itemFk + JOIN itemType it ON it.id = i.typeFk + LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk + WHERE s.warehouseFk = vWarehouseFk + AND it.workerFk = vBuyerFk + GROUP BY itemFk + ) sub LEFT JOIN (SELECT s.itemFk, SUM(s.quantity) pendiente + FROM sale s + LEFT JOIN saleTracking st ON st.saleFk = s.id + JOIN ticket t ON t.id = s.ticketFk + JOIN client c on c.id = t.clientFk + JOIN clientType ct ON ct.id = c.clientTypeFk + WHERE t.shipped BETWEEN CURDATE() AND util.dayend(CURDATE()) + AND ISNULL(st.saleFk) + AND ct.code IN ('normal', 'trust') + GROUP BY s.itemFk + ) sub2 ON sub2.itemFk = sub.itemFk + UNION ALL + SELECT v.item_id , + i.longName, + CONCAT('Hoy saldrán ', CAST(sub5.pendiente AS DECIMAL(10,0)), ' unidades.') `size`, + CONCAT(IF(sub5.pendiente,'(0) ','(3) ')) producer, + 0, + 0, + v.visible, + IFNULL(iss.sectorFk,0), + v.visible nicho + FROM cache.visible v + JOIN item i ON i.id = v.item_id + JOIN itemType it ON it.id = i.typeFk + LEFT JOIN itemShelvingStock iss ON iss.itemFk = v.item_id + LEFT JOIN (SELECT s.itemFk , SUM(s.quantity) pendiente + FROM sale s + LEFT JOIN saleTracking st ON st.saleFk = s.id + JOIN ticket t ON t.id = s.ticketFk + JOIN client c on c.id = t.clientFk + JOIN clientType ct ON ct.id = c.clientTypeFk + WHERE t.shipped BETWEEN CURDATE() AND util.dayend(CURDATE()) + AND ISNULL(st.saleFk) + AND ct.code IN ('normal', 'trust') + GROUP BY s.itemFk + ) sub5 ON sub5.itemFk = v.item_id + WHERE v.calc_id = vCalcVisibleFk + AND ISNULL(iss.itemFk) + AND it.workerFk = vBuyerFk + ) sub3 + WHERE nicho + ORDER BY producer; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -59783,6 +62719,90 @@ BEGIN DECLARE vTicketFk INT; DECLARE vClientFk INT; DECLARE vCompanyVnlFk INT DEFAULT 442; + DECLARE vVisible INT DEFAULT 0; + DECLARE vCalc INT; + DECLARE vParkedStuff INT; + + SELECT barcodeToItem(vItemFk) INTO vItemFk; + + CALL cache.visible_refresh(vCalc, TRUE, vWarehouseFk); + + SELECT IFNULL(visible,0) INTO vVisible + FROM cache.visible + WHERE calc_id = vCalc + AND item_id = vItemFk; + + SELECT sum(visible) INTO vParkedStuff + FROM itemShelvingStock + WHERE warehouseFk = vWarehouseFk + AND itemFk = vItemFk; + + SET vNewVisible = vNewVisible + IFNULL(vParkedStuff,0); + + SELECT IF(vIsTrash, 200, 400) INTO vClientFk; + + SELECT t.id INTO vTicketFk + FROM ticket t + JOIN address a ON a.id=t.addressFk + WHERE t.warehouseFk = vWarehouseFk + AND t.clientFk = vClientFk + AND DATE(t.shipped) = CURDATE() + AND a.isDefaultAddress + LIMIT 1; + + IF vTicketFk IS NULL THEN + + CALL ticket_add( + vClientFk, + CURDATE(), + vWarehouseFk, + vCompanyVnlFk, + NULL, + NULL, + NULL, + CURDATE(), + account.userGetId(), + FALSE, + vTicketFk); + + END IF; + + INSERT INTO sale(ticketFk, itemFk, concept, quantity, price, discount) + SELECT vTicketFk, vItemFk, CONCAT(longName,' ', getWorkerCode(), ' ',LEFT(CAST(NOW() AS TIME),5)), vVisible - vNewVisible, 0, 0 + FROM item + WHERE id = vItemFk; + + UPDATE cache.visible + SET visible = vNewVisible + WHERE calc_id = vCalc + AND item_id = vItemFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemStockUpdate__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemStockUpdate__`( + vItemFk INT, + vWarehouseFk INT, + vNewVisible INT, + vIsTrash BOOLEAN) +BEGIN + + DECLARE vTicketFk INT; + DECLARE vClientFk INT; + DECLARE vCompanyVnlFk INT DEFAULT 442; DECLARE vAgencyModeOthersFk INT DEFAULT 2; DECLARE vVisible INT DEFAULT 0; DECLARE vCalc INT; @@ -60233,9 +63253,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -60248,6 +63268,78 @@ BEGIN DECLARE vTicketFk INT; DECLARE vClientFk INT; + DECLARE vCompanyVnlFk INT DEFAULT 442; + DECLARE vCalc INT; + + SELECT barcodeToItem(vItemFk) INTO vItemFk; + + SELECT IF(vIsTrash, 200, 400) INTO vClientFk; + + SELECT t.id INTO vTicketFk + FROM ticket t + JOIN address a ON a.id=t.addressFk + WHERE t.warehouseFk = vWarehouseFk + AND t.clientFk = vClientFk + AND DATE(t.shipped) = CURDATE() + AND a.isDefaultAddress + LIMIT 1; + + CALL cache.visible_refresh(vCalc, TRUE, vWarehouseFk); + + IF vTicketFk IS NULL THEN + + CALL ticket_add( + vClientFk, + CURDATE(), + vWarehouseFk, + vCompanyVnlFk, + NULL, + NULL, + NULL, + CURDATE(), + account.userGetId(), + FALSE, + vTicketFk); + END IF; + + INSERT INTO sale(ticketFk, itemFk, concept, quantity) + SELECT vTicketFk, + vItemFk, + CONCAT(longName,' ',getWorkerCode(), ' ', LEFT(CAST(NOW() AS TIME),5)), + vQuantity + FROM item + WHERE id = vItemFk; + + UPDATE cache.visible + SET visible = visible - vQuantity + WHERE calc_id = vCalc + AND item_id = vItemFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemTrash__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemTrash__`( + vItemFk INT, + vWarehouseFk INT, + vQuantity INT, + vIsTrash BOOLEAN) +BEGIN + + DECLARE vTicketFk INT; + DECLARE vClientFk INT; DECLARE vCompanyVnlFk INT DEFAULT 442; DECLARE vAgencyModeOthersFk INT DEFAULT 2; DECLARE vCurrentTime VARCHAR(5); @@ -60348,13 +63440,13 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `item_getBalance`(IN vItemId INT, IN vWarehouse INT) +CREATE DEFINER=`root`@`%` PROCEDURE `item_getBalance`(IN vItemId int, IN vWarehouse int) BEGIN DECLARE vDateInventory DATETIME; DECLARE vCurdate DATE DEFAULT CURDATE(); @@ -60372,7 +63464,7 @@ BEGIN reference, clientFk, name, - `in`, + `in` AS invalue, `out`, @a := @a + IFNULL(`in`,0) - IFNULL(`out`,0) as balance, @currentLineFk := IF (@shipped < CURDATE() @@ -60386,13 +63478,13 @@ BEGIN ( SELECT tr.landed AS shipped, b.quantity AS `in`, NULL AS `out`, - al.alertLevel AS alertLevel, + al.id AS alertLevel, st.name AS stateName, s.name AS name, e.ref AS reference, e.id AS origin, s.id AS clientFk, - IF(al.alertLevel = 3, TRUE, FALSE) isPicked, + IF(al.id = 3, TRUE, FALSE) isPicked, FALSE AS isTicket, b.id lineFk, NULL `order`, @@ -60401,7 +63493,7 @@ BEGIN JOIN entry e ON e.id = b.entryFk JOIN travel tr ON tr.id = e.travelFk JOIN supplier s ON s.id = e.supplierFk - JOIN alertLevel al ON al.alertLevel = + JOIN alertLevel al ON al.id = CASE WHEN tr.shipped < CURDATE() THEN 3 WHEN tr.shipped = CURDATE() AND tr.isReceived = TRUE THEN 3 @@ -60416,25 +63508,25 @@ BEGIN UNION ALL SELECT tr.shipped, - NULL as `in`, - b.quantity AS `out`, - al.alertLevel AS alertLevel, - st.name AS stateName, - s.name AS name, - e.ref AS reference, - e.id AS origin, - s.id AS clientFk, - IF(al.alertLevel = 3, TRUE, FALSE) isPicked, - FALSE AS isTicket, + NULL, + b.quantity, + al.id, + st.name, + s.name, + e.ref, + e.id, + s.id, + IF(al.id = 3, TRUE, FALSE), + FALSE, b.id, - NULL `order`, - NULL AS clientType + NULL, + NULL FROM buy b JOIN entry e ON e.id = b.entryFk JOIN travel tr ON tr.id = e.travelFk JOIN warehouse w ON w.id = tr.warehouseOutFk JOIN supplier s ON s.id = e.supplierFk - JOIN alertLevel al ON al.alertLevel = + JOIN alertLevel al ON al.id = CASE WHEN tr.shipped < CURDATE() THEN 3 WHEN tr.shipped = CURDATE() AND tr.isReceived = TRUE THEN 3 @@ -60451,26 +63543,26 @@ BEGIN UNION ALL SELECT DATE(t.shipped), - NULL as `in`, - s.quantity AS `out`, - al.alertLevel AS alertLevel, - st.name AS stateName, - t.nickname AS name, - t.refFk AS reference, - t.id AS origin, + NULL, + s.quantity, + al.id, + st.name, + t.nickname, + t.refFk, + t.id, t.clientFk, - stk.id AS isPicked, - TRUE AS isTicket, + stk.id, + TRUE, s.id, st.`order`, - ct.code AS clientType + ct.code FROM sale s JOIN ticket t ON t.id = s.ticketFk LEFT JOIN ticketState ts ON ts.ticket = t.id LEFT JOIN state st ON st.code = ts.code JOIN client c ON c.id = t.clientFk JOIN clientType ct ON ct.id = c.clientTypeFk - JOIN alertLevel al ON al.alertLevel = + JOIN alertLevel al ON al.id = CASE WHEN t.shipped < curdate() THEN 3 WHEN t.shipped > util.dayEnd(curdate()) THEN 0 @@ -61104,6 +64196,32 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `item_updatePackingType` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `item_updatePackingType`(vItem INT, vItemPackingTypeFk VARCHAR(1)) +BEGIN +/** + * Update the packing type of an item + * + * @param vItem id del item a actualizar + * @param vItemPackingTypeFk packing type + */ + UPDATE item SET itemPackingTypeFk = vItemPackingTypeFk WHERE id = vItem; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `item_ValuateInventory` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -61494,6 +64612,70 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `kk` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `kk`(vCIF VARCHAR(9)) +BEGIN + + DECLARE vLetraInicial VARCHAR(1); + DECLARE vLetraFinal VARCHAR(1); + DECLARE vParteNumerica VARCHAR(7); + DECLARE vSuma INT DEFAULT 0; + DECLARE vNumero INT DEFAULT 0; + DECLARE i INT DEFAULT 0; + DECLARE vResult BOOL DEFAULT FALSE; + + SET vLetraInicial = SUBSTR(vCIF, 1, 1); + SET vLetraFinal = SUBSTR(vCIF, 9, 1); + SET vParteNumerica = SUBSTR(vCIF, 2, 7); + + WHILE i < 7 DO + + SET i = i + 1; + + SET vNumero = CAST(SUBSTR(vParteNumerica, i, 1) AS DECIMAL(1,0)); + + IF i MOD 2 THEN + + SET vNumero = vNumero * 2; + SET vNumero = vNumero MOD 10 + FLOOR(vNumero/10); + + END IF; + + SET vSuma = vSuma + vNumero; + + END WHILE; + + SET vSuma = vSuma MOD 10; + + IF vSuma > 0 THEN + + SET vSuma = 10 - vSuma; + + END IF; + + + -- Comprobación de dígito de control numérico + IF CAST(vLetraFinal AS DECIMAL(1,0)) = vSuma THEN + + SET vResult = TRUE; + + END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `ledger_doCompensation` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -61767,6 +64949,155 @@ 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 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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` 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 = 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 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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` 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, 'productionAssi'), 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 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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `machineWorker_update`(vPlate VARCHAR(10), vWorkerFk INT) +BEGIN + +/** + * Actualiza el registro correspondiente si el vWorkerFk ha registrado en las últimas 12 horas con vPlate, + * + * @param vPlate número de matrícula + * @param vWorkerFk id del trabajador + * +*/ + + DECLARE vMachineFk INT(10); + + SELECT m.id INTO vMachineFk + FROM machine m + WHERE m.plate = vPlate; + + IF (SELECT COUNT(*) + FROM machineWorker m + WHERE m.workerFk = vWorkerFk + AND m.inTimed >= TIMESTAMPADD(HOUR , -12,NOW()) AND ISNULL(m.outTimed)) THEN + + UPDATE machineWorker m + SET m.outTimed = CURRENT_TIMESTAMP() + WHERE m.workerFk = vWorkerFk + AND m.inTimed >= TIMESTAMPADD(HOUR , -12,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 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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` 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,NOW()) + AND ISNULL(mw.outTimed) + AND mw.workerFk = vWorkerFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -61978,7 +65309,7 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `mergeTicketUnattended` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -62024,7 +65355,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 DROP PROCEDURE IF EXISTS `mergeTicketWithArray` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -62646,133 +65977,6 @@ BEGIN END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `packageInvoicing__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `packageInvoicing__`( - IN vClient INT, - IN vDate DATE, - IN vCompany INT, - IN vIsAllInvoiceable BOOLEAN, - OUT vNewTicket INT(11) - ) -BEGIN - - DECLARE vGraceDays INT; - DECLARE vDateStart DATE DEFAULT '2017-11-21'; - DECLARE vIsInvoiceable BOOLEAN; - DECLARE vWarehouse INT DEFAULT 13; - DECLARE vAgenciaEmbalajes INT DEFAULT 628; - DECLARE vComponentCost INT DEFAULT 28; - DECLARE vGraceDate DATE; - DECLARE vZoneFk INT; - - SET vGraceDays = IF(vIsAllInvoiceable,0,30); - SET vGraceDate = TIMESTAMPADD(DAY, - vGraceDays, vDate); - - /* Clientes especiales: - 3240 MADEFLOR - 992 JAVIER FELIU - 4 TONI VENDRELL - */ - - IF vClient IN (992, 3240, 4) THEN - - SET vGraceDays = 365; - - END IF; - - /* Fin clientes especiales */ - - DROP TEMPORARY TABLE IF EXISTS tmp.packageToInvoice; - - CREATE TEMPORARY TABLE tmp.packageToInvoice - SELECT p.itemFk, - tp.packagingFk, - IF(tp.quantity < 0 OR t.shipped < vGraceDate, tp.quantity, 0) quantity, - tp.ticketFk, - p.price - FROM ticketPackaging tp - JOIN packaging p ON p.id = tp.packagingFk - JOIN ticket t ON t.id = tp.ticketFk - WHERE t.shipped BETWEEN vDateStart AND vDate - AND t.clientFk = vClient; - - DROP TEMPORARY TABLE IF EXISTS tmp.packageToInvoicePositives; - - CREATE TEMPORARY TABLE tmp.packageToInvoicePositives - SELECT itemFk, sum(quantity) as totalQuantity - FROM tmp.packageToInvoice - GROUP BY itemFk - HAVING totalQuantity > 0; - - SELECT GREATEST(COUNT(*),vIsAllInvoiceable) - INTO vIsInvoiceable - FROM tmp.packageToInvoicePositives; - - SELECT id INTO vZoneFk FROM vn.zone WHERE agencyModeFk = vAgenciaEmbalajes LIMIT 1; - - IF vIsInvoiceable THEN - - CALL vn.ticketCreateWithoutZone(vClient, vDate, vWarehouse, vCompany, NULL, vAgenciaEmbalajes, NULL, vDate, account.userGetId(), vNewTicket); - - INSERT INTO ticketPackaging( - ticketFk, - packagingFk, - quantity, - pvp) - SELECT vNewTicket, - pti.packagingFk, - - SUM(pti.quantity) AS totalQuantity, - pti.price - FROM tmp.packageToInvoice pti - LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk - WHERE ptip.itemFK IS NOT NULL - OR vIsAllInvoiceable - GROUP BY packagingFk - HAVING totalQuantity; - - INSERT INTO sale( - ticketFk, - itemFk, - concept, - quantity, - price - ) - SELECT vNewTicket, - pti.itemFk, - i.name as concept, - sum(pti.quantity) as totalQuantity, - pti.price - FROM tmp.packageToInvoice pti - JOIN item i ON i.id = pti.itemFk - LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk - WHERE ptip.itemFK IS NOT NULL - OR vIsAllInvoiceable - GROUP BY pti.itemFk - HAVING totalQuantity; - - INSERT INTO saleComponent(saleFk, componentFk, value) - SELECT id, vComponentCost, price - FROM sale - WHERE ticketFk = vNewTicket; - - UPDATE ticket SET zoneFk = vZoneFk WHERE id = vNewTicket; - END IF; - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63162,6 +66366,81 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `payRoll`(IN vFromDated DATE, IN vToDated DATE, IN vFromPaid DATE, IN vToPaid DATE, IN vPartTime BOOL) +BEGIN + + SET @userFk := 0; + + SELECT CONCAT(w.lastName,', ',w.firstname) AS Trabajador, + CAST(Sum((wj.total + wj.permission + wj.lunch)* wj.priceOrdinaryHour + wj.hollyday * wj.priceHollydayHour + + wj.nocturn * wj.priceNocturnHour + + wj.extra * wj.priceExtraHour) AS DECIMAL(10,2)) AS salario, + CAST(Sum(wj.permission) AS DECIMAL(10,2)) AS permission, + CAST(Sum(wj.total) AS DECIMAL(10,2)) AS total, + CAST(Sum(wj.nocturn) AS DECIMAL(10,2)) AS nocturn, + CAST(Sum(wj.hollyday) AS DECIMAL(10,2)) AS hollyday, + CAST(Sum(wj.lunch) AS DECIMAL(10,2)) AS lunch, + CAST(Sum(wj.extra) AS DECIMAL(10,2)) AS extra, + CAST(Sum(wj.contractJourney) AS DECIMAL(10,2)) AS contractJourney, + d.name AS departamento, + CAST(Sum((wj.contractJourney + wj.permission) * wj.priceOrdinaryHour) AS DECIMAL(10,2)) AS teorico, + CAST(Sum((wj.lunch + wj.permission + wj.total) * wj.priceordinaryhour) AS DECIMAL(10,2)) AS practico, + CAST(Sum(wj.nocturn * wj.pricenocturnhour) AS DECIMAL(10,2)) AS nocturno, + CAST(Sum(wj.hollyday * wj.priceHollydayHour) AS DECIMAL(10,2)) AS festivos, + CAST(Sum(wj.extra * wj.priceextrahour) AS DECIMAL(10,2)) AS extras, + MAX(wj.businessFk) as businessFk, + IF(sub.workerFk IS NULL, FALSE, TRUE) isLastBusiness, + Min(b.date_start) AS fromDated, + Max(b.date_end) AS toDated, + blp.importepactado, + bl.porhoras, + IF(wj.userFk != @userFk, CAST(IFNULL(a.Anticipos,0) AS DECIMAL(10,2)), 0) AS Anticipos, + IF(wj.userFk != @userFk, CAST(IFNULL(se.SaldoEuros,0) AS DECIMAL(10,2)), 0) AS SaldoEuros, + @userFk := wj.userFk as userFk + FROM worker w + JOIN workerJourney wj ON w.id = wj.userFk + JOIN postgresql.business b ON b.business_id = wj.businessFk + JOIN postgresql.business_labour bl ON bl.business_id = b.business_id + JOIN postgresql.calendar_labour_type cl ON cl.calendar_labour_type_id = bl.calendar_labour_type_id + JOIN postgresql.business_labour_payroll blp ON blp.business_id = b.business_id + JOIN department d ON bl.department_id = d.id + LEFT JOIN (SELECT pe.id_trabajador, SUM(debe) Anticipos + FROM postgresql.income_employee ie + JOIN postgresql.person pe ON ie.person_id = pe.person_id + WHERE odbc_date BETWEEN vFromPaid AND vToPaid + AND id_incomeType = 14 -- Salario + GROUP BY pe.id_trabajador + ) a ON a.id_trabajador = w.id + LEFT JOIN (SELECT pe.id_trabajador, SUM(debe) - SUM(haber) as SaldoEuros + FROM postgresql.income_employee ie + JOIN postgresql.person pe ON ie.person_id = pe.person_id + GROUP BY pe.id_trabajador + ) se ON se.id_trabajador = w.id + LEFT JOIN (SELECT MAX(IFNULL(ended, DATE_ADD(vToDated, INTERVAL 1 DAY )))dated,wl.workerFk + FROM vn.workerLabour wl + GROUP BY wl.workerFk + HAVING dated<=vToDated + ) sub ON sub.workerFk = w.id + WHERE wj.dated BETWEEN vFromDated AND vToDated + AND IF(vPartTime, cl.hours_week <= 40, cl.hours_week = 40) + GROUP BY w.id + ORDER BY w.lastName, w.firstname; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `payRoll__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `payRoll__`(IN vFromDated DATE, IN vToDated DATE, IN vFromPaid DATE, IN vToPaid DATE, IN vPartTime BOOL) BEGIN SET @userFk := 0; @@ -64098,15 +67377,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `productionSectorList`(vSectorFk INT) BEGIN - /* - DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; - CREATE TEMPORARY TABLE tmp.clientGetDebt - SELECT DISTINCT t.clientFk - FROM vn.ticket t - JOIN vn.itemShelvingAvailable isa ON isa.ticketFk = t.id; - - CALL vn.clientGetDebt(CURDATE()); - */ + DECLARE vWarehouseFk INT; SELECT warehouseFk INTO vWarehouseFk @@ -64125,7 +67396,29 @@ BEGIN ( SELECT * FROM ( - SELECT isa.*, + SELECT isa.saleFk, + isa.Modificado, + isa.ticketFk, + isa.isPicked, + isa.itemFk, + isa.quantity, + CONCAT(isa.concept,' ',i.itemPackingTypeFk ) concept , + isa.`size`, + isa.Estado, + isa.sectorProdPriority, + isa.available, + isa.sectorFk, + isa.matricula, + isa.parking, + isa.itemShelving, + isa.Agency, + isa.shipped, + isa.`grouping`, + isa.packing, + isa.`hour`, + isa.isPreviousPreparable, + isa.physicalVolume, + isa.warehouseFk , cast(max(isa.quantity mod isa.packing) as DECIMAL(10,0)) as picos, sum(isa.available) as totalAvailable, IF (HOUR(isa.shipped),HOUR(isa.shipped), HOUR(isa.`hour`)) Hora, @@ -64137,7 +67430,6 @@ BEGIN JOIN vn.sector s ON s.id = isa.sectorFk AND s.warehouseFk = isa.warehouseFk JOIN vn.ticket t ON t.id = isa.ticketFk JOIN vn.client c ON c.id = t.clientFk - -- JOIN tmp.risk r ON r.clientFk = c.id JOIN tmp.productionBuffer pb ON pb.ticketFk = t.id JOIN vn.packagingConfig pc WHERE IF(s.isPreviousPreparedByPacking, @@ -64812,7 +68104,7 @@ BEGIN IF !(vItemPackingTypeFk <=> 'V') THEN SELECT CONCAT(tc.collectionFk,' ',LEFT(cc.code,4)) `level`, - tc.ticketFk, + tc.ticketFk, LEFT(IF(t.routeFk IS null, am.name, zo.name ),12) agencyDescription, am.name, t.clientFk, @@ -64821,7 +68113,8 @@ BEGIN tt.labelCount, IF(HOUR(t.shipped),TIME(t.shipped),TIME(zo.HOUR)) as horaagencia, t.shipped, - count(*) AS urgente + count(*) AS urgente , + t.nickName FROM vn.ticket t JOIN vn.ticketCollection tc ON tc.ticketFk = t.id JOIN vn.collectionColors cc ON cc.shelve = tc.`level` AND cc.wagon = tc.wagon @@ -64850,7 +68143,8 @@ BEGIN tt.labelCount, IF(HOUR(t.shipped),TIME(t.shipped),TIME(zo.HOUR)) as horaagencia, t.shipped, - count(*) AS urgente + count(*) AS urgente , + t.nickName FROM vn.ticket t JOIN vn.ticketCollection tc ON tc.ticketFk = t.id JOIN vn.sale s ON s.ticketFk = t.id @@ -65126,6 +68420,123 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `routeMonitor_calculate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `routeMonitor_calculate`(vDate DATE) +BEGIN + + DECLARE vDateEND DATETIME; + + SET vDateEND = util.dayend(vDate); + SET vDate = TIMESTAMPADD(DAY,-1,vDate); + + DROP TEMPORARY TABLE IF EXISTS tmp.routesMonitor; + + CREATE TEMPORARY TABLE tmp.routesMonitor + (INDEX (routeFk)) + ENGINE = MEMORY + SELECT DISTINCT(t.routeFk) routeFk + FROM vn.ticket t + WHERE t.shipped BETWEEN vDate AND vDateEND + AND t.routeFk IS NOT NULL; + + INSERT IGNORE INTO routesMonitor(routeFk) + SELECT routeFk + FROM tmp.routesMonitor; + + UPDATE routesMonitor rm + JOIN route r ON r.id = rm.routeFk + JOIN agencyMode a ON a.id = r.agencyModeFk + LEFT JOIN routeGate rg ON rg.routeFk = rm.routeFk + SET rm.`name` = a.name, + rm.dated = r.created, + rm.ticketFree = 0, + rm.ticketProduction = 0, + rm.ticketPacked = 0, + rm.dated = r.created, + rm.beachFk = rg.deviceId; + + UPDATE routesMonitor rm + JOIN(SELECT t.routeFk, COUNT(*) AS ticketFree + FROM vn.ticket t + JOIN tmp.routesMonitor rm ON rm.routeFk = t.routeFk + JOIN ticketLastState ts ON t.id = ts.ticketFk + JOIN ticketTracking tt ON tt.id = ts.ticketTrackingFk + JOIN state s ON s.id = tt.stateFk AND s.alertLevel = 0 + GROUP BY t.routeFk + ) sub ON sub.routeFk = rm.routeFk + SET rm.ticketFree = sub.ticketFree; + + UPDATE routesMonitor rm + JOIN(SELECT t.routeFk, COUNT(*) AS ticketPacked + FROM vn.ticket t + JOIN tmp.routesMonitor rm ON rm.routeFk = t.routeFk + JOIN ticketLastState ts ON t.id = ts.ticketFk + JOIN ticketTracking tt ON tt.id = ts.ticketTrackingFk + JOIN state s ON s.id = tt.stateFk AND s.alertLevel = 2 + GROUP BY t.routeFk + ) sub ON sub.routeFk = rm.routeFk + SET rm.ticketPacked = sub.ticketPacked; + + UPDATE routesMonitor rm + JOIN(SELECT t.routeFk, COUNT(*) AS ticketProduction + FROM vn.ticket t + JOIN tmp.routesMonitor rm ON rm.routeFk = t.routeFk + JOIN ticketLastState ts ON t.id = ts.ticketFk + JOIN ticketTracking tt ON tt.id = ts.ticketTrackingFk + JOIN state s ON s.id = tt.stateFk AND s.alertLevel = 3 + GROUP BY t.routeFk + ) sub ON sub.routeFk = rm.routeFk + SET rm.ticketProduction = sub.ticketProduction; + + UPDATE routesMonitor rm + JOIN( SELECT t.routeFk, COUNT(*) AS packages + FROM vn.ticket t + JOIN tmp.routesMonitor rm ON rm.routeFk = t.routeFk + JOIN expedition e ON e.ticketFk = t.id + GROUP BY t.routeFk + ) sub ON sub.routeFk = rm.routeFk + SET rm.packages = sub.packages; + + UPDATE routesMonitor rm + JOIN( SELECT t.routeFk, SUM(sv.volume) AS m3 + FROM vn.ticket t + JOIN tmp.routesMonitor rm ON rm.routeFk = t.routeFk + JOIN vn.saleVolume sv ON sv.ticketFk = t.id + GROUP BY t.routeFk + ) sub ON sub.routeFk = rm.routeFk + SET rm.m3 = sub.m3; + + UPDATE routesMonitor rm + JOIN( SELECT t.routeFk , sum(IFNULL(pk.volume, pk.width * pk.height * pk.`depth` )) / 1000000 m3boxes + FROM vn.ticket t + JOIN tmp.routesMonitor rm ON rm.routeFk = t.routeFk + JOIN vn.expedition e ON e.ticketFk = t.id + JOIN vn.packaging pk ON pk.id = e.packagingFk + GROUP BY t.routeFk + ) sub ON sub.routeFk = rm.routeFk + SET rm.m3boxes = sub.m3boxes; + + UPDATE routesMonitor rm + JOIN ticket t ON t.routeFk = rm.routeFk + JOIN zoneEstimatedDelivery zed ON zed.zoneFk = t.zoneFk + SET rm.etd = IFNULL(zed.hourEffective, zed.hourTheoretical); + + DROP TEMPORARY TABLE tmp.routesMonitor; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `routeSetOk` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -65154,13 +68565,171 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `routeUpdateM3`(vRoute INT) +BEGIN +/** + * @deprecated Use vn.route_updateM3() + */ + call route_updateM3(vRoute); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `route_doRecalc` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `route_doRecalc`() +proc: BEGIN +/** + * Recalculates modified route. + */ + + DECLARE vDone BOOL; + DECLARE vRouteFk INT; + + DECLARE cCur CURSOR FOR + SELECT routeFk FROM routeRecalc; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('vn.route_doRecalc'); + ROLLBACK; + RESIGNAL; + END; + + IF !GET_LOCK('vn.route_doRecalc', 0) THEN + LEAVE proc; + END IF; + + OPEN cCur; + + myLoop: LOOP + SET vDone = FALSE; + FETCH cCur INTO vRouteFk; + + IF vDone THEN + LEAVE myLoop; + END IF; + + START TRANSACTION; + CALL route_updateM3(vRouteFk); + COMMIT; + + DELETE FROM routeRecalc WHERE routeFk = vRouteFk; + END LOOP; + + CLOSE cCur; + DO RELEASE_LOCK('vn.route_doRecalc'); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `route_getTickets` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; /*!50003 SET character_set_client = utf8mb4 */ ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `routeUpdateM3`(vRoute INT) +CREATE DEFINER=`root`@`%` PROCEDURE `route_getTickets`(vRouteFk INT) +BEGIN +/** + * Pasado un RouteFk devuelve la información + * de sus tickets. + * + * @param vRouteFk + * + * @select Información de los tickets + */ + + SELECT + t.id AS Id, + t.clientFk AS Client, + a.id AS Address, + a.nickname AS ClientName, + t.packages AS Packages, + a.street AS AddressName, + a.postalCode AS PostalCode, + a.city AS City, + sub2.itemPackingTypeFk AS PackingType, + c.phone AS ClientPhone, + c.mobile AS ClientMobile, + a.phone AS AddressPhone, + a.mobile AS AddressMobile, + tl.longitude AS Longitude, + tl.latitude AS Latitude, + wm.mediaValue AS SalePersonPhone, + tob.Note AS Note, + t.isSigned AS Signed, + st.id AS Polizon + FROM ticket t + JOIN client c ON t.clientFk = c.id + JOIN address a ON t.addressFk = a.id + LEFT JOIN ticketLocation tl ON tl.ticketFk = t.id + LEFT JOIN workerMedia wm ON wm.workerFk = c.salesPersonFk + LEFT JOIN + (SELECT tob.description AS Note, t.id + FROM ticketObservation tob + JOIN ticket t ON tob.ticketFk = t.id + JOIN observationType ot ON ot.id = tob.observationTypeFk + WHERE t.routeFk = vRouteFk + AND ot.code = 'delivery' + )tob ON tob.id = t.id + LEFT JOIN stowaway st ON st.shipFk = t.id + LEFT JOIN + (SELECT sub.ticketFk, + CONCAT('(', GROUP_CONCAT(DISTINCT sub.itemPackingTypeFk ORDER BY sub.items DESC SEPARATOR ','), ') ') itemPackingTypeFk + FROM (SELECT s.ticketFk , i.itemPackingTypeFk, COUNT(*) items + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + WHERE t.routeFk = vRouteFk + GROUP BY t.id,i.itemPackingTypeFk)sub + GROUP BY sub.ticketFk + ) sub2 ON sub2.ticketFk = t.id + WHERE t.routeFk = vRouteFk + GROUP BY t.id + ORDER BY t.priority; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `route_updateM3` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `route_updateM3`(vRoute INT) BEGIN UPDATE vn.route r @@ -65389,17 +68958,17 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `saleItemShelvingDelete` */; +/*!50003 DROP PROCEDURE IF EXISTS `saleItemShelvingDelete__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `saleItemShelvingDelete`(vSaleFk INT) +CREATE DEFINER=`root`@`%` PROCEDURE `saleItemShelvingDelete__`(vSaleFk INT) BEGIN UPDATE vn.itemShelving ish @@ -65417,7 +68986,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `saleItemShelvingIsPicked` */; +/*!50003 DROP PROCEDURE IF EXISTS `saleItemShelvingIsPicked__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -65427,7 +68996,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `saleItemShelvingIsPicked`(vTicketFk INT, vIsPicked BOOL) +CREATE DEFINER=`root`@`%` PROCEDURE `saleItemShelvingIsPicked__`(vTicketFk INT, vIsPicked BOOL) BEGIN DECLARE vStateFk INT; @@ -65453,17 +69022,17 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `saleItemShelvingMake` */; +/*!50003 DROP PROCEDURE IF EXISTS `saleItemShelvingMake__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; /*!50003 SET character_set_client = utf8mb4 */ ; /*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `saleItemShelvingMake`(IN `vTicketFk` INT, IN `vSectorFk` INT) +CREATE DEFINER=`root`@`%` PROCEDURE `saleItemShelvingMake__`(IN `vTicketFk` INT, IN `vSectorFk` INT) BEGIN SET @rest:= CAST(0 AS DECIMAL(10,0)); @@ -66349,6 +69918,445 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `sale_fruitWithoutLot` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `sale_fruitWithoutLot`() +BEGIN +/** +* +* Manda correo a el usuario encargado de fruta y verdura +* de las lineas de tickets a las que no ha sido asignada +* un lote. +* +*/ + SET SESSION group_concat_max_len = 102400; + + INSERT INTO mail (sender,replyTo,subject,body) + SELECT CONCAT(sub.name, '@verdnatura.es') sender, + 'noreply@verdnatura.es' replyTo, + CONCAT( + 'El ', + CONCAT (CAST((SUM(sub.fail)/COUNT(*))*100 AS DECIMAL(10,2)), ' %'), + CONCAT(' de los artículos han sido vendidos sin lote con fecha: ', DATE_SUB(CURDATE(), INTERVAL 3 DAY )) + ) subject, + GROUP_CONCAT(sub.ticket SEPARATOR '

') body + FROM (SELECT IF (sb.saleFk IS NULL,1, 0) fail, + u.name, + IF (sb.saleFk IS NULL,CONCAT('Artículo ',i.id,', ',i.name,':
     + https://salix.verdnatura.es/#!/ticket/',t.id,'/sale'), NULL) ticket + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + LEFT JOIN saleBuy sb ON sb.saleFk = s.id + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + JOIN account.user u ON u.id = it.workerFk + JOIN itemCategory ic ON ic.id = it.categoryFk + WHERE t.shipped = DATE_SUB(CURDATE(), INTERVAL 1 DAY) + AND ic.code='fruit')sub; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `sale_getFromTicketOrCollection` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `sale_getFromTicketOrCollection`(vParam INT) +BEGIN + + + /* + * Visualizar lineas de la tabla sale a través del parámetro vParam que puede ser ticket o collection + */ + + DECLARE vItemPackingTypeFk VARCHAR(1); + + + IF (SELECT COUNT(*) FROM vn.ticket WHERE id = vParam AND id > 2000000) THEN + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + SELECT t.id, clientFk, t.id as showTicketFk + FROM vn.ticket t + WHERE t.id = vParam; + + ELSE + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + SELECT tc.ticketFk id, clientFk, tc.ticketFk as showTicketFk + FROM vn.ticketCollection tc + JOIN vn.ticket t ON t.id = tc.ticketFk + WHERE tc.collectionFk = vParam; + + END IF; + + + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket3; + CREATE TEMPORARY TABLE tmp.ticket3 + SELECT * FROM tmp.ticket; + + SELECT showTicketFk ticketFk, + s.id as saleFk, + s.itemFk, + s.quantity, + i.longName, + i.size, + s.reserved, + MAX(IF(st.semaphore <=> 1, TRUE, FALSE)) as isPreviousPrepared, + MAX(IF(st.semaphore <=> 2, TRUE, FALSE)) as isPrepared, + MAX(IF(st.semaphore <=> 3, TRUE, FALSE)) as isControlled, + ic.color, + ip.productor, + s.discount, + s.price, + i.stems, + i.category, + o.code AS origin, + t.clientFk, + s.originalQuantity, + TRIM(CONCAT( + LPAD(s.concept,30,' '), ' ', + RPAD(IFNULL(i.size,''),5,' ') + ) + ) as line1, + TRIM(CONCAT(LPAD(IFNULL(ip.productor,''),30,' '), ' ',LPAD(IFNULL(o.code,''),4,' '))) as line2, + TRIM(CONCAT(ic.color, IF(MAX(IF(st.semaphore <=> 1, TRUE, FALSE)) AND t.id != t.showTicketFk, CONCAT(' [ TICKET ',t.id,' ] '),''), IFNULL(LPAD(st.parkingCode,40,' '),''))) as line3, + s.isAdded, + str.originalQuantity as startQuantity, -- eliminar cuando tengamos la nueva apk + IFNULL(c.workerFk,getUser()), + IFNULL(SUM(iss.quantity),0) as pickedQuantity + FROM vn.sale s + JOIN tmp.ticket t ON t.id = s.ticketFk + JOIN vn.item i ON i.id = s.itemFk + LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = t.id + LEFT JOIN vn.collection c ON c.id = tc.collectionFk + LEFT JOIN vn.saleTracking str ON str.saleFk = s.id AND str.isChecked = 1 + LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id + LEFT JOIN vn.state st ON st.id = str.stateFk + LEFT JOIN vn.itemColor ic ON ic.itemFk = s.itemFk + LEFT JOIN vn.itemProductor ip ON ip.itemFk = s.itemFk + LEFT JOIN vn.origin o ON o.id = i.originFk + LEFT JOIN (SELECT st.saleFk, p.`code` as parkingCode + FROM vn.saleTracking st + JOIN vn.state s ON s.id = st.stateFk + JOIN vn.sale sa ON sa.id = st.saleFk + JOIN tmp.ticket3 t ON t.id = sa.ticketFk + JOIN vn.ticketParking tp ON tp.ticketFk = sa.ticketFk + JOIN vn.parking p ON p.id = tp.parkingFk + WHERE st.isChecked + AND s.semaphore = 1 + GROUP BY st.saleFk) st ON st.saleFk = s.id + WHERE (i.itemPackingTypeFk = c.itemPackingTypeFk OR ISNULL(c.itemPackingTypeFk)) + GROUP BY s.id + + ; + + DROP TEMPORARY TABLE tmp.ticket; + DROP TEMPORARY TABLE tmp.ticket3; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `sale_getProblems` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `sale_getProblems`(IN vIsTodayRelative TINYINT(1)) +BEGIN +/** + * Calcula los problemas de cada venta + * para un conjunto de tickets. + * + * @table tmp.sale_getProblems(ticketFk, clientFk, warehouseFk, shipped) Identificadores de los tickets a calcular + * @return tmp.sale_problems + */ + DECLARE vWarehouse INT; + DECLARE vDate DATE; + DECLARE vAvailableCache INT; + DECLARE vDone INT DEFAULT 0; + DECLARE vComponentCount INT; + + DECLARE vCursor CURSOR FOR + SELECT DISTINCT tt.warehouseFk, IF(vIsTodayRelative, CURDATE(), date(tt.shipped)) + FROM tmp.sale_getProblems tt + WHERE DATE(tt.shipped) BETWEEN CURDATE() + AND TIMESTAMPADD(DAY, IF(vIsTodayRelative, 9.9, 1.9), CURDATE()); + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1; + + DROP TEMPORARY TABLE IF EXISTS tmp.sale_problems; + CREATE TEMPORARY TABLE tmp.sale_problems ( + ticketFk INT(11), + saleFk INT(11), + isFreezed INTEGER(1) DEFAULT 0, + risk DECIMAL(10,2) DEFAULT 0, + hasTicketRequest INTEGER(1) DEFAULT 0, + isAvailable INTEGER(1) DEFAULT 1, + itemShortage VARCHAR(250), + isTaxDataChecked INTEGER(1) DEFAULT 1, + itemDelay VARCHAR(250), + hasComponentLack INTEGER(1), + PRIMARY KEY (ticketFk, saleFk) + ) ENGINE = MEMORY; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; + CREATE TEMPORARY TABLE tmp.ticket_list + (PRIMARY KEY (ticketFk)) + ENGINE = MEMORY + SELECT tp.ticketFk, c.id clientFk + FROM tmp.sale_getProblems tp + JOIN vn.client c ON c.id = tp.clientFk; + + SELECT COUNT(*) INTO vComponentCount + FROM vn.component c + WHERE c.isRequired; + + INSERT INTO tmp.sale_problems(ticketFk, hasComponentLack, saleFk) + SELECT tl.ticketFk, (COUNT(DISTINCT s.id) * vComponentCount > COUNT(c.id)), s.id + FROM tmp.ticket_list tl + JOIN vn.sale s ON s.ticketFk = tl.ticketFk + LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id + LEFT JOIN vn.component c ON c.id = sc.componentFk AND c.isRequired + JOIN vn.ticket t ON t.id = tl.ticketFk + JOIN vn.agencyMode am ON am.id = t.agencyModeFk + JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk + WHERE dm.code IN('AGENCY','DELIVERY','PICKUP') + GROUP BY tl.ticketFk, s.id; + + INSERT INTO tmp.sale_problems(ticketFk, isFreezed) + SELECT DISTINCT tl.ticketFk, TRUE + FROM tmp.ticket_list tl + JOIN vn.client c ON c.id = tl.clientFk + WHERE c.isFreezed + ON DUPLICATE KEY UPDATE + isFreezed = c.isFreezed; + + DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; + CREATE TEMPORARY TABLE tmp.clientGetDebt + (PRIMARY KEY (clientFk)) + ENGINE = MEMORY + SELECT DISTINCT clientFk + FROM tmp.ticket_list; + + CALL clientGetDebt(CURDATE()); + + INSERT INTO tmp.sale_problems(ticketFk, risk) + SELECT DISTINCT tl.ticketFk, r.risk + FROM tmp.ticket_list tl + JOIN vn.ticket t ON t.id = tl.ticketFk + JOIN vn.agencyMode a ON t.agencyModeFk = a.id + JOIN tmp.risk r ON r.clientFk = t.clientFk + JOIN vn.client c ON c.id = t.clientFk + JOIN vn.clientConfig cc + WHERE r.risk > c.credit + 10 + AND a.isRiskFree = FALSE + ON DUPLICATE KEY UPDATE + risk = r.risk; + + INSERT INTO tmp.sale_problems(ticketFk, hasTicketRequest) + SELECT DISTINCT tl.ticketFk, TRUE + FROM tmp.ticket_list tl + JOIN vn.ticketRequest tr ON tr.ticketFk = tl.ticketFk + WHERE tr.isOK IS NULL + ON DUPLICATE KEY UPDATE + hasTicketRequest = TRUE; + + OPEN vCursor; + + WHILE NOT vDone + DO + FETCH vCursor INTO vWarehouse, vDate; + + CALL cache.available_refresh(vAvailableCache, FALSE, vWarehouse, vDate); + + INSERT INTO tmp.sale_problems(ticketFk, isAvailable, saleFk) + SELECT tl.ticketFk, FALSE, s.id + FROM tmp.ticket_list tl + JOIN vn.ticket t ON t.id = tl.ticketFk + JOIN vn.sale s ON s.ticketFk = t.id + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it on it.id = i.typeFk + LEFT JOIN cache.available av ON av.item_id = i.id + AND av.calc_id = vAvailableCache + WHERE date(t.shipped) = vDate + AND it.categoryFk != 6 + AND IFNULL(av.available, 0) < 0 + AND s.isPicked = FALSE + AND NOT i.generic + AND vWarehouse = t.warehouseFk + GROUP BY tl.ticketFk + ON DUPLICATE KEY UPDATE + isAvailable = FALSE, saleFk = VALUES(saleFk); + + INSERT INTO tmp.sale_problems(ticketFk, itemShortage, saleFk) + SELECT ticketFk, problem, saleFk + FROM ( + SELECT tl.ticketFk, CONCAT('F: ',GROUP_CONCAT(i.id, ' ', i.longName, ' ')) problem, s.id AS saleFk + FROM tmp.ticket_list tl + JOIN vn.ticket t ON t.id = tl.ticketFk + JOIN vn.sale s ON s.ticketFk = t.id + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it on it.id = i.typeFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache + WHERE IFNULL(av.available, 0) < 0 + AND s.quantity > IFNULL(issw.visible, 0) + AND s.quantity > 0 + AND s.isPicked = FALSE + AND s.reserved = FALSE + AND it.categoryFk != 6 + AND IF(vIsTodayRelative, TRUE, date(t.shipped) = vDate) + AND NOT i.generic + AND CURDATE() = vDate + AND t.warehouseFk = vWarehouse + GROUP BY tl.ticketFk LIMIT 1) sub + ON DUPLICATE KEY UPDATE + itemShortage = sub.problem, saleFk = sub.saleFk; + + INSERT INTO tmp.sale_problems(ticketFk, itemDelay, saleFk) + SELECT ticketFk, problem, saleFk + FROM ( + SELECT tl.ticketFk, GROUP_CONCAT('I: ',i.id, ' ', i.longName, ' ') problem, s.id AS saleFk + FROM tmp.ticket_list tl + JOIN vn.ticket t ON t.id = tl.ticketFk + JOIN vn.sale s ON s.ticketFk = t.id + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it on it.id = i.typeFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + WHERE s.quantity > IFNULL(issw.visible, 0) + AND s.quantity > 0 + AND s.isPicked = FALSE + AND s.reserved = FALSE + AND it.categoryFk != 6 + AND IF(vIsTodayRelative, TRUE, date(t.shipped) = vDate) + AND NOT i.generic + AND CURDATE() = vDate + AND t.warehouseFk = vWarehouse + GROUP BY tl.ticketFk LIMIT 1) sub + ON DUPLICATE KEY UPDATE + itemDelay = sub.problem, saleFk = sub.saleFk; + END WHILE; + + CLOSE vCursor; + + INSERT INTO tmp.sale_problems(ticketFk, isTaxDataChecked) + SELECT DISTINCT tl.ticketFk, FALSE + FROM tmp.ticket_list tl + JOIN vn.client c ON c.id = tl.clientFk + WHERE c.isTaxDataChecked = FALSE + ON DUPLICATE KEY UPDATE + isTaxDataChecked = FALSE; + + DROP TEMPORARY TABLE + tmp.clientGetDebt, + tmp.ticket_list; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `sale_getProblemsByTicket` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `sale_getProblemsByTicket`(IN vTicketFk INT, IN vIsTodayRelative TINYINT(1)) +BEGIN +/** + * Calcula los problemas de cada venta + * para un conjunto de tickets. + * + * @return Problems result + */ + DROP TEMPORARY TABLE IF EXISTS tmp.sale_getProblems; + CREATE TEMPORARY TABLE tmp.sale_getProblems + (INDEX (ticketFk)) + ENGINE = MEMORY + SELECT t.id ticketFk, t.clientFk, t.warehouseFk, t.shipped + FROM ticket t + WHERE t.id = vTicketFk; + + CALL sale_getProblems(vIsTodayRelative); + + SELECT * FROM tmp.sale_problems; + + DROP TEMPORARY TABLE + tmp.sale_getProblems, + tmp.sale_problems; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `sale_PriceFix` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `sale_PriceFix`(vTicketFk INT) +BEGIN + + DELETE sc.* + FROM vn.saleComponent sc + JOIN vn.sale s ON s.id = sc.saleFk + JOIN vn.component c ON c.id = sc.componentFk + JOIN vn.componentType ct ON ct.id = c.typeFk + WHERE s.ticketFk = vTicketFk + AND ct.`type` = 'otros'; + + UPDATE vn.sale s + JOIN ( + SELECT sc.saleFk, sum(sc.value ) price + FROM vn.saleComponent sc + JOIN vn.sale s ON s.id = sc.saleFk + WHERE s.ticketFk = vTicketFk + GROUP BY sc.saleFk) sub ON sub.saleFk = s.id + SET s.price = sub.price; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `sale_updateOriginalQuantity` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -66735,9 +70743,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -66781,7 +70789,7 @@ proc: BEGIN REPLACE vn.ticketParking(ticketFk,parkingFk) VALUES (vShelvingFk, vParkingFk); - CALL vn.ticketStatePrevious(vShelvingFk); + CALL vn.ticket_setPreviousState(vShelvingFk); ELSE @@ -67060,7 +71068,7 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `solunionRiskRequest` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -67103,7 +71111,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 DROP PROCEDURE IF EXISTS `stockBuyed` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -67139,7 +71147,7 @@ BEGIN -- SELECT Volumen INTO vVolume FROM vn2008.Cubos WHERE Id_Cubo = 'cc' LIMIT 1; INSERT INTO stockBuyed(user, buyed, `date`) - SELECT tr.user_id, SUM(( amount / c.packing ) * vn.buy_getVolume(Id_Compra)) / vc.espai / 1000000 buyed, vDate + SELECT tr.user_id, SUM(( amount / c.packing ) * vn.buy_getVolume(Id_Compra)) / vc.palletM3 / 1000000 buyed, vDate FROM tmp_item i JOIN vn2008.Articles a ON a.Id_Article = i.item_id JOIN vn2008.Tipos t ON a.tipo_id = t.tipo_id @@ -67153,7 +71161,7 @@ BEGIN ON DUPLICATE KEY UPDATE buyed = VALUES(buyed); INSERT INTO stockBuyed(USER, buyed, `date`) - SELECT vRuben, @amount := SUM(ic.cm3 * io.amount / vc.espai / 1000000), vDate + SELECT vRuben, @amount := SUM(ic.cm3 * io.amount / vc.palletM3 / 1000000), vDate FROM vn2008.item_out io JOIN vn.itemCost ic ON ic.itemFk = io.item_id AND ic.warehouseFk = vWarehouse JOIN vn.ticket t ON t.id = io.ticketFk @@ -67167,7 +71175,7 @@ BEGIN ON DUPLICATE KEY UPDATE buyed = buyed + @amount; INSERT INTO stockBuyed(USER, buyed, `date`) - SELECT vJose, @amount := SUM(ic.cm3 * io.amount / vc.espai / 1000000), vDate + SELECT vJose, @amount := SUM(ic.cm3 * io.amount / vc.palletM3 / 1000000), vDate FROM vn2008.item_out io JOIN vn.itemCost ic ON ic.itemFk = io.item_id AND ic.warehouseFk = vWarehouse JOIN vn.ticket t ON t.id = io.ticketFk @@ -67181,7 +71189,7 @@ BEGIN ON DUPLICATE KEY UPDATE buyed = buyed + @amount; INSERT INTO stockBuyed(USER, buyed, `date`) - SELECT vClaudi, @amount := SUM(ic.cm3 * io.amount / vc.espai / 1000000), vDate + SELECT vClaudi, @amount := SUM(ic.cm3 * io.amount / vc.palletM3 / 1000000), vDate FROM vn2008.item_out io JOIN vn.itemCost ic ON ic.itemFk = io.item_id AND ic.warehouseFk = vWarehouse JOIN vn.ticket t ON t.id = io.ticketFk @@ -67193,8 +71201,10 @@ BEGIN AND warehouse_id = vWarehouse AND c.country NOT IN ('Francia','Holanda') ON DUPLICATE KEY UPDATE buyed = buyed + @amount; - - + + DROP TEMPORARY TABLE + vn2008.t_item_last_buy, + tmp_item; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -67205,9 +71215,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -67229,24 +71239,27 @@ BEGIN JOIN vn2008.t_item_last_buy ilb ON ilb.item_id = a.Id_Article AND ilb.warehouse_id = vWarehouse JOIN vn2008.Compres c ON c.Id_compra = ilb.buy_id WHERE r.display <> 0 AND tr.user_id = vWorker; - + + DROP TEMPORARY TABLE + vn2008.t_item_last_buy, + tmp_item; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `stockBuyedByWorkerTest` */; +/*!50003 DROP PROCEDURE IF EXISTS `stockBuyedByWorkerTest__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `stockBuyedByWorkerTest`(vDate DATE, vWorker INT) +CREATE DEFINER=`root`@`%` PROCEDURE `stockBuyedByWorkerTest__`(vDate DATE, vWorker INT) BEGIN DECLARE vVolume DECIMAL(10,2); @@ -67323,7 +71336,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `stockTraslationTest` */; +/*!50003 DROP PROCEDURE IF EXISTS `stockTraslationTest__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -67333,7 +71346,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `stockTraslationTest`(vDate DATE) +CREATE DEFINER=`root`@`%` PROCEDURE `stockTraslationTest__`(vDate DATE) BEGIN /** * Calcula el stock del vWarehouse desde FechaInventario hasta v_date @@ -67678,9 +71691,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -67689,14 +71702,14 @@ BEGIN SELECT * FROM ( - SELECT supplierFk, itemFk, longName, supplier, entryFk, landed, `out`, `in`, almacen + SELECT supplierFk, itemFk, longName, supplier, entryFk, landed, `out`, `in`, almacen, cost FROM supplierPackaging WHERE supplierFk = vSupplierFk AND landed >= vFromDated UNION ALL - SELECT vSupplierFk, itemFk, longName, supplier, 'anterior', vFromDated, sum(`out`), sum(`in`), NULL + SELECT vSupplierFk, itemFk, longName, supplier, 'anterior', vFromDated, sum(`out`), sum(`in`), NULL, cost FROM supplierPackaging WHERE supplierFk = vSupplierFk AND landed < vFromDated @@ -67704,9 +71717,6 @@ BEGIN ) sub ORDER BY itemFk, landed; - - - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -68454,7 +72464,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketClosureAgencyListAdd` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticketClosureAgencyListAdd__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -68464,7 +72474,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosureAgencyListAdd`(vAgencyModeFk INT) +CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosureAgencyListAdd__`(vAgencyModeFk INT) BEGIN /** * Prepara un listado de agencias sobre los que se realizará el cierre. @@ -68534,70 +72544,13 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosureMultiWarehouse__`(vDateTo DATE) -BEGIN -/** - * Inserta los tickets de todos los almacenes en la tabla temporal - * para ser cerrados. - * - * @param vDate Fecha del cierre - */ - DECLARE vDateToEndDay DATETIME DEFAULT util.dayEnd(vDateTo); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure; - - CREATE TEMPORARY TABLE tmp.ticketClosure ENGINE = MEMORY ( - SELECT - t.id AS ticketFk - FROM expedition e - INNER JOIN ticket t ON t.id = e.ticketFk - INNER JOIN warehouse w ON w.id = t.warehouseFk AND hasComission - LEFT JOIN ticketState ts ON ts.ticketFk = t.id - WHERE - ts.alertLevel = 2 - AND DATE(t.shipped) BETWEEN DATE_ADD(vDateTo, INTERVAL -2 DAY) AND vDateTo - AND t.refFk IS NULL - GROUP BY e.ticketFk); - - CALL ticketClosure(); - - INSERT INTO mail (sender, replyTo, subject, body) - SELECT 'jgallego@verdnatura.es', 'jgallego@verdnatura.es', 'Tickets enrutados y NO preparados', - GROUP_CONCAT(ticketFk) tickets - FROM ticket t - JOIN ticketState ts ON t.id = ts.ticketFk - JOIN alertLevel al ON al.alertLevel = ts.alertLevel - JOIN agencyMode am ON am.id = t.agencyModeFk - JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk - WHERE shipped BETWEEN vDateTo AND vDateToEndDay - AND al.code NOT IN('DELIVERED','PACKED') - AND t.routeFk - HAVING tickets IS NOT NULL; - - DROP TEMPORARY TABLE tmp.ticketClosure; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketClosureMultiWarehouse__2` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; /*!50003 SET character_set_client = utf8mb4 */ ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosureMultiWarehouse__2`(vDateTo DATE) +CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosureMultiWarehouse__`(vDateTo DATE) BEGIN /** * Inserta los tickets de todos los almacenes en la tabla temporal @@ -68776,136 +72729,6 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketClosure__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosure__`() -BEGIN -/** - * @deprecated Use ticket_close() - * Realiza el cierre de todos los - * tickets de la table ticketClosure. - */ - DECLARE vDone BOOL; - DECLARE vClientFk INT; - DECLARE vTicketFk INT; - DECLARE vIsTaxDataChecked BOOL; - DECLARE vCompanyFk INT; - DECLARE vShipped DATE; - DECLARE vPriority INT DEFAULT 1; - DECLARE vReportDeliveryNote INT DEFAULT 1; - DECLARE vNewInvoiceId INT; - DECLARE vHasDailyInvoice BOOL; - DECLARE vWithPackage BOOL; - DECLARE vHasToInvoice BOOL; - - DECLARE cur CURSOR FOR - SELECT ticketFk FROM tmp.ticketClosure; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - RESIGNAL; - END; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure2; - CREATE TEMPORARY TABLE tmp.ticketClosure2 - SELECT ticketFk FROM tmp.ticketClosure; - INSERT INTO tmp.ticketClosure - SELECT id FROM stowaway s - JOIN tmp.ticketClosure2 tc ON s.shipFk = tc.ticketFk; - OPEN cur; - - proc: LOOP - SET vDone = FALSE; - - FETCH cur INTO vTicketFk; - - IF vDone THEN - LEAVE proc; - END IF; - - -- ticketClosure start - SELECT - c.id, - c.isTaxDataChecked, - t.companyFk, - t.shipped, - co.hasDailyInvoice, - w.isManaged, - c.hasToInvoice - INTO vClientFk, - vIsTaxDataChecked, - vCompanyFk, - vShipped, - vHasDailyInvoice, - vWithPackage, - vHasToInvoice - FROM ticket t - JOIN `client` c ON c.id = t.clientFk - JOIN province p ON p.id = c.provinceFk - JOIN country co ON co.id = p.countryFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.id = vTicketFk; - - INSERT INTO ticketPackaging (ticketFk, packagingFk, quantity) - (SELECT vTicketFk, p.id, COUNT(*) - FROM expedition e - JOIN packaging p ON p.itemFk = e.itemFk - WHERE e.ticketFk = vTicketFk AND p.isPackageReturnable - AND vWithPackage - GROUP BY p.itemFk); - - -- No retornables o no catalogados - INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, isPriceFixed) - (SELECT e.itemFk, vTicketFk, i.name, COUNT(*) AS amount, getSpecialPrice(e.itemFk, vClientFk), 1 - FROM expedition e - JOIN item i ON i.id = e.itemFk - LEFT JOIN packaging p ON p.itemFk = i.id - WHERE e.ticketFk = vTicketFk AND IFNULL(p.isPackageReturnable, 0) = 0 - AND getSpecialPrice(e.itemFk, vClientFk) > 0 - GROUP BY e.itemFk); - - IF(vHasDailyInvoice) AND vHasToInvoice THEN - - -- Facturacion rapida - CALL ticketTrackingAdd(vTicketFk, 'DELIVERED', NULL); - -- Facturar si está contabilizado - IF vIsTaxDataChecked THEN - CALL invoiceOut_newFromClient( - vClientFk, - (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), - vShipped, - vCompanyFk, - NULL, - vNewInvoiceId); - END IF; - ELSE - -- Albaran_print - CALL ticketTrackingAdd(vTicketFk, (SELECT vn.getAlert3State(vTicketFk)), NULL); - -- Comentar al pasar a nuevo cierre - INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(vPriority, vReportDeliveryNote, vTicketFk); - -- INSERT INTO - END IF; - - -- ticketClosure end - END LOOP; - - CLOSE cur; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure2; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `ticketCollection_get` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -69200,104 +73023,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketCreateWithoutZone` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithoutZone`( - vClientId INT - ,vShipped DATE - ,vWarehouseFk INT - ,vCompanyFk INT - ,vAddressFk INT - ,vAgencyModeFk INT - ,vRouteFk INT - ,vlanded DATE - ,vUserId INT - ,OUT vNewTicket INT) -BEGIN - - DECLARE vZoneFk INT; - - IF vClientId IS NULL THEN - CALL util.throw ('CLIENT_NOT_ESPECIFIED'); - END IF; - - IF NOT vAddressFk OR vAddressFk IS NULL THEN - SELECT id INTO vAddressFk - FROM address - WHERE clientFk = vClientId AND isDefaultAddress; - END IF; - - IF NOT vAgencyModeFk OR vAgencyModeFk IS NULL THEN - SELECT agencyModeFk INTO vAgencyModeFk - FROM address - WHERE clientFk = vClientId AND isDefaultAddress; - END IF; - - CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); - - SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped - WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; - - INSERT INTO vn2008.Tickets ( - Id_Cliente, - Fecha, - Id_Consigna, - Id_Agencia, - Alias, - warehouse_id, - Id_Ruta, - empresa_id, - landing, - zoneFk - ) - SELECT - vClientId, - vShipped, - a.id, - IF(vAgencyModeFk, vAgencyModeFk, a.agencyModeFk), - a.nickname, - vWarehouseFk, - IF(vRouteFk,vRouteFk,NULL), - vCompanyFk, - vlanded, - vZoneFk - FROM address a - JOIN agencyMode am ON am.id = a.agencyModeFk - WHERE a.id = vAddressFk; - - SET vNewTicket = LAST_INSERT_ID(); - - INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) - SELECT vNewTicket, ao.observationTypeFk, ao.description - FROM addressObservation ao - JOIN address a ON a.id = ao.addressFk - WHERE a.id = vAddressFk; - - -- CALL logAddWithUser(vNewTicket, vUserId, 'insert', 'ticket', CONCAT('Ha creado el ticket', ' ', vNewTicket)); - INSERT INTO vn.ticketLog - SET originFk = vNewTicket, userFk = vUserId, `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket); - - IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN - INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - SELECT id, vNewTicket, vUserId - FROM state - WHERE `code` = 'DELIVERED'; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketCreateWithoutZone__` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticketCreateWithUser` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -69307,103 +73033,6 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithoutZone__`( - vClientId INT - ,vShipped DATE - ,vWarehouseFk INT - ,vCompanyFk INT - ,vAddressFk INT - ,vAgencyModeFk INT - ,vRouteFk INT - ,vlanded DATE - ,vUserId INT - ,OUT vNewTicket INT) -BEGIN - - DECLARE vZoneFk INT; - - IF vClientId IS NULL THEN - CALL util.throw ('CLIENT_NOT_ESPECIFIED'); - END IF; - - IF NOT vAddressFk OR vAddressFk IS NULL THEN - SELECT id INTO vAddressFk - FROM address - WHERE clientFk = vClientId AND isDefaultAddress; - END IF; - - IF NOT vAgencyModeFk OR vAgencyModeFk IS NULL THEN - SELECT agencyModeFk INTO vAgencyModeFk - FROM address - WHERE clientFk = vClientId AND isDefaultAddress; - END IF; - - CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); - - SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped - WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; - - INSERT INTO vn2008.Tickets ( - Id_Cliente, - Fecha, - Id_Consigna, - Id_Agencia, - Alias, - warehouse_id, - Id_Ruta, - empresa_id, - landing, - zoneFk - ) - SELECT - vClientId, - vShipped, - a.id, - IF(vAgencyModeFk, vAgencyModeFk, a.agencyModeFk), - a.nickname, - vWarehouseFk, - IF(vRouteFk,vRouteFk,NULL), - vCompanyFk, - vlanded, - vZoneFk - FROM address a - JOIN agencyMode am ON am.id = a.agencyModeFk - WHERE a.id = vAddressFk; - - SET vNewTicket = LAST_INSERT_ID(); - - INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) - SELECT vNewTicket, ao.observationTypeFk, ao.description - FROM addressObservation ao - JOIN address a ON a.id = ao.addressFk - WHERE a.id = vAddressFk; - - -- CALL logAddWithUser(vNewTicket, vUserId, 'insert', 'ticket', CONCAT('Ha creado el ticket', ' ', vNewTicket)); - INSERT INTO vn.ticketLog - SET originFk = vNewTicket, userFk = vUserId, `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket); - - IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN - INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - SELECT id, vNewTicket, getWorker() - FROM state - WHERE `code` = 'DELIVERED'; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketCreateWithUser` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithUser`( vClientId INT ,vShipped DATE @@ -69416,7 +73045,7 @@ CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithUser`( ,vUserId INT ,OUT vNewTicket INT) BEGIN - +-- si se modifica algo avisad a jgallego DECLARE vZoneFk INT; DECLARE vPrice DECIMAL(10,2); DECLARE vBonus DECIMAL(10,2); @@ -69635,7 +73264,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketFilter` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticketFilter__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -69645,7 +73274,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketFilter`() +CREATE DEFINER=`root`@`%` PROCEDURE `ticketFilter__`() BEGIN /** * Obtiene un listado de tickets @@ -69687,8 +73316,9 @@ DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ticketGetProblems`(IN vIsTodayRelative TINYINT(1)) BEGIN /** - * Hay una versión en salix que machacará toda esta función/procedimiento avisa - * a joan de los cambios que quieres hacer. + * @deprecated Use ticket_getProblems() instead + * + * Hay que revisar los dos procesos y unificarlos. No son equivalentes. PAK 04/06/21 * */ DECLARE vWarehouse INT; @@ -69696,10 +73326,12 @@ BEGIN DECLARE vAvailableCache INT; DECLARE vDone INT DEFAULT 0; DECLARE vComponentCount INT; + DECLARE vHasUbications BOOL; DECLARE vCursor CURSOR FOR - SELECT DISTINCT tt.warehouseFk, IF(vIsTodayRelative, CURDATE(), date(tt.shipped)) + SELECT DISTINCT tt.warehouseFk, IF(vIsTodayRelative, CURDATE(), date(tt.shipped)), w.hasUbications FROM tmp.ticketGetProblems tt + JOIN vn.warehouse w ON w.id = tt.warehouseFk WHERE DATE(tt.shipped) BETWEEN CURDATE() AND TIMESTAMPADD(DAY, IF(vIsTodayRelative, 9.9, 1.9), CURDATE()); @@ -69731,9 +73363,13 @@ BEGIN WHERE c.isRequired; INSERT INTO tmp.ticketProblems(ticketFk, componentLack) - SELECT tl.ticketFk, (COUNT(DISTINCT s.id) * vComponentCount > COUNT(c.id)) + SELECT tl.ticketFk, + (COUNT(DISTINCT s.id) * (vComponentCount - (dm.code = 'PICKUP')) > COUNT(c.id)) FROM tmp.ticketList tl JOIN vn.sale s ON s.ticketFk = tl.ticketFk + JOIN vn.ticket t ON t.id = tl.ticketFk + JOIN vn.agencyMode am ON am.id = t.agencyModeFk + JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id LEFT JOIN vn.component c ON c.id = sc.componentFk AND c.isRequired GROUP BY tl.ticketFk; @@ -69780,7 +73416,7 @@ BEGIN WHILE NOT vDone DO - FETCH vCursor INTO vWarehouse, vDate; + FETCH vCursor INTO vWarehouse, vDate, vHasUbications; CALL cache.available_refresh(vAvailableCache, FALSE, vWarehouse, vDate); @@ -69802,56 +73438,61 @@ BEGIN GROUP BY tl.ticketFk ON DUPLICATE KEY UPDATE isAvailable = 0; -/* - INSERT INTO tmp.ticketProblems(ticketFk, itemShortage) - SELECT ticketFk, problem - FROM ( - SELECT tl.ticketFk, CONCAT('F: ',GROUP_CONCAT(i.id, ' ', i.longName, ' ')) problem - FROM tmp.ticketList tl - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it on it.id = i.typeFk - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk - LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - WHERE IFNULL(av.available, 0) < 0 - AND s.quantity > IFNULL(issw.visible, 0) - AND s.quantity > 0 - AND s.isPicked = FALSE - AND s.reserved = FALSE - AND it.categoryFk != 6 - AND IF(vIsTodayRelative, TRUE, date(t.shipped) = vDate) - AND NOT i.generic - AND CURDATE() = vDate - AND t.warehouseFk = vWarehouse - GROUP BY tl.ticketFk LIMIT 1) sub - ON DUPLICATE KEY UPDATE - itemShortage = sub.problem; -*/ - INSERT INTO tmp.ticketProblems(ticketFk, itemDelay) - SELECT ticketFk, problem - FROM ( - SELECT tl.ticketFk, GROUP_CONCAT('I: ',i.id, ' ', i.longName, ' ') problem - FROM tmp.ticketList tl - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it on it.id = i.typeFk - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk - WHERE s.quantity > IFNULL(issw.visible, 0) - AND s.quantity > 0 - AND s.isPicked = FALSE - AND s.reserved = FALSE - AND it.categoryFk != 6 - AND IF(vIsTodayRelative, TRUE, date(t.shipped) = vDate) - AND NOT i.generic - AND CURDATE() = vDate - AND t.warehouseFk = vWarehouse - GROUP BY tl.ticketFk LIMIT 1) sub - ON DUPLICATE KEY UPDATE - itemDelay = sub.problem; - END WHILE; + IF vHasUbications THEN + + INSERT INTO tmp.ticketProblems(ticketFk, itemShortage) + SELECT ticketFk, problem + FROM ( + SELECT tl.ticketFk, CONCAT('F: ',GROUP_CONCAT(i.id, ' ', i.longName, ' ')) problem + FROM tmp.ticketList tl + JOIN vn.ticket t ON t.id = tl.ticketFk + JOIN vn.sale s ON s.ticketFk = t.id + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it on it.id = i.typeFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache + WHERE IFNULL(av.available, 0) < 0 + AND s.quantity > IFNULL(issw.visible, 0) + AND s.quantity > 0 + AND s.isPicked = FALSE + AND s.reserved = FALSE + AND it.categoryFk != 6 + AND IF(vIsTodayRelative, TRUE, date(t.shipped) = vDate) + AND NOT i.generic + AND CURDATE() = vDate + AND t.warehouseFk = vWarehouse + GROUP BY tl.ticketFk) sub + ON DUPLICATE KEY UPDATE + itemShortage = sub.problem; + + INSERT INTO tmp.ticketProblems(ticketFk, itemDelay) + SELECT ticketFk, problem + FROM ( + SELECT tl.ticketFk, GROUP_CONCAT('I: ',i.id, ' ', i.longName, ' ') problem + FROM tmp.ticketList tl + JOIN vn.ticket t ON t.id = tl.ticketFk + JOIN vn.sale s ON s.ticketFk = t.id + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it on it.id = i.typeFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + WHERE s.quantity > IFNULL(issw.visible, 0) + AND s.quantity > 0 + AND s.isPicked = FALSE + AND s.reserved = FALSE + AND it.categoryFk != 6 + AND IF(vIsTodayRelative, TRUE, date(t.shipped) = vDate) + AND NOT i.generic + AND CURDATE() = vDate + AND t.warehouseFk = vWarehouse + GROUP BY tl.ticketFk) sub + ON DUPLICATE KEY UPDATE + itemDelay = sub.problem; + + END IF; + + END WHILE; + CLOSE vCursor; INSERT INTO tmp.ticketProblems(ticketFk, isTaxDataChecked) @@ -69864,8 +73505,7 @@ BEGIN DROP TEMPORARY TABLE tmp.clientGetDebt, - tmp.ticketList; - + tmp.ticketList; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -70304,14 +73944,13 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ticketGetTotal`() - READS SQL DATA BEGIN /** * Calcula el total con IVA para un conjunto de tickets. @@ -70320,12 +73959,12 @@ BEGIN * @return tmp.ticketTotal Total para cada ticket */ CALL ticket_getTax(NULL); - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketTotal; CREATE TEMPORARY TABLE tmp.ticketTotal (INDEX (ticketFk)) ENGINE = MEMORY - SELECT t.ticketFk, + SELECT t.ticketFk, IFNULL(SUM(ta.taxableBase + ta.tax), 0.0) AS total, SUM(ta.taxableBase) totalWithoutVat FROM tmp.ticket t @@ -70850,6 +74489,39 @@ BEGIN SELECT TRUE AS IsUpdated; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketStateToday_setOnchecking` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketStateToday_setOnchecking`(vParamFk INT) +BEGIN + + DECLARE vAlertLevel INT; + + SELECT s.alertLevel INTO vAlertLevel + FROM vn.state s + JOIN vn.ticketStateToday tst ON tst.state = s.id + WHERE tst.ticket = vParamFk + LIMIT 1; + + IF vAlertLevel < 2 THEN + + CALL vn.ticketStateUpdate(vParamFk, 'ON_CHECKING'); + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -70927,17 +74599,17 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketToInvoiceByClient` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticketToInvoiceByClient__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketToInvoiceByClient`( +CREATE DEFINER=`root`@`%` PROCEDURE `ticketToInvoiceByClient__`( vStarted DATE, vEnded DATETIME, vClient INT, @@ -71072,6 +74744,9 @@ DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ticketToPrePrepare`(IN vIdTicket INT, IN viewAll BOOL, IN vSectorFk INT) BEGIN +/* Tickets de preparacion previa (artificial) 21/03/2021 PAK +*/ + /* Tickets de preparacion previa (artificial) 21/03/2021 PAK */ @@ -71105,7 +74780,8 @@ IF viewAll IS true THEN stpp.Id_Movimiento_mark, stpp.Id_Trabjador, stpp.Id_Article, - CONCAT('(', i.itemPackingTypeFk,') ', stpp.Concepte) Concepte, + i.itemPackingTypeFk packingType, + stpp.Concepte Concepte, stpp.subName, stpp.Cantidad, stpp.original_quantity, @@ -71414,6 +75090,110 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_add`( + vClientId INT + ,vShipped DATE + ,vWarehouseFk INT + ,vCompanyFk INT + ,vAddressFk INT + ,vAgencyModeFk INT + ,vRouteFk INT + ,vlanded DATE + ,vUserId INT + ,vIsRequiredZone INT + ,OUT vNewTicket INT) +BEGIN + + DECLARE vZoneFk INT; + DECLARE vPrice DECIMAL(10,2); + DECLARE vBonus DECIMAL(10,2); + + IF vClientId IS NULL THEN + CALL util.throw ('CLIENT_NOT_ESPECIFIED'); + END IF; + + IF NOT vAddressFk OR vAddressFk IS NULL THEN + SELECT id INTO vAddressFk + FROM address + WHERE clientFk = vClientId AND isDefaultAddress; + END IF; + + IF vAgencyModeFk IS NOT NULL THEN + + CALL vn.zone_getShipped (vlanded, vAddressFk, vAgencyModeFk, TRUE); + + SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus + FROM tmp.zoneGetShipped + WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; + + IF (vZoneFk IS NULL OR vZoneFk = 0) AND vIsRequiredZone THEN + CALL util.throw ('NOT_ZONE_WITH_THIS_PARAMETERS'); + END IF; + END IF; + INSERT INTO ticket ( + clientFk, + shipped, + addressFk, + agencyModeFk, + nickname, + warehouseFk, + routeFk, + companyFk, + landed, + zoneFk, + zonePrice, + zoneBonus + ) + SELECT + vClientId, + vShipped, + a.id, + vAgencyModeFk, + a.nickname, + vWarehouseFk, + IF(vRouteFk,vRouteFk,NULL), + vCompanyFk, + vlanded, + vZoneFk, + vPrice, + vBonus + FROM address a + JOIN agencyMode am ON am.id = a.agencyModeFk + WHERE a.id = vAddressFk; + + SET vNewTicket = LAST_INSERT_ID(); + + INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) + SELECT vNewTicket, ao.observationTypeFk, ao.description + FROM addressObservation ao + JOIN address a ON a.id = ao.addressFk + WHERE a.id = vAddressFk; + + INSERT INTO vn.ticketLog + SET originFk = vNewTicket, userFk = vUserId, `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket); + + IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT id, vNewTicket, account.myUser_getId() + FROM state + WHERE `code` = 'DELIVERED'; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `ticket_administrativeCopy` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -71440,6 +75220,53 @@ BEGIN FROM vn.sale s WHERE s.ticketFk = vOriginalTicket; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_changeClient` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_changeClient`(vNewClient INT, vUserFk INT) +BEGIN + +/** + * Dado un conjunto de tickets + * cambia el cliente al nuevo cliente dado + * + * params @vNewClient nuevo cliente + * params @vUserFk usuario que realiza el cambio + * + * table @tmp.ticket(ticketFk) conjunto de tickets + */ + + INSERT INTO ticketLog (originFk, userFk, `action`, changedModel, oldInstance, newInstance) + SELECT t.id, vUserFk, 'update', 'Ticket', CONCAT('{"clientFk":',t.clientFk,'}'), CONCAT('{"clientFk":',vNewClient,'}') + FROM ticket t + JOIN tmp.ticket tt + ON t.id = tt.ticketFk; + + UPDATE ticket t + JOIN tmp.ticket tt + ON t.id = tt.ticketFk + SET t.clientFk = vNewClient; + + UPDATE ticket t + JOIN tmp.ticket tt + ON t.id = tt.ticketFk + JOIN stowaway s + ON s.shipFk = tt.ticketFk + SET t.clientFk = vNewClient; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -71536,7 +75363,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ticket_Clone`(vOriginalTicket INT, OUT vNewTicket INT) BEGIN - +/** + * Clona el contenido de un ticket en otro + * + * @param vOriginalTicket ticket Original + * @param vNewTicket ticket creado + */ DECLARE vStateFk INT; INSERT INTO ticket ( @@ -71584,6 +75416,10 @@ BEGIN INSERT INTO ticketLog SET originFk = vNewTicket, userFk = account.myUser_getId(), `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket, ' clonando el ', vOriginalTicket); + + INSERT INTO ticketLog + SET originFk = vOriginalTicket, userFk = account.myUser_getId(), `action` = 'insert', + description = CONCAT('Ha creado el ticket:', ' ', vNewTicket, ' clonando el ', vOriginalTicket); INSERT INTO vncontrol.inter(Id_Ticket, state_id, Id_Trabajador, odbc_date) SELECT vNewTicket, state_id, Id_Trabajador , odbc_date @@ -71600,14 +75436,167 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ticket_cloneWeekly`(IN vWeek INT) BEGIN + DECLARE vIsDone BOOL; + DECLARE vLanding DATE; + DECLARE vShipment DATE; + DECLARE vWarehouseFk INT; + DECLARE vTicketFk INT; + DECLARE vWeekDay INT; + DECLARE vClientFk INT; + DECLARE vCompanyFk INT; + DECLARE vAddressFk INT; + DECLARE vAgencyModeFk INT; + DECLARE vNewTicket INT; + DECLARE vYear INT; + + DECLARE rsTicket CURSOR FOR + SELECT tt.ticketFk, tt.weekDay, t.clientFk, t.warehouseFk, t.companyFk, t.addressFk, tt.agencyModeFk + FROM vn.ticketWeekly tt + JOIN vn.ticket t ON tt.ticketFk = t.id; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE; + + SET vYear = YEAR(CURDATE()) + IF(vWeek < WEEK(CURDATE()),1, 0); + + OPEN rsTicket; + myLoop: LOOP + BEGIN + DECLARE vSalesPersonEmail VARCHAR(150); + DECLARE vMailSent BOOL; + DECLARE vSubject VARCHAR(150); + DECLARE vMessage TEXT; + + SET vIsDone = FALSE; + FETCH rsTicket INTO vTicketFk, vWeekDay, vClientFk, vWarehouseFk, vCompanyFk, vAddressFk, vAgencyModeFk; + + IF vIsDone THEN + + LEAVE myLoop; + END IF; + SELECT dated INTO vShipment + FROM `time` + WHERE `year` = vYear AND `week` = vWeek + AND WEEKDAY(dated) = vWeekDay; + + -- busca si el ticket ya ha sido clonado + IF (SELECT COUNT(*) FROM vn.ticket tOrig + JOIN vn.sale saleOrig ON tOrig.id = saleOrig.ticketFk + JOIN vn.saleCloned sc ON sc.saleOriginalFk = saleOrig.id + JOIN vn.sale saleClon ON saleClon.id = sc.saleClonedFk + JOIN vn.ticket tClon ON tClon.id = saleClon.ticketFk + WHERE tOrig.id = vTicketFk AND tClon.isDeleted = FALSE AND DATE(tClon.shipped) = vShipment) > 0 + THEN + ITERATE myLoop; + END IF; + + IF vAgencyModeFk IS NULL THEN + SELECT agencyModeFk INTO vAgencyModeFk + FROM address + WHERE clientFk = vClientFk AND isDefaultAddress; + END IF; + + CALL vn.zone_getLanded(vShipment, vAddressFk, vAgencyModeFk, vWarehouseFk,FALSE); + SET vLanding = NULL; + SELECT landed INTO vLanding from tmp.zoneGetLanded LIMIT 1; + + CALL ticket_add( + vClientFk, + vShipment, + vWarehouseFk, + vCompanyFk, + vAddressFk, + vAgencyModeFk, + NULL, + vLanding, + account.userGetId(), + FALSE, + vNewTicket); + + IF (vLanding IS NULL) THEN + + SELECT e.email INTO vSalesPersonEmail + FROM vn.client c + JOIN vn.worker sp ON sp.id = c.salesPersonFk + JOIN account.emailUser e ON e.userFk = sp.userFk + WHERE c.id = vClientFk; + + SET vSubject = CONCAT('Turnos - No se ha podido clonar correctamente el ticket ', vTicketFk, + ' para el dia: ', vShipment); + SET vMessage = CONCAT('No se ha podido clonar el ticket ', vTicketFk, + ' para el dia: ', vShipment, + ' porque no hay una zona de envío disponible. Se ha creado el ticket: ', vNewTicket, + ' pero ha que revisar las fechas y la agencia'); + + SELECT COUNT(*) INTO vMailSent + FROM vn.mail + WHERE sender = vSalesPersonEmail + AND subject = vSubject; + + IF NOT vMailSent THEN + INSERT INTO vn.mail (`sender`,`subject`,`body`) + VALUES (vSalesPersonEmail, vSubject, vMessage); + END IF; + CALL vn.ticketStateUpdate (vNewTicket, 'FIXING'); + END IF; + + INSERT INTO vn.sale (ticketFk, itemFk, concept, quantity, price, discount, priceFixed, isPriceFixed) + SELECT vNewTicket, saleOrig.itemFk , saleOrig.concept , saleOrig.quantity, saleOrig.price , saleOrig.discount, saleOrig.priceFixed, saleOrig.isPriceFixed + FROM vn.sale saleOrig + WHERE saleOrig.ticketFk = vTicketFk; + + INSERT IGNORE INTO vn.saleCloned(saleOriginalFk, saleClonedFk) + SELECT saleOriginal.id, saleClon.id + FROM vn.sale saleOriginal + JOIN vn.sale saleClon ON saleOriginal.itemFk = saleClon.itemFk AND saleOriginal.quantity = saleClon.quantity + WHERE saleOriginal.ticketFk = vTicketFk AND saleClon.ticketFk = vNewTicket; + + INSERT INTO ticketRequest (description,ordered,shipped,salesPersonCode,buyerCode,quantity,price,itemFk,clientFk,response, + total,buyed,saleFk) + SELECT o.description,o.ordered,vShipment,o.salesPersonCode,o.buyerCode,o.quantity,o.price,o.itemFk,o.clientFk,o.response, + o.total,o.buyed,s2.id + FROM sale s JOIN ticketRequest o ON o.saleFk = s.id + JOIN sale s2 ON s.concept = s2.concept AND s.quantity = s2.quantity AND s.itemFk = s2.itemFk + WHERE s.ticketFk = vTicketFk AND s2.ticketFk = vNewTicket; + + INSERT INTO ticketObservation(ticketFk,observationTypeFk,description) VALUES(vNewTicket,4,CONCAT('turno desde ticket: ',vTicketFk)) + ON DUPLICATE KEY UPDATE description = CONCAT(ticketObservation.description,VALUES(description),' '); + + INSERT INTO ticketObservation(ticketFk,observationTypeFk,description) VALUES(vNewTicket,1,'ATENCION: Contiene lineas de TURNO') + ON DUPLICATE KEY UPDATE description = CONCAT(ticketObservation.description,VALUES(description),' '); + + CALL vn.ticketCalculateClon(vNewTicket, vTicketFk); + END; + END LOOP; + + CLOSE rsTicket; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_cloneWeekly__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_cloneWeekly__`(IN vWeek INT) +BEGIN + -- si se modifica algo avisad a jgallego DECLARE vIsDone BOOL; DECLARE vLanding DATE; DECLARE vShipment DATE; @@ -71740,7 +75729,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticket_cloneWeekly__` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_close` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -71750,145 +75739,6 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_cloneWeekly__`(IN vWeek INT) -BEGIN - DECLARE vIsDone BOOL; - DECLARE vLanding DATE; - DECLARE vShipment DATE; - DECLARE vWarehouse INT; - DECLARE vTicket INT; - DECLARE vWeekDay INT; - DECLARE vClient INT; - DECLARE vEmpresa INT; - DECLARE vAddressFk INT; - DECLARE vAgencyModeFk INT; - DECLARE vNewTicket INT; - DECLARE vYear INT; - - DECLARE rsTicket CURSOR FOR - SELECT tw.ticketFk, weekDay, t.clientFk, t.warehouseFk, t.companyFk, t.addressFk, tw.agencyModeFk - FROM ticketWeekly tw - JOIN ticket t ON tt.ticketFk = t.id; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE; - - SET vYear = YEAR(CURDATE()) + IF(vWeek < WEEK(CURDATE()),1, 0); - - OPEN rsTicket; - - myLoop: LOOP - BEGIN - DECLARE vError TEXT; - DECLARE vSalesPersonEmail VARCHAR(150); - DECLARE vMailSent BOOL; - DECLARE vSubject VARCHAR(150); - DECLARE vMessage TEXT; - DECLARE CONTINUE HANDLER FOR SQLEXCEPTION - BEGIN - GET DIAGNOSTICS CONDITION 1 - vError = MESSAGE_TEXT; - END; - - SET vIsDone = FALSE; - FETCH rsTicket INTO vTicket, vWeekDay, vClient, vWarehouse, vEmpresa, vAddressFk, vAgencyModeFk; - - IF vIsDone THEN - - LEAVE myLoop; - END IF; - SELECT date INTO vShipment - FROM `time` - WHERE `year` = vYear AND `week` = vWeek - AND WEEKDAY(date) = vWeekDay; - - -- busca si el ticket ya ha sido clonado - IF (SELECT COUNT(*) FROM vn.ticket tOrig - JOIN vn.sale saleOrig ON tOrig.id = saleOrig.ticketFk - JOIN vn.saleCloned sc ON sc.saleOriginalFk = saleOrig.id - JOIN vn.sale saleClon ON saleClon.id = sc.saleClonedFk - JOIN vn.ticket tClon ON tClon.id = saleClon.ticketFk - WHERE tOrig.id = vTicket AND DATE(tClon.shipped) = vShipment) > 0 - THEN - ITERATE myLoop; - END IF; - CALL vn.zone_getLanded(vShipment, vAddressFk, vAgencyModeFk, vWarehouse, TRUE); - - SELECT landed INTO vLanding from tmp.zoneGetLanded LIMIT 1; - - CALL vn.ticketCreateWithoutZone(vClient, vShipment, vWarehouse, vEmpresa, vAddressFk, vAgencyModeFk, NULL, vLanding, account.userGetId(), vNewTicket); - - IF (vLanding IS NULL) THEN - - SELECT e.email INTO vSalesPersonEmail - FROM vn.client c - JOIN vn.worker sp ON sp.id = c.salesPersonFk - JOIN account.emailUser e ON e.userFk = sp.userFk - WHERE c.id = vClient; - - SET vSubject = CONCAT('Turnos - No se ha podido clonar correctamente el ticket ', vTicket, - ' para el dia: ', vShipment); - SET vMessage = CONCAT('No se ha podido clonar el ticket ', vTicket, - ' para el dia: ', vShipment, - ' porque no hay una zona de envío disponible. Se ha creado el ticket: ', vNewTicket, - ' pero ha que revisar las fechas y la agencia'); - - SELECT COUNT(*) INTO vMailSent - FROM vn.mail - WHERE sender = vSalesPersonEmail - AND subject = vSubject; - - IF NOT vMailSent THEN - INSERT INTO vn.mail (sender,`subject`,body) - VALUES (vSalesPersonEmail, vSubject, vMessage); - END IF; - CALL vn.ticketStateUpdate (vNewTicket, 'FIXING'); - END IF; - - INSERT INTO vn.sale (ticketFk, itemFk, concept, quantity, price, discount, priceFixed, isPriceFixed) - SELECT vNewTicket, saleOrig.itemFk , saleOrig.concept , saleOrig.quantity, saleOrig.price , saleOrig.discount, saleOrig.priceFixed, saleOrig.isPriceFixed - FROM vn.ticket tOrig - JOIN vn.sale saleOrig ON tOrig.id = saleOrig.ticketFk - LEFT JOIN vn.saleCloned sc ON sc.saleOriginalFk = saleOrig.id - LEFT JOIN vn.sale saleClon ON saleClon.id = sc.saleClonedFk - LEFT JOIN vn.ticket tClon ON tClon.id = saleClon.ticketFk AND DATE(tClon.shipped) = vShipment - WHERE tOrig.id = vTicket AND saleClon.id IS NULL; - - INSERT IGNORE INTO vn.saleCloned(saleOriginalFk, saleClonedFk) - SELECT saleOriginal.id, saleClon.id - FROM vn.sale saleOriginal - JOIN vn.sale saleClon ON saleOriginal.itemFk = saleClon.itemFk AND saleOriginal.quantity = saleClon.quantity - WHERE saleOriginal.ticketFk = vTicket AND saleClon.ticketFk = vNewTicket; - - INSERT INTO ticketRequest (description, ordered, shipped, salesPersonCode, buyerCode, quantity, price, - itemFk ,clientFk, response, total, buyed, saleFk) - SELECT tr.description, tr.ordered, tr.shipped, tr.salesPersonCode, tr.buyerCode, tr.quantity, tr.price, - tr.itemFk, tr.clientFk, tr.response, tr.total, tr.buyed, tr.saleFk - FROM sale s JOIN ticketRequest tr ON tr.saleFk = s.id - JOIN sale s2 ON s.concept = s2.concept AND s.quantity = s2.quantity AND m.Id_Article = m2.Id_Article - WHERE s.ticketFk = vTicket AND s2.ticketFk = vNewTicket; - - CALL vn.ticketCalculateClon(vNewTicket, vTicket); - END; - END LOOP; - - CLOSE rsTicket; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticket_close` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ticket_close`(vTicketFk INT) BEGIN /** @@ -71989,6 +75839,7 @@ BEGIN vShipped, vCompanyFk, NULL, + NULL, vNewInvoiceId); END IF; ELSE @@ -71997,8 +75848,9 @@ BEGIN END LOOP; CLOSE cur; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72115,6 +75967,7 @@ BEGIN vShipped, vCompanyFk, NULL, + NULL, vNewInvoiceId); END IF; ELSE @@ -72182,46 +76035,40 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_componentMakeUpdate`(IN vTicketFk INT, IN vClientFk INT, IN vAgencyModeFk INT, +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_componentMakeUpdate`(IN vTicketFk INT, IN vClientFk INT, + IN vNickname VARCHAR(50), IN vAgencyModeFk INT, IN vAddressFk INT, IN vZoneFk INT, IN vWarehouseFk TINYINT, IN vCompanyFk SMALLINT, IN vShipped DATETIME, IN vLanded DATE, IN vIsDeleted TINYINT(1), IN vHasToBeUnrouted TINYINT(1), IN vOption INT) BEGIN -/** - * Hay una versión en salix que machacará toda esta función/procedimiento avisa - * a carlosjr de los cambios que quieres hacer. - * - * Modifica en el ticket los campos que se le pasan por parámetro - * y cambia sus componentes - * - * @param vTicketFk Id del ticket a modificar - * @param vClientFk nuevo cliente - * @param vAgencyModeFk nueva agencia - * @param vAddressFk nuevo consignatario - * @param vZoneFk nueva zona - * @param vWarehouseFk nuevo almacen - * @param vCompanyFk nueva empresa - * @param vShipped nueva fecha del envio de mercancia - * @param vLanded nueva fecha de recepcion de mercancia - * @param vIsDeleted si se borra el ticket - * @param vHasToBeUnrouted si se le elimina la ruta al ticket - * @param vOption opcion para el case del proc ticketComponentUpdateSale - */ + + /** + * Modifica en el ticket los campos que se le pasan por parámetro + * y cambia sus componentes + * + * @param vTicketFk Id del ticket a modificar + * @param vClientFk nuevo cliente + * @param vNickname nuevo alias + * @param vAgencyModeFk nueva agencia + * @param vAddressFk nuevo consignatario + * @param vZoneFk nueva zona + * @param vWarehouseFk nuevo almacen + * @param vCompanyFk nueva empresa + * @param vShipped nueva fecha del envio de mercancia + * @param vLanded nueva fecha de recepcion de mercancia + * @param vIsDeleted si se borra el ticket + * @param vHasToBeUnrouted si se le elimina la ruta al ticket + * @param vOption opcion para el case del proc ticketComponentUpdateSale + */ + DECLARE vPrice DECIMAL(10,2); DECLARE vBonus DECIMAL(10,2); - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; CALL ticket_componentPreview (vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk); - START TRANSACTION; - IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN UPDATE ticket t @@ -72231,7 +76078,7 @@ BEGIN END IF; - CALL zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); + CALL zone_getShipped(vLanded, vAddressFk, vAgencyModeFk, TRUE); SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus FROM tmp.zoneGetShipped @@ -72240,6 +76087,7 @@ BEGIN UPDATE ticket t SET t.clientFk = vClientFk, + t.nickname = vNickname, t.agencyModeFk = vAgencyModeFk, t.addressFk = vAddressFk, t.zoneFk = vZoneFk, @@ -72254,10 +76102,8 @@ BEGIN t.id = vTicketFk; IF vHasToBeUnrouted THEN - UPDATE ticket t - SET t.routeFk = NULL, - t.shipped = TIMESTAMP(DATE(t.shipped), 0) - WHERE t.id = vTicketFk; + UPDATE ticket t SET t.routeFk = NULL + WHERE t.id = vTicketFk; END IF; IF vOption <> 8 THEN @@ -72266,9 +76112,7 @@ BEGIN (PRIMARY KEY (saleFk)) ENGINE = MEMORY SELECT id AS saleFk, vWarehouseFk warehouseFk - FROM sale s - LEFT JOIN vn.saleCloned sc ON sc.saleClonedFk = s.id - WHERE s.ticketFk = vTicketFk AND sc.saleClonedFk IS NULL; + FROM sale s WHERE s.ticketFk = vTicketFk; DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; CREATE TEMPORARY TABLE tmp.ticketComponent @@ -72279,7 +76123,6 @@ BEGIN DROP TEMPORARY TABLE tmp.sale; DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; END IF; - COMMIT; DROP TEMPORARY TABLE tmp.zoneGetShipped, tmp.ticketComponentPreview; END ;; @@ -72788,6 +76631,51 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_getProblems` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_getProblems`(IN vIsTodayRelative TINYINT(1)) +BEGIN +/** + * Calcula los problemas para un conjunto de tickets. + * Agrupados por ticket + * + * @table tmp.sale_getProblems(ticketFk, clientFk, warehouseFk, shipped) Identificadores de los tickets a calcular + * @return tmp.ticket_problems + */ + CALL sale_getProblems(vIsTodayRelative); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket_problems; + CREATE TEMPORARY TABLE tmp.ticket_problems + (INDEX (ticketFk)) + ENGINE = MEMORY + SELECT + ticketFk, + MAX(p.isFreezed) AS isFreezed, + MAX(p.risk) AS risk, + MAX(p.hasTicketRequest) AS hasTicketRequest, + MIN(p.isAvailable) AS isAvailable, + MAX(p.itemShortage) AS itemShortage, + MIN(p.isTaxDataChecked) AS isTaxDataChecked, + MAX(p.hasComponentLack) AS hasComponentLack + FROM tmp.sale_problems p + GROUP BY ticketFk; + + DROP TEMPORARY TABLE + tmp.sale_problems; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `ticket_getShip` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -72814,20 +76702,19 @@ DELIMITER ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; /*!50003 SET character_set_client = utf8mb4 */ ; /*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_getTax`(vTaxArea VARCHAR(25)) - READS SQL DATA +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_getTax`(IN vTaxArea VARCHAR(25)) BEGIN /** * Calcula la base imponible, el IVA y el recargo de equivalencia para * un conjunto de tickets. * * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular - * @return tmp.ticketAmount - * @return tmp.ticketTax Impuesto desglosado para cada ticket. + * @return tmp.ticketAmount (ticketFk, taxableBase, tax, code) + * @return tmp.ticketTax (ticketFk, pgcFk, taxableBase, rate, code) Impuesto desglosado para cada ticket. */ DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; CREATE TEMPORARY TABLE tmp.addressCompany @@ -72838,50 +76725,50 @@ BEGIN JOIN ticket t ON t.id = tmpTicket.ticketFk; CALL addressTaxArea (); - + IF vTaxArea > '' THEN UPDATE tmp.addressTaxArea SET areaFk = vTaxArea; END IF; /* Solo se calcula la base imponible (taxableBase) y el impuesto se calculará posteriormente - * No se debería cambiar el sistema por problemas con los decimales + * No se debería cambiar el sistema por problemas con los decimales */ DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax; CREATE TEMPORARY TABLE tmp.ticketTax - (INDEX (ticketFk)) + (PRIMARY KEY (ticketFk, code, rate)) ENGINE = MEMORY - SELECT * FROM ( - SELECT tmpTicket.ticketFk, - bp.pgcFk, - SUM(s.quantity * s.price * (100 - s.discount)/100 ) AS taxableBase, - pgc.rate, - tc.code, - bp.priority - FROM tmp.ticket tmpTicket - JOIN sale s ON s.ticketFk = tmpTicket.ticketFk - JOIN item i ON i.id = s.itemFk - JOIN ticket t ON t.id = tmpTicket.ticketFk - JOIN supplier su ON su.id = t.companyFk - JOIN tmp.addressTaxArea ata - ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk - JOIN itemTaxCountry itc - ON itc.itemFk = i.id AND itc.countryFk = su.countryFk - JOIN bookingPlanner bp - ON bp.countryFk = su.countryFk - AND bp.taxAreaFk = ata.areaFk - AND bp.taxClassFk = itc.taxClassFk - JOIN pgc ON pgc.code = bp.pgcFk - JOIN taxClass tc ON tc.id = bp.taxClassFk - GROUP BY tmpTicket.ticketFk, pgc.code,pgc.rate - HAVING taxableBase != 0) t - ORDER BY priority; + SELECT * FROM ( + SELECT tmpTicket.ticketFk, + bp.pgcFk, + SUM(s.quantity * s.price * (100 - s.discount)/100 ) AS taxableBase, + pgc.rate, + tc.code, + bp.priority + FROM tmp.ticket tmpTicket + JOIN sale s ON s.ticketFk = tmpTicket.ticketFk + JOIN item i ON i.id = s.itemFk + JOIN ticket t ON t.id = tmpTicket.ticketFk + JOIN supplier su ON su.id = t.companyFk + JOIN tmp.addressTaxArea ata + ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk + JOIN itemTaxCountry itc + ON itc.itemFk = i.id AND itc.countryFk = su.countryFk + JOIN bookingPlanner bp + ON bp.countryFk = su.countryFk + AND bp.taxAreaFk = ata.areaFk + AND bp.taxClassFk = itc.taxClassFk + JOIN pgc ON pgc.code = bp.pgcFk + JOIN taxClass tc ON tc.id = bp.taxClassFk + GROUP BY tmpTicket.ticketFk, pgc.code, pgc.rate + HAVING taxableBase != 0) t3 + ORDER BY priority; DROP TEMPORARY TABLE IF EXISTS tmp.ticketServiceTax; CREATE TEMPORARY TABLE tmp.ticketServiceTax - (PRIMARY KEY (ticketFk, rate,code)) + (PRIMARY KEY (ticketFk, code, rate)) ENGINE = MEMORY - SELECT tt.ticketFk, + SELECT tt.ticketFk, pgc.code pgcFk, SUM(ts.quantity * ts.price) AS taxableBase, pgc.rate, @@ -72891,31 +76778,34 @@ BEGIN JOIN ticket t ON t.id = tt.ticketFk JOIN supplier su ON su.id = t.companyFk JOIN tmp.addressTaxArea ata - ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk + ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk JOIN bookingPlanner bp ON bp.countryFk = su.countryFk AND bp.taxAreaFk = ata.areaFk AND bp.taxClassFk = ts.taxClassFk - JOIN pgc ON pgc.code = bp.pgcFk + JOIN pgc ON pgc.code = bp.pgcFk JOIN taxClass tc ON tc.id = bp.taxClassFk GROUP BY tt.ticketFk, pgc.code HAVING taxableBase != 0; - INSERT INTO tmp.ticketTax (ticketFk, pgcFk, taxableBase, rate, code) - SELECT ts.ticketFk, ts.pgcFk, ts.taxableBase, ts.rate, ts.code - FROM tmp.ticketServiceTax ts - ON DUPLICATE KEY UPDATE ticketTax.taxableBase = ticketTax.taxableBase + VALUES (taxableBase); + INSERT INTO tmp.ticketTax (ticketFk, pgcFk, taxableBase, rate, code) + SELECT ts.ticketFk, ts.pgcFk, ts.taxableBase, ts.rate, ts.code + FROM tmp.ticketServiceTax ts + ON DUPLICATE KEY UPDATE ticketTax.taxableBase = VALUES (taxableBase) + ticketTax.taxableBase ; DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount; CREATE TEMPORARY TABLE tmp.ticketAmount (INDEX (ticketFk)) ENGINE = MEMORY - SELECT ticketFk, taxableBase, SUM(CAST(taxableBase * rate / 100 AS DECIMAL(10, 2))) tax,code + SELECT ticketFk, + taxableBase, + SUM(CAST(taxableBase * rate / 100 AS DECIMAL(10, 2))) tax, + code FROM tmp.ticketTax GROUP BY ticketFk, code; - DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; - DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea; + DROP TEMPORARY TABLE tmp.addressCompany; + DROP TEMPORARY TABLE tmp.addressTaxArea; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73034,6 +76924,120 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_getTax___` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_getTax___`(vTaxArea VARCHAR(25)) + READS SQL DATA +BEGIN +/** + * Calcula la base imponible, el IVA y el recargo de equivalencia para + * un conjunto de tickets. + * + * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular + * @return tmp.ticketAmount + * @return tmp.ticketTax Impuesto desglosado para cada ticket. + */ + DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; + CREATE TEMPORARY TABLE tmp.addressCompany + (INDEX (addressFk, companyFk)) + ENGINE = MEMORY + SELECT DISTINCT t.addressFk, t.companyFk + FROM tmp.ticket tmpTicket + JOIN ticket t ON t.id = tmpTicket.ticketFk; + + CALL addressTaxArea (); + + IF vTaxArea > '' THEN + UPDATE tmp.addressTaxArea + SET areaFk = vTaxArea; + END IF; + /* Solo se calcula la base imponible (taxableBase) y el impuesto se calculará posteriormente + * No se debería cambiar el sistema por problemas con los decimales + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax; + CREATE TEMPORARY TABLE tmp.ticketTax + (INDEX (ticketFk)) + ENGINE = MEMORY + SELECT * FROM ( + SELECT tmpTicket.ticketFk, + bp.pgcFk, + SUM(s.quantity * s.price * (100 - s.discount)/100 ) AS taxableBase, + pgc.rate, + tc.code, + bp.priority + FROM tmp.ticket tmpTicket + JOIN sale s ON s.ticketFk = tmpTicket.ticketFk + JOIN item i ON i.id = s.itemFk + JOIN ticket t ON t.id = tmpTicket.ticketFk + JOIN supplier su ON su.id = t.companyFk + JOIN tmp.addressTaxArea ata + ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk + JOIN itemTaxCountry itc + ON itc.itemFk = i.id AND itc.countryFk = su.countryFk + JOIN bookingPlanner bp + ON bp.countryFk = su.countryFk + AND bp.taxAreaFk = ata.areaFk + AND bp.taxClassFk = itc.taxClassFk + JOIN pgc ON pgc.code = bp.pgcFk + JOIN taxClass tc ON tc.id = bp.taxClassFk + GROUP BY tmpTicket.ticketFk, pgc.code,pgc.rate + HAVING taxableBase != 0) t + ORDER BY priority; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketServiceTax; + CREATE TEMPORARY TABLE tmp.ticketServiceTax + (PRIMARY KEY (ticketFk, rate,code)) + ENGINE = MEMORY + SELECT tt.ticketFk, + pgc.code pgcFk, + SUM(ts.quantity * ts.price) AS taxableBase, + pgc.rate, + tc.code + FROM tmp.ticket tt + JOIN ticketService ts ON ts.ticketFk = tt.ticketFk + JOIN ticket t ON t.id = tt.ticketFk + JOIN supplier su ON su.id = t.companyFk + JOIN tmp.addressTaxArea ata + ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk + JOIN bookingPlanner bp + ON bp.countryFk = su.countryFk + AND bp.taxAreaFk = ata.areaFk + AND bp.taxClassFk = ts.taxClassFk + JOIN pgc ON pgc.code = bp.pgcFk + JOIN taxClass tc ON tc.id = bp.taxClassFk + GROUP BY tt.ticketFk, pgc.code + HAVING taxableBase != 0; + + INSERT INTO tmp.ticketTax (ticketFk, pgcFk, taxableBase, rate, code) + SELECT ts.ticketFk, ts.pgcFk, ts.taxableBase, ts.rate, ts.code + FROM tmp.ticketServiceTax ts + ON DUPLICATE KEY UPDATE ticketTax.taxableBase = ticketTax.taxableBase + VALUES (taxableBase); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount; + CREATE TEMPORARY TABLE tmp.ticketAmount + (INDEX (ticketFk)) + ENGINE = MEMORY + SELECT ticketFk, taxableBase, SUM(CAST(taxableBase * rate / 100 AS DECIMAL(10, 2))) tax,code + FROM tmp.ticketTax + GROUP BY ticketFk, code; + + DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; + DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `ticket_insertZone` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -73470,6 +77474,57 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_setPreviousState` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_setPreviousState`(vTicketFk INT) +BEGIN + + DECLARE vControlFk INT; + + SELECT MAX(inter_id) INTO vControlFk + FROM vncontrol.inter + WHERE Id_Ticket = vTicketFk; + + IF (SELECT s.code + FROM vn.state s + JOIN vncontrol.inter i ON i.state_id = s.id + WHERE i.inter_id = vControlFk) + = 'PREVIOUS_PREPARATION' THEN + + SELECT inter_id + INTO vControlFk + FROM vncontrol.inter i + JOIN vn.state s ON i.state_id = s.id + WHERE Id_Ticket = vTicketFk + AND inter_id < vControlFk + AND s.code != 'PREVIOUS_PREPARATION' + ORDER BY inter_id DESC + LIMIT 1; + + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT s.nextStateFk, i.Id_Ticket, account.myUser_getId() + FROM vncontrol.inter i + JOIN vn.state s ON i.state_id = s.id + WHERE inter_id = vControlFk; + + END IF; + + SELECT TRUE AS IsUpdated; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `ticket_splitItemPackingType` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -74309,6 +78364,44 @@ proc: BEGIN */ CALL vn.workerTimeControl_check(vUserFk,vDated,vTabletFk); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `tpvTransaction_checkStatus` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `tpvTransaction_checkStatus`() +BEGIN +/** + * + * Envia mail con los cobros web no + * trasladados a la ficha del cliente. + * + */ + INSERT INTO mail (sender,replyTo,subject,body) + SELECT 'administracion@verdnatura.es', + 'noreply@verdnatura.es', + CONCAT('Cobro web no trasladado a la ficha del cliente ', t.clientFk), + CONCAT('Hay un importe de ', t.amount/100, '€ del cliente ', t.clientFk, ' con fecha ', t.created, + ', que no se ha trasladado a recibos. Si nos ha llegado el importe al banco confirme el pago en + + https://salix.verdnatura.es/#!/client/',t.clientFk,'/web-payment') + FROM hedera.tpvTransaction t + WHERE t.receiptFk IS NULL + AND t.status = 'ok' + AND t.created < DATE_ADD(NOW(),INTERVAL - 2 DAY) + GROUP BY t.clientFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -74319,9 +78412,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -74337,9 +78430,9 @@ BEGIN e.id Id_Entrada, e.REF Referencia, CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * - vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.carro / 1000000 ,1) AS DECIMAL(10,2)) AS CC, + vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) AS CC, CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * - vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.espai / 1000000,1) AS DECIMAL(10,2)) AS espais + vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) AS espais FROM vn.buy b JOIN vn.entry e ON e.id = b.entryFk JOIN vn.supplier s ON s.id = e.supplierFk @@ -74430,7 +78523,163 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `travel_cloneWithEntries`(IN vTravelFk INT, IN vDateStart DATE, IN vDateEnd DATE, +CREATE DEFINER=`root`@`%` PROCEDURE `travel_cloneWithEntries`( + IN vTravelFk INT, + IN vDateStart DATE, + IN vDateEnd DATE, + IN vWarehouseOutFk INT, + IN vWarehouseInFk INT, + IN vRef VARCHAR(255), + IN vAgencyModeFk INT, + OUT vNewTravelFk INT) +BEGIN +/** + * Clona un travel junto con sus entradas y compras + * + * @param vTravelFk travel plantilla a clonar + * @param vDateStart fecha del shipment del nuevo travel + * @param vDateEnd fecha del landing del nuevo travel + * @param vWarehouseOutFk fecha del salida del nuevo travel + * @param vWarehouseInFk warehouse de landing del nuevo travel + * @param vRef referencia del nuevo travel + * @param vAgencyModeFk del nuevo travel + * @param vNewTravelFk id del nuevo travel + */ + DECLARE vEntryNew INT; + DECLARE vDone BOOLEAN DEFAULT FALSE; + DECLARE vAuxEntryFk INT; + DECLARE vRsEntry CURSOR FOR + SELECT e.id + FROM entry e + JOIN travel t + ON t.id = e.travelFk + WHERE e.travelFk = vTravelFk; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION/*, 1062 Duplicate key*/ + BEGIN + ROLLBACK; + + END; + + START TRANSACTION; + INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk, agencyFk, `ref`, isDelivered, isReceived, m3, kg) + SELECT vDateStart, vDateEnd, vWarehouseInFk, vWarehouseOutFk, vAgencyModeFk, vRef, isDelivered, isReceived, m3, kg + FROM travel + WHERE id = vTravelFk; + + SET vNewTravelFk = LAST_INSERT_ID(); + CALL logAdd(vNewTravelFk, 'insert', 'travel', CONCAT('clona travel ',vTravelFk)); + SET vDone = FALSE; + SET @isModeInventory = TRUE; + OPEN vRsEntry ; + FETCH vRsEntry INTO vAuxEntryFk; + + WHILE NOT vDone DO + INSERT INTO entry ( + supplierFk, + ref, + isInventory, + isConfirmed, + isOrdered, + isRaid, + commission, + created, + evaNotes, + travelFk, + currencyFk, + companyFk, + gestDocFk, + invoiceInFk) + SELECT supplierFk, + ref, + isInventory, + isConfirmed, + isOrdered, + isRaid, + commission, + created, + evaNotes, + vNewTravelFk, + currencyFk, + companyFk, + gestDocFk, + invoiceInFk + FROM entry + WHERE id = vAuxEntryFk; + + SET vEntryNew = LAST_INSERT_ID(); + + CALL logAdd(vEntryNew, 'insert', 'entry', CONCAT('clona entrada ',vAuxEntryFk)); + INSERT INTO buy ( + entryFk, + itemFk, + quantity, + buyingValue, + packageFk, + stickers, + freightValue, + packageValue, + comissionValue, + packing, + `grouping`, + groupingMode, + location, + price1, + price2, + price3, + minPrice, + producer, + printedStickers, + isChecked, + weight) + SELECT vEntryNew, + itemFk, + quantity, + buyingValue, + packageFk, + stickers, + freightValue, + packageValue, + comissionValue, + packing, + `grouping`, + groupingMode, + location, + price1, + price2, + price3, + minPrice, + producer, + printedStickers, + isChecked, + weight + FROM buy + WHERE entryFk = vAuxEntryFk; + + FETCH vRsEntry INTO vAuxEntryFk; + END WHILE; + SET @isModeInventory = FALSE; + CLOSE vRsEntry; + COMMIT; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `travel_cloneWithEntries__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `travel_cloneWithEntries__`(IN vTravelFk INT, IN vDateStart DATE, IN vDateEnd DATE, IN vRef VARCHAR(255), OUT vNewTravelFk INT) BEGIN DECLARE vEntryNew INT; @@ -74654,6 +78903,82 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `travel_weeklyClone`(vSinceWeek INT, vToWeek INT) +BEGIN +/** + * Clona los travels plantilla para las semanas pasadas por parámetros + * + * @param vSinceWeek Numero de semanas en el futuro para empezar a clonar + * @param vToWeek Número de semenas en el futuro hasta donde clonar + */ + + DECLARE vCounter INT; + DECLARE vCurrentTravelFk INT; + DECLARE vShipped DATE; + DECLARE vLanded DATE; + DECLARE vWarehouseInFk INT; + DECLARE vWarehouseOutFk INT; + DECLARE vAgencyModeFk INT; + DECLARE vRef VARCHAR(255); + DECLARE vDone BOOLEAN DEFAULT FALSE; + DECLARE vRsTravel CURSOR FOR + SELECT travelFk, + @a := TIMESTAMPADD(DAY,vCounter * 7 - WEEKDAY(CURDATE()) - 1 + weekDay,CURDATE()), + @a := TIMESTAMPADD(DAY,duration,@a), + warehouseOutFk, + warehouseInFk, + `ref`, + agencyModeFk + FROM travel_cloneWeekly + WHERE travelFk; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + SET vCounter = vSinceWeek; + vWeekLoop :LOOP + INSERT IGNORE INTO travel (shipped, landed, warehouseOutFk, warehouseInFk, agencyFk, ref, cargoSupplierFk, kg) + SELECT @a := TIMESTAMPADD(DAY, vCounter * 7 - WEEKDAY(CURDATE()) - 1 + weekDay,CURDATE()), + @a := TIMESTAMPADD(DAY, duration, @a), + warehouseOutFk, + warehouseInFk, + agencyModeFk, + ref, + cargoSupplierFk, + kg + FROM travel_cloneWeekly + WHERE travelFk IS NULL; + OPEN vRsTravel; + FETCH vRsTravel INTO vCurrentTravelFk, vShipped, vLanded, vWarehouseOutFk, vWarehouseInFk, vRef, vAgencyModeFk; + SET vDone = FALSE; + WHILE NOT vDone DO + CALL travel_cloneWithEntries(vCurrentTravelFk, vShipped, vLanded, vWarehouseOutFk, vWarehouseInFk, vRef, vAgencyModeFk, @newTravel); + FETCH vRsTravel INTO vCurrentTravelFk, vShipped, vLanded, vWarehouseOutFk, vWarehouseInFk, vRef, vAgencyModeFk; + END WHILE; + CLOSE vRsTravel; + + IF vCounter = vToWeek THEN + LEAVE vWeekLoop; + END IF; + SET vCounter = vCounter + 1; + + END LOOP vWeekLoop; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `travel_weeklyClone__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `travel_weeklyClone__`(vSinceWeek INT, vToWeek INT) BEGIN DECLARE vCounter INT; @@ -74680,42 +79005,6 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `travel_weeklyClone__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `travel_weeklyClone__`(vSinceWeek INT, vToWeek INT) -BEGIN - DECLARE vCounter INT; - - SET vCounter = vSinceWeek; - vWeekLoop :LOOP - INSERT IGNORE INTO travel (shipped, landed, warehouseOutFk, warehouseInFk, agencyFk, ref, cargoSupplierFk) - SELECT @a := TIMESTAMPADD(DAY,vCounter * 7 - WEEKDAY(CURDATE()) - 1 + weekDay,CURDATE()), - @a := TIMESTAMPADD(DAY,duration,@a), - warehouseOutFk, - warehouseInFk, - agencyModeFk, - ref, - cargoSupplierFk - FROM travel_cloneWeekly; - IF vCounter = vToWeek THEN - LEAVE vWeekLoop; - END IF; - SET vCounter = vCounter + 1; - END LOOP; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `typeTagMake` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -74728,7 +79017,13 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `typeTagMake`(vTypeFk INT) BEGIN - +/* + * Plantilla para modificar reemplazar todos los tags + * por los valores que tienen los articulos + * + * @param vTypeFk tipo a modificar + * + */ DELETE it.* FROM itemTag it JOIN item i ON i.id = it.itemFk @@ -74797,6 +79092,34 @@ BEGIN UPDATE vn.item SET upToDown = 0 WHERE item.id = vItemFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `vehicleWarehouseTimeControl_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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `vehicleWarehouseTimeControl_getHistorical`(vNumberPLate VARCHAR(20), vWorkerFk INT) +BEGIN +/** + * Obtiene historial de la matrícula del trabajador, si es jefe de producción muestra el historial completo. +*/ + + SELECT timed,workerFk,IF (direction="out","Salida","Entrada") direction + FROM vn.vehicleWarehouseTimeControl vwt + JOIN vn.vehicleWarehouse vw ON vw.numberPlate=vNumberPLate + WHERE vwt.vehicleWarehouseFk =vw.id + AND vwt.workerFk = IF(account.userHasRole(account.user_getNameFromId(vWorkerFk), 'productionAssi'), vwt.workerFk, vWorkerFk); + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -74983,7 +79306,6 @@ DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `workerCreate`( vFirstname VARCHAR(50), vSurnames VARCHAR(50), - vFi VARCHAR(9), vWorkerCode CHAR(3), vBossFk INT, vUserFk INT @@ -74993,8 +79315,8 @@ BEGIN * Create new worker * */ - INSERT INTO worker(id, code, firstName, lastName, fi, userFk, bossFk) - VALUES (vUserFk, vWorkerCode, vFirstname, vSurnames, vFi, vUserFk, vBossFk); + INSERT INTO worker(id, code, firstName, lastName, userFk, bossFk) + VALUES (vUserFk, vWorkerCode, vFirstname, vSurnames, vUserFk, vBossFk); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75769,6 +80091,45 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerShelving_Add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerShelving_Add`(vWorkerFk INT, vBarcode VARCHAR(12)) +BEGIN +/* + * Inserta en workerShelving asociando los carros al trabajador + * @Param vWorkerFk es id del trabajador + * @Param vBarcode se puede pasar tanto el smarttag como el shelving + */ + DECLARE vIsShelvingFk BOOL; + + SELECT COUNT(*) > 0 INTO vIsShelvingFk + FROM vn.shelving s + WHERE s.code = vBarcode COLLATE utf8_general_ci; + + IF NOT vIsShelvingFk THEN + + SELECT st.shelvingFk INTO vBarcode + FROM vn.smartTag st + WHERE st.code = vBarcode COLLATE utf8_general_ci; + + END IF; + + INSERT INTO vn.workerShelving (workerFk, shelvingFk) + VALUES(vWorkerFk, vBarcode); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `workerTimeControlAdd` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -76095,7 +80456,7 @@ proc: BEGIN ) THEN SELECT "Dias con fichadas impares" AS problem; -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Dias con fichadas impares") INTO vBody; + 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; @@ -76116,7 +80477,7 @@ proc: BEGIN IF(LENGTH(vCalendarStateType)) THEN SELECT vCalendarStateType AS problem; -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Vacaciones") INTO vBody; + 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; @@ -76135,7 +80496,7 @@ proc: BEGIN ) = 0 THEN SELECT "No hay un contrato en vigor" AS problem; -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No hay un contrato en vigor") INTO vBody; + 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; @@ -76158,7 +80519,7 @@ proc: BEGIN IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA SELECT "Descansos 36 h" AS problem; -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Descansos 36 h") INTO vBody; + 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; @@ -76177,7 +80538,7 @@ proc: BEGIN IF vTimedWorked > vDayWorkMax THEN SELECT "Jornadas" AS problem; -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Jornadas") INTO vBody; + 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; @@ -76713,6 +81074,283 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControl_sendMail`(vWeek INT, vYear INT, vWorkerFk INT) BEGIN +/** + * Inserta en la tabla vn.mail para notificar a los empleados que teletrabajan de las jornadas que se han registrado. + * Inserta fichadas en el casos que se determina que el empleado está realizando teletrabajo + * + * @param vWeek + * @param vYear + * @param vWorkerFk -> En el caso de querer generarlo para todos los empleados deberá de informarse como NULL + */ + DECLARE vStarted VARCHAR(25); + DECLARE vEnded VARCHAR(25); + DECLARE vDone BOOL; + DECLARE vSender VARCHAR(255); + DECLARE vSenderOld VARCHAR(255); + DECLARE vDated DATE; + DECLARE vTimeWorkDecimal DECIMAL(5,2); + DECLARE vTimeWorkSexagesimal VARCHAR(5); + DECLARE vTimeWorkedDecimal DECIMAL(5,2); + DECLARE vTimeWorkedSexagesimal VARCHAR(5); + DECLARE vTimeWorkDecimalTotal DECIMAL(5,2); + DECLARE vTimeTable VARCHAR(100); + DECLARE vTimeTableDecimal DECIMAL(5,2); + DECLARE vWorkerFkOld INTEGER; + DECLARE vBusinessFk INTEGER; + DECLARE vHeader TEXT; + DECLARE vBody TEXT; + DECLARE vFooter TEXT; + DECLARE vReturn INTEGER; + DECLARE vAbsenceType VARCHAR(50); + DECLARE vWorkerInfo VARCHAR(90); + DECLARE vPermissionRate DECIMAL(5,2); + DECLARE vIsTeleworking BOOL; + DECLARE vIsTeleworkingOld BOOL; + + DECLARE vCursor CURSOR FOR + SELECT CONCAT(u.name, '@verdnatura.es'), u.id, tb.dated, tb.timeWorkDecimal, LEFT(tb.timeWorkSexagesimal,5) timeWorkSexagesimal, + tb.timeTable, tc.timeWorkDecimal timeWorkedDecimal, LEFT(tc.timeWorkSexagesimal,5) timeWorkedSexagesimal, tb.type, tb.businessFk,tb.permissionRate, d.isTeleworking + FROM tmp.timeBusinessCalculate tb + JOIN user u ON u.id = tb.userFk + JOIN department d ON d.id = tb.departmentFk + JOIN postgresql.business b ON b.business_id = tb.businessFk + JOIN company c ON c.id = b.provider_id + LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = tb.userFk AND tc.dated = tb.dated + JOIN (SELECT tb.userFk, + SUM(IF(tb.type IS NULL, + IF(tc.timeWorkDecimal > 0, FALSE, IF(tb.timeWorkDecimal > 0, TRUE, FALSE)), + TRUE))isTeleworkingWeek + FROM tmp.timeBusinessCalculate1 tb + LEFT JOIN tmp.timeControlCalculate1 tc ON tc.userFk = tb.userFk AND tc.dated = tb.dated + GROUP BY tb.userFk + HAVING isTeleworkingWeek > 0 + )sub ON sub.userFk = u.id + WHERE d.hasToRefill AND + IFNULL(vWorkerFk,u.id) = u.id AND + c.code = 'VNL' + ORDER BY u.id, tb.dated; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + DROP TABLE IF EXISTS tmp.timeControlCalculate; + DROP TABLE IF EXISTS tmp.timeBusinessCalculate; + DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate; + DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate; + DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate1; + DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate1; + + SELECT CONCAT (MIN(dated), ' 00:00:00'), CONCAT (MAX(dated), ' 23:59:59') INTO vStarted, vEnded + FROM time + WHERE year = vYear AND + week = vWeek; + + DELETE FROM workerTimeControl + WHERE IFNULL(vWorkerFk, userFk) = userFk AND + timed BETWEEN vStarted AND vEnded AND + isSendMail; + + UPDATE workerTimeControlMail + SET updated = NOW(), state = 'SENDED' + WHERE year = vYear AND + week = vWeek AND + IFNULL(vWorkerFk, workerFk) = workerFk ; + + IF vWorkerFk IS NULL THEN + CALL timeControl_calculateAll(vStarted,vEnded); + CALL timeBusiness_calculateAll(vStarted,vEnded); + ELSE + CALL timeControl_calculateByUser(vWorkerFk,vStarted,vEnded); + CALL timeBusiness_calculateByUser(vWorkerFk,vStarted,vEnded); + END IF; + + CREATE TEMPORARY TABLE tmp.timeControlCalculate1 + SELECT * FROM tmp.timeControlCalculate; + CREATE TEMPORARY TABLE tmp.timeBusinessCalculate1 + SELECT * FROM tmp.timeBusinessCalculate; + + SET vTimeWorkDecimalTotal = 0; + SET vBody= ''; + OPEN vCursor; + FETCH vCursor INTO vSender, vWorkerFk, vDated, vTimeWorkDecimal, vTimeWorkSexagesimal, vTimeTable, vTimeWorkedDecimal, vTimeWorkedSexagesimal, vAbsenceType, vBusinessFk, vPermissionRate, vIsTeleworking ; + SET vWorkerFkOld = vWorkerFk ; + SET vSenderOld = vSender; + SET vIsTeleworkingOld = vIsTeleworking; +proc: LOOP + IF vDone THEN + LEAVE proc; + END IF; + + IF vTimeWorkDecimal>0 AND vTimeWorkedDecimal IS NULL AND IFNULL(vPermissionRate, TRUE) THEN + IF vTimeTable IS NULL THEN + INSERT INTO workerTimeControl (userFk, timed, manual, direction, isSendMail) + SELECT vWorkerFk, CONCAT(vDated,' 08:00'), TRUE, 'in', TRUE; + IF vTimeWorkDecimal >= 5 THEN + INSERT INTO workerTimeControl (userFk, timed, manual, direction, isSendMail) + SELECT vWorkerFk, CONCAT(vDated,' 09:00'), TRUE, 'middle', TRUE; + INSERT INTO workerTimeControl (userFk, timed, manual, direction, isSendMail) + SELECT vWorkerFk, CONCAT(vDated,' 09:20'), TRUE, 'middle', TRUE; + END IF; + INSERT INTO workerTimeControl (userFk, timed, manual, direction, isSendMail) + SELECT vWorkerFk,CONCAT(vDated,' ', LEFT (SEC_TO_TIME(28800 + (vTimeWorkDecimal * 3600)), 5)), TRUE, 'out', TRUE; + ELSE + SELECT SUM(TIME_TO_SEC(j.end)-TIME_TO_SEC(j.start))/3600 INTO vTimeTableDecimal + FROM postgresql.journey j + WHERE j.business_id = vBusinessFk AND + j.day_id = WEEKDAY(vDated)+1; + IF vTimeWorkDecimal = vTimeTableDecimal THEN + INSERT INTO workerTimeControl (userFk, timed, manual, isSendMail) + SELECT vWorkerFk, CONCAT(vDated, ' ', j.start), TRUE, TRUE + FROM postgresql.journey j + WHERE j.business_id = vBusinessFk AND + j.day_id = WEEKDAY(vDated)+1; + + INSERT INTO workerTimeControl (userFk, timed, manual, isSendMail) + SELECT vWorkerFk, CONCAT(vDated, ' ', j.end), TRUE, TRUE + FROM postgresql.journey j + WHERE j.business_id = vBusinessFk AND + j.day_id = WEEKDAY(vDated)+1; + ELSE + INSERT INTO workerTimeControl (userFk, timed, manual, isSendMail) + SELECT vWorkerFk, CONCAT(vDated, ' ', MIN(j.start)), TRUE, TRUE + FROM postgresql.journey j + WHERE j.business_id = vBusinessFk AND + j.day_id = WEEKDAY(vDated)+1; + INSERT INTO workerTimeControl (userFk, timed, manual, isSendMail) + SELECT vWorkerFk, CONCAT(vDated, ' ', SEC_TO_TIME(TIME_TO_SEC(MIN(j.start)) + (vTimeWorkDecimal * 3600))), TRUE, TRUE + FROM postgresql.journey j + WHERE j.business_id = vBusinessFk AND + j.day_id = WEEKDAY(vDated)+1; + END IF; + + IF vTimeWorkDecimal >= 5 THEN + INSERT INTO workerTimeControl (userFk, timed, manual, isSendMail) + SELECT vWorkerFk, CONCAT(vDated, ' ', SEC_TO_TIME(TIME_TO_SEC(MIN(j.start)) + 3600)), TRUE, TRUE + FROM postgresql.journey j + WHERE j.business_id = vBusinessFk AND + j.day_id = WEEKDAY(vDated)+1; + INSERT INTO workerTimeControl (userFk, timed, manual, isSendMail) + SELECT vWorkerFk, CONCAT(vDated, ' ', SEC_TO_TIME(TIME_TO_SEC(MIN(j.start)) + 4800)), TRUE, TRUE + FROM postgresql.journey j + WHERE j.business_id = vBusinessFk AND + j.day_id = WEEKDAY(vDated)+1; + END IF; + + UPDATE workerTimeControl wtc + JOIN (SELECT id FROM workerTimeControl + WHERE userFk = vWorkerFk AND + timed BETWEEN vDated AND CONCAT(vDated, ' 23:59:59') + ORDER BY timed ASC + LIMIT 1)sub on sub.id= wtc.id + SET direction = 'in' ; + + UPDATE workerTimeControl wtc + JOIN (SELECT id FROM workerTimeControl + WHERE userFk = vWorkerFk AND + timed BETWEEN vDated AND CONCAT(vDated, ' 23:59:59') + ORDER BY timed DESC + LIMIT 1)sub on sub.id= wtc.id + SET direction = 'out' ; + + END IF; + END IF; + + SELECT CONCAT(IFNULL(vBody,""), " + ", DATE_FORMAT(vDated, "%d/%m/%Y"), " + ", CASE WEEKDAY(vDated)+1 + WHEN 1 THEN 'Lunes' + WHEN 2 THEN 'Martes' + WHEN 3 THEN 'Miércoles' + WHEN 4 THEN 'Jueves' + WHEN 5 THEN 'Viernes' + WHEN 6 THEN 'Sábado' + WHEN 7 THEN 'Domingo' + END , " + ", IFNULL(GROUP_CONCAT(MID(timed, 12, 5) ORDER BY timed ASC SEPARATOR ' - '), " - ")," + ", IFNULL(vAbsenceType, IF (vTimeWorkedDecimal>0, "Presencial", IF(vTimeWorkDecimal>0, "Teletrabajo", " - "))), " + ", IFNULL(vTimeWorkedSexagesimal,IF(IFNULL(vPermissionRate, TRUE), vTimeWorkDecimal, 0)), " + ") INTO vBody + FROM workerTimeControl + WHERE userFk = vWorkerFk AND + timed BETWEEN vDated AND CONCAT(vDated," 23:59:59"); + SET vTimeWorkDecimalTotal = vTimeWorkDecimalTotal + IFNULL(vTimeWorkedDecimal, IF( IFNULL(vPermissionRate, TRUE), vTimeWorkDecimal, 0)); + SET vDone = FALSE; + FETCH vCursor INTO vSender, vWorkerFk, vDated, vTimeWorkDecimal, vTimeWorkSexagesimal, vTimeTable, vTimeWorkedDecimal, vTimeWorkedSexagesimal, vAbsenceType, vBusinessFk, vPermissionRate, vIsTeleworking; + + IF vWorkerFk <> vWorkerFkOld OR vDone THEN + SELECT CONCAT( IFNULL(nif, ''), ' - ', firstName, ' ', name ) INTO vWorkerInfo + FROM postgresql.person + WHERE id_trabajador = vWorkerFkOld; + SET vHeader = CONCAT("


+
+

", vWorkerInfo , "

+ + + + + + + + + + + + "); + + SET vFooter = CONCAT(" + + + + +
+ Según la información recogida en el sistema adjuntamos la tabla con los registros de las horas trabajadas en el período indicado. + Si está conforme tiene que contestar indicando únicamente la palabra OK, en caso contrario puede contestar detallando la causa de la disconformidad. + Rogamos nos conteste lo antes posible. +

+
FechaDíaFichadasDescripciónHoras
TOTAL", IFNULL(LEFT (SEC_TO_TIME(vTimeWorkDecimalTotal * 3600), 5), 0), "
+
"); + + IF vIsTeleworkingOld THEN + INSERT INTO mail(sender, replyto, subject, body) + VALUES (vSenderOld, + 'timecontrol@verdnatura.es', + CONCAT('Registro de horas semana ', vWeek, ' año ', vYear) , + CONCAT(vHeader, ' ' , vBody, ' ', vFooter)); + + INSERT IGNORE INTO workerTimeControlMail (workerFk, year, week) + VALUES(vWorkerFkOld, vYear, vWeek); + END IF; + + SET vBody = ''; + SET vTimeWorkDecimalTotal = 0; + SET vWorkerFkOld = vWorkerFk; + SET vIsTeleworkingOld = vIsTeleworking; + SET vSenderOld = vSender; + END IF; + END LOOP; + CLOSE vCursor; + + DROP TABLE tmp.timeControlCalculate; + DROP TABLE tmp.timeBusinessCalculate; + DROP TABLE tmp.timeControlCalculate1; + DROP TABLE tmp.timeBusinessCalculate1; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_sendMail__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControl_sendMail__`(vWeek INT, vYear INT, vWorkerFk INT) +BEGIN /** * Inserta en la tabla vn.mail para notificar a los empleados que teletrabajan de las jornadas que se han registrado. * Inserta fichadas en el casos que se determina que el empleado está realizando teletrabajo @@ -76967,243 +81605,6 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_sendMail__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControl_sendMail__`(vWeek INT, vYear INT, vWorkerFk INT) -BEGIN -/** - * Inserta en la tabla vn.mail para notificar a los empleados que teletrabajan de las jornadas que se han registrado. - * Inserta fichadas en el casos que se determina que el empleado está realizando teletrabajo - * - * @param vWeek - * @param vYear - * @param vWorkerFk -> En el caso de querer generarlo para todos los empleados deberá de informarse como NULL - */ - DECLARE vStarted VARCHAR(25); - DECLARE vEnded VARCHAR(25); - DECLARE vDone BOOL; - DECLARE vSender VARCHAR(255); - DECLARE vSenderOld VARCHAR(255); - DECLARE vDated DATE; - DECLARE vTimeWorkDecimal DECIMAL(5,2); - DECLARE vTimeWorkSexagesimal VARCHAR(5); - DECLARE vTimeWorkedDecimal DECIMAL(5,2); - DECLARE vTimeWorkedSexagesimal VARCHAR(5); - DECLARE vTimeWorkDecimalTotal DECIMAL(5,2); - DECLARE vTimeTable VARCHAR(100); - DECLARE vTimeTableDecimal DECIMAL(5,2); - DECLARE vWorkerFkOld INTEGER; - DECLARE vBusinessFk INTEGER; - DECLARE vHeader TEXT; - DECLARE vBody TEXT; - DECLARE vFooter TEXT; - DECLARE vReturn INTEGER; - DECLARE vAbsenceType VARCHAR(50); - DECLARE vWorkerInfo VARCHAR(90); - - DECLARE vCursor CURSOR FOR - SELECT CONCAT(u.name, '@verdnatura.es'), u.id, tb.dated, tb.timeWorkDecimal, LEFT(tb.timeWorkSexagesimal,5) timeWorkSexagesimal, - tb.timeTable, tc.timeWorkDecimal timeWorkedDecimal, LEFT(tc.timeWorkSexagesimal,5) timeWorkedSexagesimal, tb.type, tb.businessFk - FROM tmp.timeBusinessCalculate tb - JOIN user u ON u.id = tb.userFk - JOIN department d ON d.id = tb.departmentFk - JOIN postgresql.business b ON b.business_id = tb.businessFk - JOIN company c ON c.id = b.provider_id - LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = tb.userFk AND tc.dated = tb.dated - WHERE d.isTeleworking AND - IFNULL(vWorkerFk,u.id) = u.id AND - c.code = 'VNL' - ORDER BY u.id, tb.dated; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - DROP TABLE IF EXISTS tmp.timeControlCalculate; - DROP TABLE IF EXISTS tmp.timeBusinessCalculate; - DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate; - DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate; - - SELECT CONCAT (MIN(dated), ' 00:00:00'), CONCAT (MAX(dated), ' 23:59:59') INTO vStarted, vEnded - FROM time - WHERE year = vYear AND - week = vWeek; - - DELETE FROM workerTimeControl - WHERE IFNULL(vWorkerFk, userFk) = userFk AND - timed BETWEEN vStarted AND vEnded AND isSendMail; - - UPDATE workerTimeControlMail - SET updated = NOW(), state = 'SENDED' - WHERE year = vYear AND - week = vWeek AND - IFNULL(vWorkerFk, workerFk) = workerFk ; - - IF vWorkerFk IS NULL THEN - CALL timeControl_calculateAll(vStarted,vEnded); - CALL timeBusiness_calculateAll(vStarted,vEnded); - ELSE - CALL timeControl_calculateByUser(vWorkerFk,vStarted,vEnded); - CALL timeBusiness_calculateByUser(vWorkerFk,vStarted,vEnded); - END IF; - - SET vTimeWorkDecimalTotal = 0; - SET vBody= ''; - OPEN vCursor; - FETCH vCursor INTO vSender, vWorkerFk, vDated, vTimeWorkDecimal, vTimeWorkSexagesimal, vTimeTable, vTimeWorkedDecimal, vTimeWorkedSexagesimal, vAbsenceType, vBusinessFk ; - SET vWorkerFkOld = vWorkerFk ; - SET vSenderOld = vSender; - proc: LOOP - IF vDone THEN - LEAVE proc; - END IF; - - IF vTimeTable IS NULL AND vTimeWorkDecimal>0 AND vTimeWorkedDecimal IS NULL THEN - INSERT INTO workerTimeControl (userFk, timed, manual, direction, isSendMail) - SELECT vWorkerFk, CONCAT(vDated,' 08:00'), TRUE, 'in', TRUE; - IF vTimeWorkDecimal >= 5 THEN - INSERT INTO workerTimeControl (userFk, timed, manual, direction, isSendMail) - SELECT vWorkerFk, CONCAT(vDated,' 09:00'), TRUE, 'middle', TRUE; - INSERT INTO workerTimeControl (userFk, timed, manual, direction, isSendMail) - SELECT vWorkerFk, CONCAT(vDated,' 09:20'), TRUE, 'middle', TRUE; - END IF; - INSERT INTO workerTimeControl (userFk, timed, manual, direction, isSendMail) - SELECT vWorkerFk,CONCAT(vDated,' ', LEFT (SEC_TO_TIME(28800 + (vTimeWorkDecimal * 3600)), 5)), TRUE, 'out', TRUE; - ELSEIF vTimeWorkDecimal>0 AND vTimeWorkedDecimal IS NULL THEN - SELECT SUM(TIME_TO_SEC(j.end)-TIME_TO_SEC(j.start))/3600 INTO vTimeTableDecimal - FROM postgresql.journey j - WHERE j.business_id = vBusinessFk AND j.day_id = WEEKDAY(vDated)+1; - IF vTimeWorkDecimal = vTimeTableDecimal THEN - INSERT INTO workerTimeControl (userFk, timed, manual, isSendMail) - SELECT vWorkerFk, CONCAT(vDated, ' ', j.start), TRUE, TRUE - FROM postgresql.journey j - WHERE j.business_id = vBusinessFk AND j.day_id = WEEKDAY(vDated)+1; - - INSERT INTO workerTimeControl (userFk, timed, manual, isSendMail) - SELECT vWorkerFk, CONCAT(vDated, ' ', j.end), TRUE, TRUE - FROM postgresql.journey j - WHERE j.business_id = vBusinessFk AND j.day_id = WEEKDAY(vDated)+1; - ELSE - INSERT INTO workerTimeControl (userFk, timed, manual, isSendMail) - SELECT vWorkerFk, CONCAT(vDated, ' ', MIN(j.start)), TRUE, TRUE - FROM postgresql.journey j - WHERE j.business_id = vBusinessFk AND j.day_id = WEEKDAY(vDated)+1; - INSERT INTO workerTimeControl (userFk, timed, manual, isSendMail) - SELECT vWorkerFk, CONCAT(vDated, ' ', SEC_TO_TIME(TIME_TO_SEC(MIN(j.start)) + (vTimeWorkDecimal * 3600))), TRUE, TRUE - FROM postgresql.journey j - WHERE j.business_id = vBusinessFk AND j.day_id = WEEKDAY(vDated)+1; - END IF; - - IF vTimeWorkDecimal >= 5 THEN - INSERT INTO workerTimeControl (userFk, timed, manual, isSendMail) - SELECT vWorkerFk, CONCAT(vDated, ' ', SEC_TO_TIME(TIME_TO_SEC(MIN(j.start)) + 3600)), TRUE, TRUE - FROM postgresql.journey j - WHERE j.business_id = vBusinessFk AND j.day_id = WEEKDAY(vDated)+1; - INSERT INTO workerTimeControl (userFk, timed, manual, isSendMail) - SELECT vWorkerFk, CONCAT(vDated, ' ', SEC_TO_TIME(TIME_TO_SEC(MIN(j.start)) + 4800)), TRUE, TRUE - FROM postgresql.journey j - WHERE j.business_id = vBusinessFk AND j.day_id = WEEKDAY(vDated)+1; - END IF; - - UPDATE workerTimeControl wtc - JOIN (SELECT id FROM workerTimeControl - WHERE userFk = vWorkerFk AND - timed BETWEEN vDated AND CONCAT(vDated, ' 23:59:59') - ORDER BY timed ASC - LIMIT 1)sub on sub.id= wtc.id - SET direction = 'in' ; - - UPDATE workerTimeControl wtc - JOIN (SELECT id FROM workerTimeControl - WHERE userFk = vWorkerFk AND - timed BETWEEN vDated AND CONCAT(vDated, ' 23:59:59') - ORDER BY timed DESC - LIMIT 1)sub on sub.id= wtc.id - SET direction = 'out' ; - - END IF; - - SELECT CONCAT(IFNULL(vBody,""), " - ", DATE_FORMAT(vDated, "%d/%m/%Y"), " - ", CASE WEEKDAY(vDated)+1 - WHEN 1 THEN 'Lunes' - WHEN 2 THEN 'Martes' - WHEN 3 THEN 'Miércoles' - WHEN 4 THEN 'Jueves' - WHEN 5 THEN 'Viernes' - WHEN 6 THEN 'Sábado' - WHEN 7 THEN 'Domingo' - END , " - ", IFNULL(GROUP_CONCAT(MID(timed,12,5) ORDER BY timed ASC SEPARATOR ' - '), " - ")," - ", IFNULL(vAbsenceType, IF (vTimeWorkedDecimal>0, "Presencial", IF(vTimeWorkDecimal>0,"Teletrabajo", " - "))), " - ", IFNULL(vTimeWorkedSexagesimal, vTimeWorkSexagesimal) , " - ") INTO vBody - FROM workerTimeControl - WHERE userFk = vWorkerFk AND - timed BETWEEN vDated AND CONCAT(vDated," 23:59:59"); - SET vTimeWorkDecimalTotal = vTimeWorkDecimalTotal + IFNULL(vTimeWorkedDecimal, vTimeWorkDecimal); - SET vDone = FALSE; - FETCH vCursor INTO vSender, vWorkerFk, vDated, vTimeWorkDecimal, vTimeWorkSexagesimal, vTimeTable, vTimeWorkedDecimal, vTimeWorkedSexagesimal, vAbsenceType, vBusinessFk ; - - IF vWorkerFk <> vWorkerFkOld OR vDone THEN - SELECT CONCAT( IFNULL(nif, ''), ' - ', firstName, ' ', name ) INTO vWorkerInfo - FROM postgresql.person - WHERE id_trabajador = vWorkerFkOld; - SET vHeader = CONCAT("


-
-

", vWorkerInfo , "

- - - - - - - - - - - - "); - - SET vFooter = CONCAT(" - - - - -
- Según la información recogida en el sistema adjuntamos la tabla con los registros de las horas trabajadas en el período indicado. - Si está conforme tiene que contestar indicando únicamente la palabra OK, en caso contrario puede contestar detallando la causa de la disconformidad. - Rogamos nos conteste lo antes posible. -

-
FechaDíaFichadasDescripciónHoras
TOTAL", IFNULL(LEFT (SEC_TO_TIME(vTimeWorkDecimalTotal * 3600), 5), 0), "
-
"); - INSERT INTO mail(sender, replyto, subject, body) - VALUES (vSenderOld, 'timecontrol@verdnatura.es', CONCAT('Registro de horas semana ', vWeek, ' año ', vYear) , CONCAT(vHeader,' ' , vBody,' ', vFooter)); - - INSERT IGNORE INTO workerTimeControlMail (workerFk, year,week) - VALUES(vWorkerFkOld, vYear, vWeek); - SET vBody = ''; - SET vTimeWorkDecimalTotal = 0; - SET vWorkerFkOld = vWorkerFk ; - SET vSenderOld = vSender; - END IF; - END LOOP; - CLOSE vCursor; - - DROP TABLE IF EXISTS tmp.timeControlCalculate; - DROP TABLE IF EXISTS tmp.timeBusinessCalculate; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_sendMail____` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -78054,7 +82455,7 @@ BEGIN r.kmEnd-r.kmStart km, r.m3 m3Delivery, CAST(r.m3/loadWorker AS DECIMAL(10,2)) m3Load, - CAST(rc.m3Distribution*m3 AS DECIMAL(10,2)) amountDelivery, + CAST(rc.m3Distribution*r.m3 AS DECIMAL(10,2)) amountDelivery, CASE loadWorker WHEN 1 THEN CAST(r.m3/ loadWorker*rc.load1m3 AS DECIMAL(10,2)) WHEN 2 THEN CAST(r.m3/ loadWorker*rc.load2m3 AS DECIMAL(10,2)) @@ -78063,12 +82464,13 @@ BEGIN WHEN 5 THEN CAST(r.m3/ loadWorker*rc.load5m3 AS DECIMAL(10,2)) ELSE CAST(r.m3/ loadWorker*rc.load6m3 AS DECIMAL(10,2)) END amountLoad, - rc.kmRate*(r.kmEnd-r.kmStart) amountKm, + IF(v.isKmTruckRate, rc.kmTruckRate, rc.kmRate)*(r.kmEnd-r.kmStart) amountKm, CAST('' AS CHAR(45)) description, CAST( 0 AS DECIMAL(10,2)) extra, - CAST( 0 AS DECIMAL(10,2)) maxSalary - FROM ticket t - LEFT JOIN route r ON t.routeFk = r.id + CAST( 0 AS DECIMAL(10,2)) maxSalary + FROM route r + LEFT JOIN ticket t ON t.routeFk = r.id + LEFT JOIN vehicle v ON v.id = r.vehicleFk LEFT JOIN worker w ON w.id = r.workerFk LEFT JOIN routeConfig rc ON TRUE LEFT JOIN (SELECT rw.routeFk, COUNT(rw.workerFk) loadWorker @@ -78138,6 +82540,8 @@ BEGIN THEN CAST(((12 * blp.importepactado) / (52 * tb.hoursWeek)) * 4 AS DECIMAL(10,2)) WHEN tb.type = 'Vacaciones' OR tb.type = 'Baja enfermedad común' OR tb.type = 'Permiso retribuido' OR tb.type = 'Festivo' THEN CAST(((12 * blp.importepactado) / (52 * tb.hoursWeek)) * 8 AS DECIMAL(10,2)) + WHEN tb.type = 'Maternidad/Paternidad' + THEN 0 END FROM worker w JOIN tmp.timeBusinessCalculate tb ON tb.userFk = w.id @@ -78145,7 +82549,7 @@ BEGIN JOIN time tm ON tm.dated = tb.dated WHERE tb.dated BETWEEN vDateFrom AND vDateTo AND w.id = vWorkerFk AND - tb.type IN ('Vacaciones 1/2 día', 'Vacaciones', 'Baja enfermedad común','Festivo','Permiso retribuido 1/2 día','Permiso retribuido') + tb.type IN ('Vacaciones 1/2 día', 'Vacaciones', 'Baja enfermedad común','Festivo','Permiso retribuido 1/2 día','Permiso retribuido', 'Maternidad/Paternidad') GROUP BY tb.dated; INSERT INTO tmp.workerSalaryRoleDelivery (workerFk, @@ -78230,12 +82634,12 @@ BEGIN CREATE TEMPORARY TABLE tmp.daysToDelete SELECT dated FROM tmp.workerSalaryRoleDelivery d - WHERE d.description IN ('Baja enfermedad común'); + WHERE d.description IN ('Baja enfermedad común', 'Maternidad/Paternidad'); DELETE d FROM tmp.workerSalaryRoleDelivery d JOIN tmp.daysToDelete dd on dd.dated = d.dated - WHERE d.description NOT IN ('Baja enfermedad común'); + WHERE d.description NOT IN ('Baja enfermedad común', 'Maternidad/Paternidad'); INSERT INTO tmp.workerSalaryRoleDelivery (workerFk,dated,id,packages,hours,km,m3Delivery,m3Load,amountDelivery,amountLoad,AmountKm,description, extra) SELECT workerFk, @@ -78258,7 +82662,7 @@ BEGIN dated, description, extra, - maxSalary) + maxSalary) SELECT wdc.workerFk , CONCAT(YEAR(t.dated),'-', MONTH(t.dated),'-01') , CASE @@ -78273,7 +82677,7 @@ BEGIN WHEN wdc.category = 2 THEN CAST(rc.plusCategory2 AS DECIMAL (10,2)) END, - CASE + CASE WHEN wdc.category = 1 THEN CAST(rc.maxSalaryCategory1 AS DECIMAL (10,2)) WHEN wdc.category = 2 @@ -78543,6 +82947,280 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `worker_calculateSalaryRoleDelivery___` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `worker_calculateSalaryRoleDelivery___`(vWorkerFk INTEGER,vDateFrom DATE,vDateTo DATE) +BEGIN +/** + * Calcula el salario de trabajadores para los departamentos de reparto, paletizado + * + * @param vDateFrom + * @param vDateTo + * @param vWorkerFk + * @return tmp.workerSalaryRoleDelivery + */ + DROP TEMPORARY TABLE IF EXISTS tmp.workerSalaryRoleDelivery; + + CREATE TEMPORARY TABLE tmp.workerSalaryRoleDelivery + SELECT w.id workerFk, + r.created dated, + r.id, + SUM(t.packages) packages, + CAST(time_to_sec(TIMEDIFF( DATE_FORMAT(r.finished, '%H:%i:%s'),DATE_FORMAT(r.time, '%H:%i:%s'))) / (60 * 60) AS DECIMAL(10, 1)) hours , + r.kmEnd-r.kmStart km, + r.m3 m3Delivery, + CAST(r.m3/loadWorker AS DECIMAL(10,2)) m3Load, + CAST(rc.m3Distribution*m3 AS DECIMAL(10,2)) amountDelivery, + CASE loadWorker + WHEN 1 THEN CAST(r.m3/ loadWorker*rc.load1m3 AS DECIMAL(10,2)) + WHEN 2 THEN CAST(r.m3/ loadWorker*rc.load2m3 AS DECIMAL(10,2)) + WHEN 3 THEN CAST(r.m3/ loadWorker*rc.load3m3 AS DECIMAL(10,2)) + WHEN 4 THEN CAST(r.m3/ loadWorker*rc.load4m3 AS DECIMAL(10,2)) + WHEN 5 THEN CAST(r.m3/ loadWorker*rc.load5m3 AS DECIMAL(10,2)) + ELSE CAST(r.m3/ loadWorker*rc.load6m3 AS DECIMAL(10,2)) + END amountLoad, + rc.kmRate*(r.kmEnd-r.kmStart) amountKm, + CAST('' AS CHAR(45)) description, + CAST( 0 AS DECIMAL(10,2)) extra, + CAST( 0 AS DECIMAL(10,2)) maxSalary + FROM ticket t + LEFT JOIN route r ON t.routeFk = r.id + LEFT JOIN worker w ON w.id = r.workerFk + LEFT JOIN routeConfig rc ON TRUE + LEFT JOIN (SELECT rw.routeFk, COUNT(rw.workerFk) loadWorker + FROM routeLoadWorker rw + JOIN routeLoadWorker rw2 ON rw.routeFk = rw2.routeFk AND rw2.workerFk = vWorkerFk + GROUP BY rw2.routeFk + ) sub ON sub.routeFk=r.id + WHERE r.created BETWEEN vDateFrom AND vDateTo AND w.id = vWorkerFk + GROUP BY r.id; + + INSERT INTO tmp.workerSalaryRoleDelivery (workerFk, + dated, + id, + packages, + km, + m3Load, + amountLoad) + SELECT w.id , + r.created , + r.id, + SUM(t.packages) , + r.kmEnd-r.kmStart , + CAST(r.m3/loadWorker AS DECIMAL(10,2)) , + CASE loadWorker + WHEN 1 THEN CAST(r.m3/ loadWorker*rc.load1m3 AS DECIMAL(10,2)) + WHEN 2 THEN CAST(r.m3/ loadWorker*rc.load2m3 AS DECIMAL(10,2)) + WHEN 3 THEN CAST(r.m3/ loadWorker*rc.load3m3 AS DECIMAL(10,2)) + WHEN 4 THEN CAST(r.m3/ loadWorker*rc.load4m3 AS DECIMAL(10,2)) + WHEN 5 THEN CAST(r.m3/ loadWorker*rc.load5m3 AS DECIMAL(10,2)) + ELSE CAST(r.m3/ loadWorker*rc.load6m3 AS DECIMAL(10,2)) + END + FROM (SELECT rw.routeFk, COUNT(rw.workerFk) loadWorker + FROM routeLoadWorker rw + JOIN routeLoadWorker rw2 ON rw.routeFk = rw2.routeFk AND rw2.workerFk = vWorkerFk + GROUP BY rw2.routeFk) sub + LEFT JOIN route r ON sub.routeFk = r.id + LEFT JOIN ticket t ON t.routeFk = r.id + LEFT JOIN worker w ON w.id = r.workerFk + LEFT JOIN routeConfig rc ON TRUE + WHERE r.created BETWEEN vDateFrom AND vDateTo AND w.id <> vWorkerFk + GROUP BY r.id; + + INSERT INTO tmp.workerSalaryRoleDelivery(workerFk, + dated, + description, + extra) + SELECT workerFk, + dated, + GROUP_CONCAT(ra.name) , + CAST(SUM(rc.price) AS DECIMAL(9,2)) + FROM routeComplement rc + JOIN routeAction ra ON rc.routeActionFk=ra.id + WHERE dated BETWEEN vDateFrom AND vDateTo AND workerFk=vWorkerFk + GROUP BY dated; + + CALL timeBusiness_calculateByWorker(vWorkerFk, vDateFrom, vDateTo); + + INSERT INTO tmp.workerSalaryRoleDelivery (workerFk, + dated, + description, + extra) + SELECT w.id, + tb.dated, + tb.type COLLATE utf8_general_ci, + CASE + WHEN tb.type = 'Vacaciones 1/2 día' OR tb.type = 'Permiso retribuido 1/2 día' + THEN CAST(((12 * blp.importepactado) / (52 * tb.hoursWeek)) * 4 AS DECIMAL(10,2)) + WHEN tb.type = 'Vacaciones' OR tb.type = 'Baja enfermedad común' OR tb.type = 'Permiso retribuido' OR tb.type = 'Festivo' + THEN CAST(((12 * blp.importepactado) / (52 * tb.hoursWeek)) * 8 AS DECIMAL(10,2)) + WHEN tb.type = 'Maternidad/Paternidad' + THEN 0 + END + FROM worker w + JOIN tmp.timeBusinessCalculate tb ON tb.userFk = w.id + JOIN postgresql.business_labour_payroll blp ON blp.business_id = tb.businessFk + JOIN time tm ON tm.dated = tb.dated + WHERE tb.dated BETWEEN vDateFrom AND vDateTo AND + w.id = vWorkerFk AND + tb.type IN ('Vacaciones 1/2 día', 'Vacaciones', 'Baja enfermedad común','Festivo','Permiso retribuido 1/2 día','Permiso retribuido', 'Maternidad/Paternidad') + GROUP BY tb.dated; + + INSERT INTO tmp.workerSalaryRoleDelivery (workerFk, + dated, + m3Delivery, + amountLoad, + description) + SELECT wdc.workerFk , + r.created, + SUM(r.m3) , + CASE + WHEN wdc.category = 1 + THEN CAST(SUM(r.m3) * rc.distributionM3Category1 AS DECIMAL (10,2)) + WHEN wdc.category = 2 + THEN CAST(SUM(r.m3) * rc.distributionM3Category2 AS DECIMAL (10,2)) + END amountLoad, + 'Gestión de la distribución' description + FROM route r + JOIN agencyMode am ON am.id= r.agencyModeFk + JOIN agency a ON a.id = am.agencyFk + JOIN workerDistributionCategory wdc ON wdc.workerFk = vWorkerFk + JOIN workerLabour wl ON r.created BETWEEN wl.started AND IFNULL(wl.ended, CURDATE()) AND wl.workerFk = wdc.workerFk AND a.workCenterFk = wl.workCenterFk + JOIN department v ON v.id = departmentFk + JOIN routeConfig rc + WHERE r.m3>0 AND created BETWEEN vDateFrom AND vDateTo AND + am.name NOT LIKE "REC_%" AND + v.name= "REPARTO" + GROUP BY r.created; + + INSERT INTO tmp.workerSalaryRoleDelivery (workerFk, + dated, + m3Delivery, + amountLoad, + description) + SELECT sub.workerFk, + r.created, + SUM(r.m3), + CAST( (SUM(r.m3)*sub.percentage /100) * rc.m3Palletization AS DECIMAL (10,2) ), + 'Gestión de paletizado' + FROM route r + JOIN agencyMode am ON am.id= r.agencyModeFk + JOIN agency a ON a.id = am.agencyFk + JOIN (SELECT percentage,workerFk ,dated + FROM routeUserPercentage ru + WHERE workerFk = vWorkerFk AND ru.dated <= vDateTo + ORDER BY dated DESC LIMIT 1 + ) sub + JOIN routeConfig rc + JOIN workerLabour wl ON r.created BETWEEN wl.started AND IFNULL(wl.ended, CURDATE()) AND + wl.workerFk = sub.workerFk + JOIN department v ON v.id = departmentFk + WHERE r.m3>0 AND + r.created BETWEEN vDateFrom AND vDateTo AND + am.name NOT LIKE "REC_%" AND + v.name= "PALETIZADO" + GROUP BY r.created; + + DROP TEMPORARY TABLE IF EXISTS tmp.daysToRateHoliday; + CREATE TEMPORARY TABLE tmp.daysToRateHoliday + SELECT * + FROM tmp.workerSalaryRoleDelivery tb + WHERE (tb.description IN ('Festivo') OR dayofweek(tb.dated)=1) AND tb.extra = 0 ; + + INSERT INTO tmp.workerSalaryRoleDelivery (workerFk,dated,id,packages,hours,km,m3Delivery,m3Load,amountDelivery,amountLoad,AmountKm,description, extra) + SELECT workerFk, + dated, + d.id, + packages, + hours, + km, + m3Delivery, + m3Load, + amountDelivery * r.rateHoliday, + amountLoad * r.rateHoliday, + AmountKm * r.rateHoliday, + CONCAT('Plus festivo: ',description), + extra + FROM tmp.daysToRateHoliday d + LEFT JOIN routeConfig r ON TRUE; + + DROP TEMPORARY TABLE IF EXISTS tmp.daysToDelete; + CREATE TEMPORARY TABLE tmp.daysToDelete + SELECT dated + FROM tmp.workerSalaryRoleDelivery d + WHERE d.description IN ('Baja enfermedad común', 'Maternidad/Paternidad'); + + DELETE d + FROM tmp.workerSalaryRoleDelivery d + JOIN tmp.daysToDelete dd on dd.dated = d.dated + WHERE d.description NOT IN ('Baja enfermedad común', 'Maternidad/Paternidad'); + + INSERT INTO tmp.workerSalaryRoleDelivery (workerFk,dated,id,packages,hours,km,m3Delivery,m3Load,amountDelivery,amountLoad,AmountKm,description, extra) + SELECT workerFk, + dated, + d.id, + packages, + hours, + km, + m3Delivery, + m3Load, + amountDelivery * r.rateHoliday, + amountLoad * r.rateHoliday, + AmountKm * r.rateHoliday, + CONCAT('Plus festivo: ', description), + extra + FROM tmp.daysToRateHoliday d + LEFT JOIN routeConfig r ON TRUE; + + INSERT INTO tmp.workerSalaryRoleDelivery (workerFk, + dated, + description, + extra, + maxSalary) + SELECT wdc.workerFk , + CONCAT(YEAR(t.dated),'-', MONTH(t.dated),'-01') , + CASE + WHEN wdc.category = 1 + THEN rc.plusCategory1Concept + WHEN wdc.category = 2 + THEN rc.plusCategory2Concept + END, + CASE + WHEN wdc.category = 1 + THEN CAST(rc.plusCategory1 AS DECIMAL (10,2)) + WHEN wdc.category = 2 + THEN CAST(rc.plusCategory2 AS DECIMAL (10,2)) + END, + CASE + WHEN wdc.category = 1 + THEN CAST(rc.maxSalaryCategory1 AS DECIMAL (10,2)) + WHEN wdc.category = 2 + THEN CAST(rc.maxSalaryCategory2 AS DECIMAL (10,2)) + END + FROM worker w + JOIN workerDistributionCategory wdc ON wdc.workerFk = w.id + JOIN routeConfig rc + JOIN time t on t.dated BETWEEN vDateFrom AND vDateTo + WHERE w.id = vWorkerFk + GROUP BY MONTH(t.dated), YEAR(t.dated); + + DROP TEMPORARY TABLE tmp.daysToRateHoliday; + DROP TEMPORARY TABLE tmp.daysToDelete; + DROP TEMPORARY TABLE tmp.timeBusinessCalculate; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `worker_getHierarchy` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -78657,48 +83335,75 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `worker_getProductionErrors` */; +/*!50003 DROP PROCEDURE IF EXISTS `worker_getProductionerrors` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `worker_getProductionErrors`(vDepartment VARCHAR(25), vStateCode VARCHAR(25) CHARSET utf8, vDatedFrom DATETIME, vDatedTo DATETIME) +CREATE DEFINER=`root`@`%` PROCEDURE `worker_getProductionerrors`(vAction VARCHAR(25), vDepartment VARCHAR(25), vStateCode VARCHAR(25) CHARSET utf8, vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN - + DROP TEMPORARY TABLE IF EXISTS tmp.total; - - CREATE TEMPORARY TABLE tmp.total - ENGINE = MEMORY - SELECT st.workerFk, Count(t.id) AS CuentaDeId_Ticket - FROM state ss - JOIN vn.saleTracking st ON st.stateFk = ss.id - JOIN vn.sale s ON s.id = st.saleFk - JOIN ticket t ON s.ticketFk = t.id - JOIN worker w ON st.workerFk = w.id - WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo AND ss.code = vStateCode - GROUP BY st.workerFk; - - SELECT w.code, w.firstName, w.lastName, CAST(tmp.total.CuentaDeId_Ticket AS DECIMAL(10,0)) AS Totaltickets, CAST(sub.CuentaDeTicketFk AS DECIMAL(10,0)) AS Fallos - FROM tmp.total - JOIN worker w ON w.id = tmp.total.workerFk - LEFT JOIN ( - SELECT COUNT(c.ticketFk) AS CuentaDeTicketFk, cd.workerFk - FROM claimDevelopment cd - JOIN claim c ON cd.claimFk = c.id - JOIN ticket t ON c.ticketFk = t.id - JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id - WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo AND cr.description=vDepartment - GROUP BY cd.workerFk - )sub ON tmp.total.workerFk = sub.workerFk; - - DROP TEMPORARY TABLE tmp.total; - - END ;; + + IF (vDepartment = 'Encajadores') + THEN + CREATE TEMPORARY TABLE tmp.total + ENGINE = MEMORY + SELECT e.workerFk, Count(DISTINCT t.id) AS ticketCount + FROM expedition e + JOIN ticket t ON e.ticketFk = t.id + WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo + GROUP BY e.workerFk; + ELSE + CREATE TEMPORARY TABLE tmp.total + ENGINE = MEMORY + SELECT st.workerFk, Count(DISTINCT t.id) AS ticketCount + FROM state ss + JOIN vn.saleTracking st ON st.stateFk = ss.id + JOIN vn.sale s ON s.id = st.saleFk + JOIN ticket t ON s.ticketFk = t.id + WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo) AND ss.code = vStateCode + GROUP BY st.workerFk; + END IF; + + SELECT sub1.id, sub1.firstName, sub1.lastName, CAST(sub1.totalTickets AS DECIMAL(10,0)) AS totalTickets, CAST(IFNULL(sub1.errors,0) + IFNULL(sub2.errors,0) AS DECIMAL(10,0)) AS errors + FROM( + SELECT w.id, w.code, w.firstName, w.lastName, t.ticketCount AS totalTickets, sub.errors + FROM tmp.total AS t + JOIN worker w ON w.id = t.workerFk + LEFT JOIN ( + SELECT COUNT(c.ticketFk) AS errors, cd.workerFk + FROM claimDevelopment cd + JOIN claim c ON cd.claimFk = c.id + JOIN ticket t ON c.ticketFk = t.id + JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id + WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo AND cr.description = vDepartment + GROUP BY cd.workerFk + )sub ON t.workerFk = sub.workerFk + GROUP BY w.code) sub1 + LEFT JOIN( + SELECT sub1.workerFk, COUNT(id) AS errors + FROM ( + SELECT st.workerFk, t.id + FROM vn.saleMistake sm + JOIN vn.saleTracking st ON sm.saleFk = st.saleFk + JOIN state ss ON ss.id = st.stateFk + JOIN vncontrol.accion a ON a.accion_id = st.actionFk + JOIN vn.sale s ON s.id = sm.saleFk + JOIN vn.ticket t on t.id = s.ticketFk + WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo) AND a.accion = vAction AND ss.code = vStateCode + GROUP BY s.ticketFk + ) sub1 + GROUP BY sub1.workerFk) sub2 ON sub2.workerFk = sub1.id; + + DROP TEMPORARY TABLE tmp.total; + +END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; /*!50003 SET character_set_client = @saved_cs_client */ ; @@ -78717,38 +83422,51 @@ DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `worker_getProductionErrors__`(vDepartment VARCHAR(25), vStateCode VARCHAR(25) CHARSET utf8, vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN -DROP TEMPORARY TABLE IF EXISTS tmp.total; - CREATE TEMPORARY TABLE tmp.total - ENGINE = MEMORY - SELECT tt.workerFk, Count(tt.ticketFk) AS CuentaDeId_Ticket - FROM state s - INNER JOIN ticketTracking tt ON s.id = tt.stateFk - INNER JOIN ticket t ON tt.ticketFk = t.id - INNER JOIN worker w ON tt.workerFk = w.id - WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo AND s.code = vStateCode - GROUP BY tt.workerFk; + DROP TEMPORARY TABLE IF EXISTS tmp.total; -SELECT w.code, w.firstName, w.lastName, CAST(tmp.total.CuentaDeId_Ticket AS DECIMAL(10,0)) AS Totaltickets, - CAST(sub.CuentaDeId_Ticket AS DECIMAL(10,0)) AS Fallos -fROM tmp.total - JOIN worker w ON w.id= tmp.total.workerFk -LEFT JOIN ( SELECT Count(s.ticketFk) AS CuentaDeId_Ticket, cd.workerFk - FROM (claimDevelopment cd - INNER JOIN ((sale s - INNER JOIN claimBeginning cb ON s.id = cb.saleFk) - INNER JOIN ticket t ON s.ticketFk = t.id) ON cd.claimFk = cb.claimFk) - INNER JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id - WHERE t.shipped BETwEEN vDatedFrom AND vDatedTo AND cr.description=vDepartment - GROUP BY cd.workerFk)sub ON tmp.total.workerFk = sub.workerFk; + CREATE TEMPORARY TABLE tmp.total + ENGINE = MEMORY + SELECT st.workerFk, Count(t.id) AS saleCount + FROM state ss + JOIN vn.saleTracking st ON st.stateFk = ss.id + JOIN vn.sale s ON s.id = st.saleFk + JOIN ticket t ON s.ticketFk = t.id + JOIN worker w ON st.workerFk = w.id + WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo AND ss.code = vStateCode + GROUP BY st.workerFk; + + INSERT INTO tmp.total + SELECT e.workerFk, Count(DISTINCT t.id) AS saleCount + FROM expedition e + JOIN ticket t ON e.ticketFk = t.id + JOIN worker w ON e.workerFk = w.id + WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo + GROUP BY e.workerFk; + + SELECT w.code, w.firstName, w.lastName, CAST(MAX(tmp.total.saleCount) AS DECIMAL(10,0)) AS Totaltickets, CAST(sub.CuentaDeTicketFk AS DECIMAL(10,0)) AS Fallos + FROM tmp.total + JOIN worker w ON w.id = tmp.total.workerFk + LEFT JOIN ( + SELECT COUNT(c.ticketFk) AS CuentaDeTicketFk, cd.workerFk + FROM claimDevelopment cd + JOIN claim c ON cd.claimFk = c.id + JOIN ticket t ON c.ticketFk = t.id + JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id + WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo AND cr.description=vDepartment + GROUP BY cd.workerFk + )sub ON tmp.total.workerFk = sub.workerFk + GROUP BY w.code; -END ;; + DROP TEMPORARY TABLE tmp.total; + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `workingHours` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -78777,9 +83495,9 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 DROP PROCEDURE IF EXISTS `workingHoursTimeIn` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -78799,9 +83517,9 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 DROP PROCEDURE IF EXISTS `workingHoursTimeOut` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -78823,7 +83541,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci ; /*!50003 DROP PROCEDURE IF EXISTS `wrongEqualizatedClient` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -78964,7 +83682,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `zoneClosure_recalc_beta` */; +/*!50003 DROP PROCEDURE IF EXISTS `zoneClosure_recalc_beta__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -78974,7 +83692,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `zoneClosure_recalc_beta`() +CREATE DEFINER=`root`@`%` PROCEDURE `zoneClosure_recalc_beta__`() proc: BEGIN /** * Recalculates the delivery time (hour) for every zone in days + scope in future @@ -79295,205 +84013,6 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `zoneGetAgency__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetAgency__`(vAddress INT, vLanded DATE) -BEGIN -/** - * Devuelve el listado de agencias disponibles para la fecha - * y dirección pasadas. - * - * @param vAddress Id de dirección de envío, %NULL si es recogida - * @param vDate Fecha de recogida - * @select Listado de agencias disponibles - */ - - CALL zone_getAgency(vAddress,vLanded); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `zoneGetLanded__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetLanded__`(vShipped DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT) -BEGIN -/** -* JGF procedimiento TEMPORAL -* ATENCION hablad conmigo si queréis cambiar algo de aquí -* Devuelve una tabla temporal con el dia de recepcion para vShipped. -* -* @param vShipped Fecha de preparacion de mercancia -* @param vAddressFk Id de consignatario, %NULL para recogida -* @param vAgencyModeFk Id agencia -* @param vWarehouseFk vWarehouseFk -* @table tmp.zoneGetLanded Datos de recepción -*/ - - CALL zone_getFromGeo(address_getGeo(vAddressFk)); - CALL zone_getOptionsForShipment(vShipped, FALSE); - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; - CREATE TEMPORARY TABLE tmp.zoneGetLanded - ENGINE = MEMORY - SELECT vWarehouseFk warehouseFk, - TIMESTAMPADD(DAY,zo.travelingDays, vShipped) landed, - zo.zoneFk - FROM tmp.zoneOption zo - JOIN zone z ON z.id = zo.zoneFk - JOIN zoneWarehouse zw ON zw.zoneFk = z.id - WHERE agencyModeFk = vAgencyModeFk - AND zw.warehouseFk = vWarehouseFk; - - DROP TEMPORARY TABLE - tmp.zone, - tmp.zoneOption; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `zoneGetShippedWarehouse__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetShippedWarehouse__`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) -BEGIN -/** - * Devuelve la mínima fecha de envío para cada warehouse - * - * @param vLanded La fecha de recepcion - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id de la agencia - * @return tmp.zoneGetShipped - */ - CALL zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `zoneGetShipped__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetShipped__`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT) -BEGIN -/** - * OBSOLETO usar zone_getShippedWarehouse - * Devuelve la mínima fecha de envía para cada warehouse - * - * @param vLanded La fecha de recepcion - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id de la agencia - * @return tmp.zoneGetShipped - */ - CALL zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); - - SELECT * FROM tmp.zoneGetShipped WHERE warehouseFk <> vWarehouseFk; - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `zoneGetWarehouse__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetWarehouse__`(vAddress INT, vLanded DATE, vWarehouse INT) -BEGIN -/** -* Devuelve el listado de agencias disponibles para la fecha, - * dirección y warehouse pasadas - * - * @param vAddress - * @param vWarehouse warehouse - * @param vLanded Fecha de recogida - * @select Listado de agencias disponibles - */ - - DECLARE vGeoFk INT; - - SELECT p.geoFk INTO vGeoFk - FROM address a - JOIN town t ON t.provinceFk = a.provinceFk - JOIN postCode p ON p.townFk = t.id AND p.code = a.postalCode - WHERE a.id = vAddress - ORDER BY (a.city SOUNDS LIKE t.`name`) DESC - LIMIT 1; - - - SELECT * FROM ( - SELECT * FROM ( - SELECT am.id agencyModeFk, - am.name agencyMode, - am.description, - am.deliveryMethodFk, - TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, - z.warehouseFk, - zi.isIncluded, - z.id zoneFk - FROM zoneGeo zgSon - JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt - JOIN zoneIncluded zi ON zi.geoFk = zgFather.id - JOIN zone z ON z.id = zi.zoneFk - JOIN zoneCalendar zc ON zc.zoneFk = z.id - JOIN agencyMode am ON am.id = z.agencyModeFk - WHERE zgSon.`id` = vGeoFk - AND delivered = vLanded - AND z.warehouseFk = vWarehouse - AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) - ORDER BY z.id, zgFather.depth DESC) t - GROUP BY zoneFk - HAVING isIncluded > 0) t - GROUP BY agencyModeFk; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `zonePromo_Make` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -79696,6 +84215,114 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getCollisions` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getCollisions`() +BEGIN +/** + * Calcula si para un mismo codigo postal y dia + * hay mas de una zona configurada + * + */ + DECLARE vGeoFk INT DEFAULT NULL; + DECLARE vZoneFk INT; + DECLARE vIsDone INT DEFAULT FALSE; + DECLARE cur1 CURSOR FOR SELECT zoneFk from tmp.zoneOption; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE; + + DROP TEMPORARY TABLE IF EXISTS tmp.zone; + CREATE TEMPORARY TABLE tmp.zone + SELECT z.id + FROM zone z + JOIN agencyMode am ON am.id = z.agencyModeFk + JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk + WHERE dm.code IN ('AGENCY','DELIVERY'); + + CALL zone_getOptionsForShipment(CURDATE(),FALSE); + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneNodes; + CREATE TEMPORARY TABLE tmp.zoneNodes ( + geoFk INT, + name VARCHAR(100), + parentFk INT, + sons INT, + isChecked BOOL DEFAULT 0, + zoneFk INT, + PRIMARY KEY zoneFkk (zoneFk, geoFk)) + ENGINE = MEMORY; + + OPEN cur1; + cur1Loop: LOOP + SET vIsDone = FALSE; + FETCH cur1 INTO vZoneFk; + IF vIsDone THEN + LEAVE cur1Loop; + END IF; + + CALL zone_getLeaves2(vZoneFk, NULL, NULL); + + myLoop: LOOP + SET vGeoFk = NULL; + SELECT geoFk INTO vGeoFk + FROM tmp.zoneNodes zn + WHERE NOT isChecked + LIMIT 1; + + IF vGeoFk IS NULL THEN + LEAVE myLoop; + END IF; + + CALL zone_getLeaves2(vZoneFk, vGeoFk, NULL); + UPDATE tmp.zoneNodes + SET isChecked = TRUE + WHERE geoFk = vGeoFk; + END LOOP; + + END LOOP; + CLOSE cur1; + DELETE FROM tmp.zoneNodes + WHERE sons > 0; + + DROP TEMPORARY TABLE IF EXISTS geoCollision; + CREATE TEMPORARY TABLE geoCollision + SELECT z.agencyModeFk, zn.geoFk + FROM tmp.zoneNodes zn + JOIN zone z ON z.id = zn.zoneFk + GROUP BY z.agencyModeFk, zn.geoFk + HAVING count(*) > 1; + + SELECT zn.name postalCode, + zoneFk, + z.price, + z.name, + CONCAT('https://salix.verdnatura.es/#!/zone/', + zoneFk, + '/location?q=%7B%22search%22:%22', + zn.name, + '%22%7D') salix + FROM tmp.zoneNodes zn + JOIN zone z ON z.id = zn.zoneFk + JOIN geoCollision gc ON gc.agencyModeFk = z.agencyModeFk AND zn.geoFk = gc.geoFk; + + DROP TEMPORARY TABLE + geoCollision, + tmp.zone, + tmp.zoneNodes; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `zone_getEvents` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -79769,66 +84396,6 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `zone_getEvents__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getEvents__`( - vProvinceFk INT, - vPostCode VARCHAR(255), - vAgencyModeFk INT) -BEGIN -/** - * Returns available events for the passed province/postcode and agency. - * - * @param vAgencyModeFk The agency mode id - * @param vProvinceFk The province id - * @param vPostCode The postcode or %NULL to use the province - */ - - DECLARE vGeoFk INT; - - IF vPostCode IS NOT NULL THEN - SELECT p.geoFk INTO vGeoFk - FROM postCode p - JOIN town t ON t.id = p.townFk - WHERE p.`code` = vPostCode - AND t.provinceFk = vProvinceFk; - ELSE - SELECT geoFk INTO vGeoFk - FROM province - WHERE id = vProvinceFk; - END IF; - - CALL zone_getFromGeo(vGeoFk); - - IF vAgencyModeFk IS NOT NULL THEN - DELETE t FROM tmp.zone t - JOIN zone z ON z.id = t.id - WHERE z.agencyModeFk != vAgencyModeFk; - END IF; - - SELECT e.zoneFk, e.`type`, e.dated, e.`started`, e.`ended`, e.weekDays - FROM tmp.zone t - JOIN zoneEvent e ON e.zoneFk = t.id; - - SELECT e.zoneFk, e.dated - FROM tmp.zone t - JOIN zoneExclusion e ON e.zoneFk = t.id; - - DROP TEMPORARY TABLE tmp.zone; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `zone_getFromGeo` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -80043,6 +84610,222 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getLeaves2` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getLeaves2`( + vSelf INT, + vParentFk INT, + vSearch VARCHAR(255) +) +BEGIN +/** + * HAY QUE REFACTORIZAR ESTE Y zone_getLeaves + * https://redmine.verdnatura.es/issues/3073 + * Devuelve los geoFk incluidos en la ruta y que sean hijos de parentFk + * @param vSelf Id de la zona + * @param vParentFk Id del geo a calcular + * @param vSearch cadena a buscar + * + * @return tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + * + */ + DECLARE vIsNumber BOOL; + DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != ''; + + DROP TEMPORARY TABLE IF EXISTS tNodes; + CREATE TEMPORARY TABLE tNodes + (UNIQUE (id)) + ENGINE = MEMORY + SELECT id FROM zoneGeo LIMIT 0; + + IF vIsSearch THEN + SET vIsNumber = vSearch REGEXP '^[0-9]+$'; + + INSERT INTO tNodes + SELECT id FROM zoneGeo + WHERE (vIsNumber AND `name` = vSearch) + OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) + LIMIT 1000; + ELSEIF vParentFk IS NULL THEN + INSERT INTO tNodes + SELECT geoFk FROM zoneIncluded + WHERE zoneFk = vSelf; + END IF; + + IF vParentFk IS NULL THEN + DROP TEMPORARY TABLE IF EXISTS tChilds; + CREATE TEMPORARY TABLE tChilds + ENGINE = MEMORY + SELECT id FROM tNodes; + + DROP TEMPORARY TABLE IF EXISTS tParents; + CREATE TEMPORARY TABLE tParents + ENGINE = MEMORY + SELECT id FROM zoneGeo LIMIT 0; + + myLoop: LOOP + DELETE FROM tParents; + INSERT INTO tParents + SELECT parentFk id + FROM zoneGeo g + JOIN tChilds c ON c.id = g.id + WHERE g.parentFk IS NOT NULL; + + INSERT IGNORE INTO tNodes + SELECT id FROM tParents; + + IF ROW_COUNT() = 0 THEN + LEAVE myLoop; + END IF; + + DELETE FROM tChilds; + INSERT INTO tChilds + SELECT id FROM tParents; + END LOOP; + + DROP TEMPORARY TABLE + tChilds, + tParents; + END IF; + + IF !vIsSearch THEN + INSERT IGNORE INTO tNodes + SELECT id FROM zoneGeo + WHERE parentFk <=> vParentFk; + END IF; + + INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + SELECT g.id, + g.`name`, + g.parentFk, + g.sons, + NOT g.sons OR type = 'country', + vSelf + FROM zoneGeo g + JOIN tNodes n ON n.id = g.id + LEFT JOIN zoneIncluded i + ON i.geoFk = g.id AND i.zoneFk = vSelf + WHERE (i.isIncluded = TRUE + OR (i.isIncluded IS NULL AND vParentFk IS NOT NULL)); + DROP TEMPORARY TABLE tNodes; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getLeaves___` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getLeaves___`( + vSelf INT, + vParentFk INT, + vSearch VARCHAR(255) +) +BEGIN + DECLARE vIsNumber BOOL; + DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != ''; + + DROP TEMPORARY TABLE IF EXISTS tNodes; + CREATE TEMPORARY TABLE tNodes + (UNIQUE (id)) + ENGINE = MEMORY + SELECT id FROM zoneGeo LIMIT 0; + + IF vIsSearch THEN + SET vIsNumber = vSearch REGEXP '^[0-9]+$'; + + INSERT INTO tNodes + SELECT id FROM zoneGeo + WHERE (vIsNumber AND `name` = vSearch) + OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) + LIMIT 1000; + ELSEIF vParentFk IS NULL THEN + INSERT INTO tNodes + SELECT geoFk FROM zoneIncluded + WHERE zoneFk = vSelf; + END IF; + + IF vParentFk IS NULL THEN + DROP TEMPORARY TABLE IF EXISTS tChilds; + CREATE TEMPORARY TABLE tChilds + ENGINE = MEMORY + SELECT id FROM tNodes; + + DROP TEMPORARY TABLE IF EXISTS tParents; + CREATE TEMPORARY TABLE tParents + ENGINE = MEMORY + SELECT id FROM zoneGeo LIMIT 0; + + myLoop: LOOP + DELETE FROM tParents; + INSERT INTO tParents + SELECT parentFk id + FROM zoneGeo g + JOIN tChilds c ON c.id = g.id + WHERE g.parentFk IS NOT NULL; + + INSERT IGNORE INTO tNodes + SELECT id FROM tParents; + + IF ROW_COUNT() = 0 THEN + LEAVE myLoop; + END IF; + + DELETE FROM tChilds; + INSERT INTO tChilds + SELECT id FROM tParents; + END LOOP; + + DROP TEMPORARY TABLE + tChilds, + tParents; + END IF; + + IF !vIsSearch THEN + INSERT IGNORE INTO tNodes + SELECT id FROM zoneGeo + WHERE parentFk <=> vParentFk; + END IF; + + + INSERT IGNORE INTO zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + SELECT g.id, + g.`name`, + g.parentFk, + g.sons, + NOT g.sons OR type = 'country', + vSelf + FROM zoneGeo g + JOIN tNodes n ON n.id = g.id + LEFT JOIN zoneIncluded i + ON i.geoFk = g.id AND i.zoneFk = vSelf + WHERE (i.isIncluded = TRUE + OR (i.isIncluded IS NULL AND vParentFk IS NOT NULL)) + ; + + DROP TEMPORARY TABLE tNodes; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `zone_getOptionsForLanding` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -80117,80 +84900,6 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `zone_getOptionsForLanding__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getOptionsForLanding__`(vLanded DATE) -BEGIN -/** - * Gets computed options for the passed zones and delivery date. - * - * @table tmp.zones(id) The zones ids - * @param vLanded The delivery date - * @return tmp.zoneOption The computed options - */ - DECLARE vHour TIME DEFAULT TIME(NOW()); - - DROP TEMPORARY TABLE IF EXISTS tTemp; - CREATE TEMPORARY TABLE tTemp - ENGINE = MEMORY - SELECT t.id zoneFk, - IFNULL(TIME(e.`hour`), TIME(z.`hour`)) `hour`, - IFNULL(e.travelingDays, z.travelingDays) travelingDays, - IFNULL(e.price, z.price) price, - IFNULL(e.bonus, z.bonus) bonus, - CASE - WHEN e.`type` = 'day' - THEN 1 - WHEN e.`type` = 'range' - THEN 2 - ELSE 3 - END specificity - FROM tmp.zone t - JOIN zone z ON z.id = t.id - JOIN zoneEvent e ON e.zoneFk = t.id - WHERE ( - e.`type` = 'day' - AND e.dated = vLanded - ) OR ( - e.`type` != 'day' - AND e.weekDays & (1 << WEEKDAY(vLanded)) - AND (e.`started` IS NULL OR vLanded >= e.`started`) - AND (e.`ended` IS NULL OR vLanded <= e.`ended`) - ); - - DELETE t FROM tTemp t - JOIN zoneExclusion e - ON e.zoneFk = t.zoneFk AND e.`dated` = vLanded; - - DELETE FROM tTemp - WHERE (@shipped := TIMESTAMPADD(DAY, -travelingDays, vLanded)) < CURDATE() - OR @shipped = CURDATE() AND vHour > `hour`; - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; - CREATE TEMPORARY TABLE tmp.zoneOption - ENGINE = MEMORY - SELECT * - FROM ( - SELECT * FROM tTemp - ORDER BY zoneFk, specificity - ) t - GROUP BY zoneFk; - - DROP TEMPORARY TABLE tTemp; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `zone_getOptionsForShipment` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -80387,97 +85096,6 @@ BEGIN -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `zone_getOptionsForShipment__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getOptionsForShipment__`(vShipped DATE, vShowExpiredZones BOOLEAN) -BEGIN -/** - * Gets computed options for the passed zones and shipping date. - * - * @table tmp.zones(id) The zones ids - * @param vShipped The shipping date - * @return tmp.zoneOption(zoneFk, hour, travelingDays, price, bonus, specificity) The computed options - */ - DECLARE vHour TIME DEFAULT TIME(NOW()); - - DROP TEMPORARY TABLE IF EXISTS tLandings; - CREATE TEMPORARY TABLE tLandings - (INDEX (eventFk)) - ENGINE = MEMORY - SELECT e.id eventFk, - @travelingDays := IFNULL(e.travelingDays, z.travelingDays) travelingDays, - TIMESTAMPADD(DAY, @travelingDays, vShipped) landed - FROM tmp.zone t - JOIN zone z ON z.id = t.id - JOIN zoneEvent e ON e.zoneFk = t.id; - - DROP TEMPORARY TABLE IF EXISTS tTemp; - CREATE TEMPORARY TABLE tTemp - ENGINE = MEMORY - SELECT t.id zoneFk, - IFNULL(TIME(e.`hour`), TIME(z.`hour`)) `hour`, - IFNULL(e.price, z.price) price, - IFNULL(e.bonus, z.bonus) bonus, - CASE - WHEN e.`type` = 'day' - THEN 1 - WHEN e.`type` = 'range' - THEN 2 - ELSE 3 - END specificity, - l.travelingDays, - l.landed - FROM tmp.zone t - JOIN zone z ON z.id = t.id - JOIN zoneEvent e ON e.zoneFk = t.id - JOIN tLandings l ON l.eventFk = e.id - WHERE ( - e.`type` = 'day' - AND e.`dated` = l.landed - ) OR ( - e.`type` != 'day' - AND e.weekDays & (1 << WEEKDAY(l.landed)) - AND (e.`started` IS NULL OR l.landed >= e.`started`) - AND (e.`ended` IS NULL OR l.landed <= e.`ended`) - ); - - DELETE t FROM tTemp t - JOIN zoneExclusion e - ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed; - - IF NOT vShowExpiredZones THEN - DELETE FROM tTemp - WHERE vShipped < CURDATE() - OR (vShipped = CURDATE() AND vHour > `hour`); - END IF; - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; - CREATE TEMPORARY TABLE tmp.zoneOption - ENGINE = MEMORY - SELECT * - FROM ( - SELECT * FROM tTemp - ORDER BY zoneFk, specificity - ) t - GROUP BY zoneFk; - - DROP TEMPORARY TABLE - tTemp, - tLandings; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -80562,57 +85180,6 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `zone_getShippedWarehouse__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getShippedWarehouse__`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) -BEGIN -/** - * Devuelve la mínima fecha de envío para cada warehouse - * - * @param vLanded La fecha de recepcion - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id de la agencia - * @return tmp.zoneGetShipped - */ - - CALL zone_getFromGeo(address_getGeo(vAddressFk)); - CALL zone_getOptionsForLanding(vLanded,TRUE); - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped; - CREATE TEMPORARY TABLE tmp.zoneGetShipped - ENGINE = MEMORY - SELECT * FROM ( - SELECT zo.zoneFk, - TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped, - zo.`hour`, - zw.warehouseFk, - z.agencyModeFk, - zo.price, - zo.bonus - FROM tmp.zoneOption zo - JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk - JOIN zone z ON z.id = zo.zoneFk - WHERE z.agencyModeFk = vAgencyModeFk - ORDER BY shipped) t - GROUP BY warehouseFk; - - DROP TEMPORARY TABLE - tmp.zone, - tmp.zoneOption; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `zone_getWarehouse` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -80657,56 +85224,6 @@ BEGIN tmp.zone, tmp.zoneOption; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `zone_getWarehouse__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getWarehouse__`(vAddress INT, vLanded DATE, vWarehouse INT) -BEGIN -/** - * Devuelve el listado de agencias disponibles para la fecha, - * dirección y almacén pasados. - * - * @param vAddress - * @param vWarehouse warehouse - * @param vLanded Fecha de recogida - * @select Listado de agencias disponibles - */ - - CALL zone_getFromGeo(address_getGeo(vAddress)); - CALL zone_getOptionsForLanding(vLanded, FALSE); - - SELECT am.id agencyModeFk, - am.name agencyMode, - am.description, - am.deliveryMethodFk, - TIMESTAMPADD(DAY, -zo.travelingDays, vLanded) shipped, - zw.warehouseFk, - z.id zoneFk - FROM tmp.zoneOption zo - JOIN zone z ON z.id = zo.zoneFk - JOIN agencyMode am ON am.id = z.agencyModeFk - JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk - WHERE zw.warehouseFk - GROUP BY z.agencyModeFk - ORDER BY agencyMode; - - DROP TEMPORARY TABLE - tmp.zone, - tmp.zoneOption; - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -80856,7 +85373,7 @@ CREATE TABLE `inter` ( `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `Id_Ticket` int(11) DEFAULT NULL, `Id_Trabajador` int(11) DEFAULT NULL, - `Id_Supervisor` int(11) DEFAULT NULL, + `Id_Supervisor` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`inter_id`), KEY `currante` (`Id_Trabajador`), KEY `responsable` (`Id_Supervisor`), @@ -82174,6 +86691,25 @@ USE `vn`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; +-- +-- Final view structure for view `bankPolicy` +-- + +/*!50001 DROP TABLE IF EXISTS `bankPolicy`*/; +/*!50001 DROP VIEW IF EXISTS `bankPolicy`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `bankPolicy` AS select `bp`.`poliza_id` AS `id`,`bp`.`referencia` AS `ref`,`bp`.`importe` AS `amount`,`bp`.`com_dispuesto` AS `balanceInterestDrawn`,`bp`.`com_no_dispuesto` AS `commissionAvailableBalances`,`bp`.`com_anual` AS `openingCommission`,`bp`.`apertura` AS `started`,`bp`.`cierre` AS `ended`,`bp`.`Id_Banco` AS `bankFk`,`bp`.`empresa_id` AS `companyFk`,`bp`.`supplierFk` AS `supplierFk`,`bp`.`description` AS `description`,`bp`.`hasGuarantee` AS `hasGuarantee`,`bp`.`dmsFk` AS `dmsFk`,`bp`.`notaryFk` AS `notaryFk`,`bp`.`currencyFk` AS `currencyFk`,`bp`.`amortizationTypeFk` AS `amortizationTypeFk`,`bp`.`periodicityTypeFk` AS `periodicityTypeFk`,`bp`.`insuranceExpired` AS `insuranceExpired` from `vn2008`.`Bancos_poliza` `bp` order by `bp`.`poliza_id` desc */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + -- -- Final view structure for view `businessCalendar` -- @@ -82302,7 +86838,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `clientRisk__` AS select `c`.`customer_id` AS `clientFk`,`c`.`company_id` AS `companyFk`,`c`.`amount` AS `amount` from `bi`.`customer_risk` `c` */; +/*!50001 VIEW `clientRisk__` AS select `c`.`customer_id` AS `clientFk`,`c`.`company_id` AS `companyFk`,`c`.`amount` AS `amount` from `bi`.`customer_risk__` `c` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -82316,12 +86852,12 @@ USE `vn`; /*!50001 SET @saved_cs_client = @@character_set_client */; /*!50001 SET @saved_cs_results = @@character_set_results */; /*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `cmr_list` AS select `cmr`.`id` AS `cmrFk`,`cmr`.`ticketFk` AS `ticketFk`,`cmr`.`truckPlate` AS `truckPlate`,`cmr`.`observations` AS `observations`,`cmr`.`senderInstruccions` AS `senderInstruccions`,`cmr`.`paymentInstruccions` AS `paymentInstruccions`,`cmr`.`specialAgreements` AS `specialAgreements`,`cmr`.`created` AS `created`,`cmr`.`packagesList` AS `packagesList`,`aTo`.`nickname` AS `clientName`,`aTo`.`postalCode` AS `clientPostalCode`,`aTo`.`street` AS `clientStreet`,`aTo`.`city` AS `clientCity`,`pTo`.`name` AS `clientProvince`,`cTo`.`country` AS `clientCountry`,`su`.`name` AS `companyName`,`su`.`street` AS `companyStreet`,`su`.`postCode` AS `companyPostCode`,`su`.`city` AS `companyCity`,`cSu`.`country` AS `companyCountry`,concat(`aFrom`.`street`,' ',`aFrom`.`postalCode`,' ',`aFrom`.`city`,' (',`cFrom`.`country`,')') AS `warehouseAddress`,`cmr`.`created` AS `shipped`,`aTo`.`nickname` AS `clientOficialName`,`cmr`.`supplierFk` AS `supplierFk`,`aSu`.`name` AS `carrierName`,`aSu`.`street` AS `carrierStreet`,`aSu`.`postCode` AS `carrierPostCode`,`aSu`.`city` AS `carrierCity`,`cAs`.`country` AS `carrierCountry`,ifnull(`aTo`.`phone`,`client`.`phone`) AS `phone`,ifnull(`aTo`.`mobile`,`client`.`mobile`) AS `mobile`,`aTo`.`id` AS `addressFk` from (((((((((((`cmr` left join `address` `aTo` on((`aTo`.`id` = `cmr`.`addressToFk`))) left join `province` `pTo` on((`pTo`.`id` = `aTo`.`provinceFk`))) left join `country` `cTo` on((`cTo`.`id` = `pTo`.`countryFk`))) left join `client` on((`client`.`id` = `aTo`.`clientFk`))) left join `supplier` `su` on((`su`.`id` = `cmr`.`companyFk`))) left join `country` `cSu` on((`cSu`.`id` = `su`.`countryFk`))) left join `address` `aFrom` on((`aFrom`.`id` = `cmr`.`addressFromFk`))) left join `province` `pFrom` on((`pFrom`.`id` = `aFrom`.`provinceFk`))) left join `country` `cFrom` on((`cFrom`.`id` = `pFrom`.`countryFk`))) left join `supplier` `aSu` on((`aSu`.`id` = `cmr`.`supplierFk`))) left join `country` `cAs` on((`cAs`.`id` = `aSu`.`countryFk`))) */; +/*!50001 VIEW `cmr_list` AS select `cmr`.`id` AS `cmrFk`,`cmr`.`ticketFk` AS `ticketFk`,`cmr`.`truckPlate` AS `truckPlate`,`cmr`.`observations` AS `observations`,`cmr`.`senderInstruccions` AS `senderInstruccions`,`cmr`.`paymentInstruccions` AS `paymentInstruccions`,`cmr`.`specialAgreements` AS `specialAgreements`,`cmr`.`created` AS `created`,`cmr`.`packagesList` AS `packagesList`,`aTo`.`nickname` AS `clientName`,`aTo`.`postalCode` AS `clientPostalCode`,`aTo`.`street` AS `clientStreet`,`aTo`.`city` AS `clientCity`,`pTo`.`name` AS `clientProvince`,`cTo`.`country` AS `clientCountry`,`su`.`name` AS `companyName`,`su`.`street` AS `companyStreet`,`su`.`postCode` AS `companyPostCode`,`su`.`city` AS `companyCity`,`cSu`.`country` AS `companyCountry`,concat(`aFrom`.`street`,' ',`aFrom`.`postalCode`,' ',`aFrom`.`city`,' (',`cFrom`.`country`,')') AS `warehouseAddress`,`cmr`.`created` AS `shipped`,`aTo`.`nickname` AS `clientOficialName`,`cmr`.`supplierFk` AS `supplierFk`,`aSu`.`name` AS `carrierName`,`aSu`.`street` AS `carrierStreet`,`aSu`.`postCode` AS `carrierPostCode`,`aSu`.`city` AS `carrierCity`,`cAs`.`country` AS `carrierCountry`,ifnull(`aTo`.`phone`,`client`.`phone`) AS `phone`,ifnull(`aTo`.`mobile`,`client`.`mobile`) AS `mobile`,`aTo`.`id` AS `addressFk`,`c`.`stamp` AS `stamp`,`cmr`.`merchandiseDetail` AS `merchandiseDetail` from ((((((((((((`cmr` left join `address` `aTo` on((`aTo`.`id` = `cmr`.`addressToFk`))) left join `province` `pTo` on((`pTo`.`id` = `aTo`.`provinceFk`))) left join `country` `cTo` on((`cTo`.`id` = `pTo`.`countryFk`))) left join `client` on((`client`.`id` = `aTo`.`clientFk`))) left join `supplier` `su` on((`su`.`id` = `cmr`.`companyFk`))) left join `country` `cSu` on((`cSu`.`id` = `su`.`countryFk`))) left join `address` `aFrom` on((`aFrom`.`id` = `cmr`.`addressFromFk`))) left join `province` `pFrom` on((`pFrom`.`id` = `aFrom`.`provinceFk`))) left join `country` `cFrom` on((`cFrom`.`id` = `pFrom`.`countryFk`))) left join `supplier` `aSu` on((`aSu`.`id` = `cmr`.`supplierFk`))) left join `country` `cAs` on((`cAs`.`id` = `aSu`.`countryFk`))) join `company` `c` on((`c`.`id` = `cmr`.`companyFk`))) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -82364,6 +86900,25 @@ USE `vn`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; +-- +-- Final view structure for view `collectionSmartTag2` +-- + +/*!50001 DROP TABLE IF EXISTS `collectionSmartTag2`*/; +/*!50001 DROP VIEW IF EXISTS `collectionSmartTag2`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `collectionSmartTag2` AS select `st`.`code` AS `code`,`tc`.`ticketFk` AS `ticketFk`,`tc`.`level` AS `level`,`tc`.`wagon` AS `wagon`,`st`.`shelvingFk` AS `shelvingFk`,`tc`.`collectionFk` AS `collectionFk`,`am`.`name` AS `agencyFk`,`t`.`clientFk` AS `clientFk`,`u`.`name` AS `worker`,`t`.`shipped` AS `shipped`,`t`.`landed` AS `landed` from ((((((`vn`.`ticketCollection` `tc` join `vn`.`smartTag` `st` on((`st`.`code` = (`tc`.`smartTagFk` collate utf8_general_ci)))) join `vn`.`ticket` `t` on((`t`.`id` = `tc`.`ticketFk`))) join `vn`.`collection` `c` on((`c`.`id` = `tc`.`collectionFk`))) join `vn`.`worker` `w` on((`w`.`id` = `c`.`workerFk`))) join `vn`.`agencyMode` `am` on((`am`.`id` = `t`.`agencyModeFk`))) join `account`.`user` `u` on((`u`.`id` = `w`.`id`))) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + -- -- Final view structure for view `componentRate__` -- @@ -82582,12 +87137,12 @@ USE `vn`; /*!50001 SET @saved_cs_client = @@character_set_client */; /*!50001 SET @saved_cs_results = @@character_set_results */; /*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `exchangeInsuranceOut` AS select `p`.`received` AS `received`,sum(`p`.`divisa`) AS `divisa`,(sum(`p`.`divisa`) / sum(`p`.`amount`)) AS `rate` from (`payment` `p` join `bank` `b` on((`b`.`id` = `p`.`bankFk`))) where ((`p`.`currencyFk` = 2) and (`b`.`cash` = 0) and (`p`.`supplierFk` <> 2213)) group by `p`.`received` */; +/*!50001 VIEW `exchangeInsuranceOut` AS select `p`.`received` AS `received`,sum(`p`.`divisa`) AS `divisa`,(sum(`p`.`divisa`) / sum(`p`.`amount`)) AS `rate` from ((`payment` `p` join `bank` `b` on((`b`.`id` = `p`.`bankFk`))) join `accountingType` `at2` on((`at2`.`id` = `b`.`cash`))) where ((`p`.`currencyFk` = 2) and (`at2`.`code` = 'wireTransfer') and (`p`.`supplierFk` <> 2213)) group by `p`.`received` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -82715,12 +87270,31 @@ USE `vn`; /*!50001 SET @saved_cs_client = @@character_set_client */; /*!50001 SET @saved_cs_results = @@character_set_results */; /*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionSticker` AS select `e`.`id` AS `expeditionFk`,`e`.`ticketFk` AS `ticketFk`,`t`.`addressFk` AS `addressFk`,`t`.`clientFk` AS `clientFk`,`a`.`street` AS `street`,`a`.`postalCode` AS `postalCode`,`a`.`city` AS `city`,`a`.`nickname` AS `nickname`,concat('R(',right(`t`.`routeFk`,4),')') AS `routeFk`,`rm`.`beachFk` AS `beachFk`,if(`t`.`routeFk`,replace(`z`.`name`,'ZONA ','Z'),`am`.`name`) AS `zona`,`p`.`name` AS `province`,ifnull(`a`.`mobile`,`a`.`phone`) AS `phone` from (((((((`expedition` `e` join `ticket` `t` on((`t`.`id` = `e`.`ticketFk`))) join `address` `a` on((`a`.`id` = `t`.`addressFk`))) join `province` `p` on((`p`.`id` = `a`.`provinceFk`))) left join `routesMonitor` `rm` on((`rm`.`routeFk` = `t`.`routeFk`))) left join `beach` `b` on((`b`.`id` = `rm`.`beachFk`))) left join `zone` `z` on((`z`.`id` = `t`.`zoneFk`))) join `agencyMode` `am` on((`t`.`agencyModeFk` = `am`.`id`))) */; +/*!50001 VIEW `expeditionSticker` AS select `e`.`id` AS `expeditionFk`,`e`.`ticketFk` AS `ticketFk`,`t`.`addressFk` AS `addressFk`,`t`.`clientFk` AS `clientFk`,`a`.`street` AS `street`,`a`.`postalCode` AS `postalCode`,`a`.`city` AS `city`,`a`.`nickname` AS `nickname`,concat('R(',convert(right(`t`.`routeFk`,4) using utf8mb4),')') AS `routeFk`,`rm`.`beachFk` AS `beachFk`,if(`t`.`routeFk`,replace(`am`.`name`,'ZONA ','Z'),`z`.`name`) AS `zona`,`p`.`name` AS `province`,ifnull(`c`.`mobile`,ifnull(`a`.`mobile`,ifnull(`c`.`phone`,`a`.`phone`))) AS `phone` from (((((((((`expedition` `e` join `ticket` `t` on((`t`.`id` = `e`.`ticketFk`))) join `address` `a` on((`a`.`id` = `t`.`addressFk`))) join `province` `p` on((`p`.`id` = `a`.`provinceFk`))) left join `routesMonitor` `rm` on((`rm`.`routeFk` = `t`.`routeFk`))) left join `beach` `b` on((`b`.`id` = `rm`.`beachFk`))) left join `zone` `z` on((`z`.`id` = `t`.`zoneFk`))) left join `route` `r` on((`r`.`id` = `t`.`routeFk`))) left join `agencyMode` `am` on((`am`.`id` = `r`.`agencyModeFk`))) join `client` `c` on((`c`.`id` = `a`.`clientFk`))) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `expeditionSticker__` +-- + +/*!50001 DROP TABLE IF EXISTS `expeditionSticker__`*/; +/*!50001 DROP VIEW IF EXISTS `expeditionSticker__`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `expeditionSticker__` AS select `e`.`id` AS `expeditionFk`,`e`.`ticketFk` AS `ticketFk`,`t`.`addressFk` AS `addressFk`,`t`.`clientFk` AS `clientFk`,`a`.`street` AS `street`,`a`.`postalCode` AS `postalCode`,`a`.`city` AS `city`,`a`.`nickname` AS `nickname`,concat('R(',convert(right(`t`.`routeFk`,4) using utf8mb4),')') AS `routeFk`,`rm`.`beachFk` AS `beachFk`,if(`t`.`routeFk`,replace(`z`.`name`,'ZONA ','Z'),`am`.`name`) AS `zona`,`p`.`name` AS `province`,ifnull(`a`.`mobile`,`a`.`phone`) AS `phone` from (((((((`expedition` `e` join `ticket` `t` on((`t`.`id` = `e`.`ticketFk`))) join `address` `a` on((`a`.`id` = `t`.`addressFk`))) join `province` `p` on((`p`.`id` = `a`.`provinceFk`))) left join `routesMonitor` `rm` on((`rm`.`routeFk` = `t`.`routeFk`))) left join `beach` `b` on((`b`.`id` = `rm`.`beachFk`))) left join `zone` `z` on((`z`.`id` = `t`.`zoneFk`))) join `agencyMode` `am` on((`t`.`agencyModeFk` = `am`.`id`))) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -83157,7 +87731,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `itemInk` AS select `i`.`longName` AS `longName`,`i`.`inkFk` AS `inkFk` from (`item` `i` join `ink` on((`ink`.`id` = `i`.`inkFk`))) where `ink`.`isRealColor` group by `i`.`longName` */; +/*!50001 VIEW `itemInk` AS select `i`.`longName` AS `longName`,`i`.`inkFk` AS `inkFk`,`ink`.`name` AS `color` from (`item` `i` join `ink` on((`ink`.`id` = `i`.`inkFk`))) where `ink`.`isRealColor` group by `i`.`longName` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -83200,6 +87774,25 @@ USE `vn`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; +-- +-- Final view structure for view `itemSearch` +-- + +/*!50001 DROP TABLE IF EXISTS `itemSearch`*/; +/*!50001 DROP VIEW IF EXISTS `itemSearch`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `itemSearch` AS select `s`.`itemFk` AS `itemFk`,`s`.`concept` AS `concept`,`s`.`quantity` AS `quantity`,`t`.`nickname` AS `nickname`,`t`.`shipped` AS `shipped` from ((`sale` `s` join `ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) join `warehouse` `w` on((`w`.`id` = `t`.`warehouseFk`))) where ((`t`.`shipped` between `util`.`yesterday`() and `util`.`tomorrow`()) and (`w`.`name` in ('VNH','Floramondo'))) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + -- -- Final view structure for view `itemShelvingAvailable` -- @@ -83485,6 +88078,25 @@ USE `vn`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; +-- +-- Final view structure for view `lastPurchases` +-- + +/*!50001 DROP TABLE IF EXISTS `lastPurchases`*/; +/*!50001 DROP VIEW IF EXISTS `lastPurchases`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` 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`.`ref` AS `ref`,`b`.`itemFk` AS `itemFk` from ((((`buy` `b` join `entry` `e` on((`e`.`id` = `b`.`entryFk`))) join `item` `i` on((`i`.`id` = `b`.`itemFk`))) join `travel` `tr` on((`tr`.`id` = `e`.`travelFk`))) join `warehouse` `w` on((`w`.`id` = `tr`.`warehouseInFk`))) where ((`tr`.`landed` between `util`.`yesterday`() and `util`.`tomorrow`()) and (`e`.`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 */; + -- -- Final view structure for view `lastTopClaims` -- @@ -83608,12 +88220,12 @@ USE `vn`; /*!50001 SET @saved_cs_client = @@character_set_client */; /*!50001 SET @saved_cs_results = @@character_set_results */; /*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `packageEquivalentItem` AS select `i`.`itemFk` AS `itemFk`,`ie`.`itemFk` AS `equivalentFk` from ((`packageEquivalent` `pe` join `packaging` `i` on((`i`.`id` = `pe`.`packageFk`))) join `packaging` `ie` on((`ie`.`id` = `pe`.`equivalentFk`))) */; +/*!50001 VIEW `packageEquivalentItem` AS select `p`.`itemFk` AS `itemFk`,`p2`.`itemFk` AS `equivalentFk` from ((`packageEquivalent` `pe` join `packaging` `p` on((`p`.`id` = `pe`.`packagingFk`))) join `packaging` `p2` on((`p2`.`id` = `pe`.`equivalentFk`))) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -84007,12 +88619,12 @@ USE `vn`; /*!50001 SET @saved_cs_client = @@character_set_client */; /*!50001 SET @saved_cs_results = @@character_set_results */; /*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `supplierPackaging` AS select `e`.`supplierFk` AS `supplierFk`,`b`.`itemFk` AS `itemFk`,`i`.`longName` AS `longName`,`s`.`name` AS `supplier`,`b`.`entryFk` AS `entryFk`,`tr`.`landed` AS `landed`,-(least(`b`.`quantity`,0)) AS `out`,greatest(`b`.`quantity`,0) AS `in`,`w`.`name` AS `almacen` from ((((((`buy` `b` join `item` `i` on((`i`.`id` = `b`.`itemFk`))) join `packaging` `p` on((`p`.`itemFk` = `i`.`id`))) join `entry` `e` on((`e`.`id` = `b`.`entryFk`))) join `supplier` `s` on((`s`.`id` = `e`.`supplierFk`))) join `travel` `tr` on((`tr`.`id` = `e`.`travelFk`))) join `warehouse` `w` on((`w`.`id` = `tr`.`warehouseInFk`))) where `p`.`isPackageReturnable` */; +/*!50001 VIEW `supplierPackaging` AS select `e`.`supplierFk` AS `supplierFk`,`b`.`itemFk` AS `itemFk`,`i`.`longName` AS `longName`,`s`.`name` AS `supplier`,`b`.`entryFk` AS `entryFk`,`tr`.`landed` AS `landed`,-(least(`b`.`quantity`,0)) AS `out`,greatest(`b`.`quantity`,0) AS `in`,`w`.`name` AS `almacen`,`b`.`buyingValue` AS `cost` from ((((((`buy` `b` join `item` `i` on((`i`.`id` = `b`.`itemFk`))) join `packaging` `p` on((`p`.`itemFk` = `i`.`id`))) join `entry` `e` on((`e`.`id` = `b`.`entryFk`))) join `supplier` `s` on((`s`.`id` = `e`.`supplierFk`))) join `travel` `tr` on((`tr`.`id` = `e`.`travelFk`))) join `warehouse` `w` on((`w`.`id` = `tr`.`warehouseInFk`))) where `p`.`isPackageReturnable` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -84055,6 +88667,25 @@ USE `vn`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; +-- +-- Final view structure for view `ticketLabel_Source` +-- + +/*!50001 DROP TABLE IF EXISTS `ticketLabel_Source`*/; +/*!50001 DROP VIEW IF EXISTS `ticketLabel_Source`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `ticketLabel_Source` AS select concat(`tc`.`collectionFk`,' ',`tc`.`wagon`,'-',`tc`.`level`) AS `level`,`t`.`id` AS `Id_Ticket`,(case when (`t`.`routeFk` is not null) then if(`agr`.`showAgencyName`,concat(right(left(`agr`.`name`,(locate(' ',`agr`.`name`) - 1)),2),'- R',right(`t`.`routeFk`,3)),`agr`.`name`) else if((`am`.`deliveryMethodFk` = 2),`zo`.`name`,`am`.`name`) end) AS `Agencia`,`t`.`clientFk` AS `Id_Cliente`,`t`.`notes` AS `Notas`,'CDT' AS `Sacador`,1 AS `ncarro`,if(hour(`t`.`shipped`),date_format(`t`.`shipped`,'%H:%i'),date_format(`zo`.`hour`,'%H:%i')) AS `horaagencia`,`t`.`shipped` AS `fecha`,if(((now() + interval 1 hour) > `ze`.`etc`),'!!!','') AS `urgente` from (((((((`vn`.`ticket` `t` join `vn`.`agencyMode` `am` on((`t`.`agencyModeFk` = `am`.`id`))) left join `vn`.`address` `a` on((`a`.`id` = `t`.`addressFk`))) left join `vn`.`route` `r` on((`t`.`routeFk` = `r`.`id`))) left join `vn`.`zone_ETD` `ze` on((`ze`.`zoneFk` = `t`.`zoneFk`))) left join `vn`.`ticketCollection` `tc` on((`tc`.`ticketFk` = `t`.`id`))) left join `vn`.`agencyMode` `agr` on((`r`.`agencyModeFk` = `agr`.`id`))) left join `vn`.`zone` `zo` on((`t`.`zoneFk` = `zo`.`id`))) where (`t`.`shipped` between `util`.`yesterday`() and `util`.`dayend`(curdate())) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + -- -- Final view structure for view `ticketLastUpdated` -- @@ -84093,6 +88724,25 @@ USE `vn`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; +-- +-- Final view structure for view `ticketLocation` +-- + +/*!50001 DROP TABLE IF EXISTS `ticketLocation`*/; +/*!50001 DROP VIEW IF EXISTS `ticketLocation`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `ticketLocation` AS select `tl`.`Id_Ticket` AS `ticketFk`,`tl`.`longitude` AS `longitude`,`tl`.`latitude` AS `latitude` from `vn2008`.`ticket_location` `tl` */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + -- -- Final view structure for view `ticketMRW` -- @@ -84145,7 +88795,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `ticketPackingList` AS select `t`.`nickname` AS `nickname`,`t`.`id` AS `ticketFk`,`am`.`name` AS `agencyMode`,`am`.`flag` AS `flag`,`p`.`name` AS `province`,`s`.`itemFk` AS `itemFk`,`s`.`concept` AS `concept`,`s`.`quantity` AS `quantity` from ((((`ticket` `t` join `address` `a` on((`a`.`id` = `t`.`addressFk`))) join `province` `p` on((`p`.`id` = `a`.`provinceFk`))) join `agencyMode` `am` on((`am`.`id` = `t`.`agencyModeFk`))) left join `sale` `s` on((`s`.`ticketFk` = `t`.`id`))) */; +/*!50001 VIEW `ticketPackingList` AS select `t`.`nickname` AS `nickname`,`t`.`id` AS `ticketFk`,`am`.`name` AS `agencyMode`,`am`.`flag` AS `flag`,`p`.`name` AS `province`,`s`.`itemFk` AS `itemFk`,`s`.`concept` AS `concept`,`s`.`quantity` AS `quantity`,`sv`.`litros` AS `litros` from (((((`ticket` `t` join `address` `a` on((`a`.`id` = `t`.`addressFk`))) join `province` `p` on((`p`.`id` = `a`.`provinceFk`))) join `agencyMode` `am` on((`am`.`id` = `t`.`agencyModeFk`))) left join `sale` `s` on((`s`.`ticketFk` = `t`.`id`))) left join `saleVolume` `sv` on((`sv`.`saleFk` = `s`.`id`))) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -84501,12 +89151,12 @@ USE `vn`; /*!50001 SET @saved_cs_client = @@character_set_client */; /*!50001 SET @saved_cs_results = @@character_set_results */; /*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `workerTimeControlUserInfo` AS select `u`.`id` AS `userFk`,`w`.`firstName` AS `name`,`w`.`lastName` AS `surname`,`u`.`name` AS `user`,`u`.`password` AS `password`,`u`.`bcryptPassword` AS `bcryptPassword`,`wd`.`departmentFk` AS `departmentFk`,left(`w`.`fi`,8) AS `dni` from ((`account`.`user` `u` join `vn`.`worker` `w` on((`w`.`userFk` = `u`.`id`))) left join `vn`.`workerDepartment` `wd` on((`wd`.`workerFk` = `w`.`id`))) */; +/*!50001 VIEW `workerTimeControlUserInfo` AS select `u`.`id` AS `userFk`,`w`.`firstName` AS `name`,`w`.`lastName` AS `surname`,`u`.`name` AS `user`,`u`.`password` AS `password`,`u`.`bcryptPassword` AS `bcryptPassword`,`wd`.`departmentFk` AS `departmentFk`,left(`c`.`fi`,8) AS `dni` from (((`account`.`user` `u` join `vn`.`worker` `w` on((`w`.`userFk` = `u`.`id`))) join `vn`.`client` `c` on((`c`.`id` = `u`.`id`))) left join `vn`.`workerDepartment` `wd` on((`wd`.`workerFk` = `w`.`id`))) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -84568,6 +89218,44 @@ USE `vn`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; +-- +-- Final view structure for view `workerWithoutDevice` +-- + +/*!50001 DROP TABLE IF EXISTS `workerWithoutDevice`*/; +/*!50001 DROP VIEW IF EXISTS `workerWithoutDevice`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `workerWithoutDevice` AS select `c`.`workerFk` AS `workerFk`,`cl`.`name` AS `Trabajador`,count(distinct `c`.`id`) AS `Colecciones` from ((`collection` `c` join `client` `cl` on((`cl`.`id` = `c`.`workerFk`))) left join `deviceProductionUser` `dpu` on((`dpu`.`userFk` = `c`.`workerFk`))) where ((`c`.`created` > curdate()) and isnull(`dpu`.`userFk`)) 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 */; + +-- +-- Final view structure for view `workerWithoutTractor` +-- + +/*!50001 DROP TABLE IF EXISTS `workerWithoutTractor`*/; +/*!50001 DROP VIEW IF EXISTS `workerWithoutTractor`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `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` > curdate())))) where ((`c`.`created` > curdate()) and isnull(`mw`.`workerFk`)) 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 */; + -- -- Final view structure for view `zoneEstimatedDelivery` -- @@ -84621,4 +89309,4 @@ USE `vncontrol`; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2021-05-25 10:34:01 +-- Dump completed on 2021-08-31 14:41:28 diff --git a/db/export-data.sh b/db/export-data.sh index 5292e8f6a5..96adc7ab68 100755 --- a/db/export-data.sh +++ b/db/export-data.sh @@ -40,6 +40,7 @@ TABLES=( vn alertLevel bookingPlanner + businessType cplusInvoiceType472 cplusInvoiceType477 cplusRectificationType diff --git a/db/tests/cache/last_buy_refresh.spec.js b/db/tests/cache/last_buy_refresh.spec.js index 0036e27620..71a9c3872d 100644 --- a/db/tests/cache/last_buy_refresh.spec.js +++ b/db/tests/cache/last_buy_refresh.spec.js @@ -3,22 +3,18 @@ const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; describe('last_buy_refresh()', () => { it(`should store some data on cache.last_buy`, async() => { - let stmts = []; - let stmt; + const stmts = []; stmts.push('START TRANSACTION'); - stmt = new ParameterizedSQL('CALL cache.last_buy_refresh(true)'); - stmts.push(stmt); - - let lastBuyTableIndex = stmts.push(`SELECT * FROM cache.last_buy ORDER BY item_id ASC`) - 1; + const lastBuyTableIndex = stmts.push(`SELECT * FROM cache.last_buy ORDER BY item_id ASC`) - 1; stmts.push('ROLLBACK'); - let sql = ParameterizedSQL.join(stmts, ';'); - let result = await app.models.Ticket.rawStmt(sql); + const sql = ParameterizedSQL.join(stmts, ';'); + const result = await app.models.Ticket.rawStmt(sql); - let lastBuyTable = result[lastBuyTableIndex]; + const lastBuyTable = result[lastBuyTableIndex]; expect(lastBuyTable.length).toEqual(12); diff --git a/db/tests/vn/ticketCalculateClon.spec.js b/db/tests/vn/ticketCalculateClon.spec.js index 4015d57dbe..03814682d6 100644 --- a/db/tests/vn/ticketCalculateClon.spec.js +++ b/db/tests/vn/ticketCalculateClon.spec.js @@ -10,7 +10,7 @@ describe('ticket ticketCalculateClon()', () => { stmts.push('START TRANSACTION'); let params = { - clientFk: 101, + clientFk: 1101, shipped: today, warehouseFk: 1, companyFk: 442, @@ -59,7 +59,7 @@ describe('ticket ticketCalculateClon()', () => { stmts.push('START TRANSACTION'); let params = { - clientFk: 101, + clientFk: 1101, shipped: today, warehouseFk: 1, companyFk: 442, diff --git a/db/tests/vn/ticketCreateWithUser.spec.js b/db/tests/vn/ticketCreateWithUser.spec.js index 6728eb2da3..1c13be1b3c 100644 --- a/db/tests/vn/ticketCreateWithUser.spec.js +++ b/db/tests/vn/ticketCreateWithUser.spec.js @@ -10,7 +10,7 @@ describe('ticket ticketCreateWithUser()', () => { stmts.push('START TRANSACTION'); let params = { - clientFk: 101, + clientFk: 1101, shipped: today, warehouseFk: 1, companyFk: 442, @@ -59,7 +59,7 @@ describe('ticket ticketCreateWithUser()', () => { stmts.push('START TRANSACTION'); let params = { - clientFk: 101, + clientFk: 1101, shipped: today, warehouseFk: 1, companyFk: 442, @@ -109,7 +109,7 @@ describe('ticket ticketCreateWithUser()', () => { stmts.push('START TRANSACTION'); let params = { - clientFk: 101, + clientFk: 1101, shipped: today, warehouseFk: 1, companyFk: 442, @@ -156,7 +156,7 @@ describe('ticket ticketCreateWithUser()', () => { stmts.push('START TRANSACTION'); let params = { - clientFk: 101, + clientFk: 1101, shipped: today, warehouseFk: 1, companyFk: 442, diff --git a/db/tests/vn/ticket_componentMakeUpdate.spec.js b/db/tests/vn/ticket_componentMakeUpdate.spec.js index 4954c44f4c..a059f1060c 100644 --- a/db/tests/vn/ticket_componentMakeUpdate.spec.js +++ b/db/tests/vn/ticket_componentMakeUpdate.spec.js @@ -9,7 +9,7 @@ xdescribe('ticket_componentMakeUpdate()', () => { let params = { ticketId: 11, - clientId: 102, + clientId: 1102, agencyModeId: 2, addressId: 122, zoneId: 3, @@ -68,7 +68,7 @@ xdescribe('ticket_componentMakeUpdate()', () => { let params = { ticketId: 11, - clientId: 102, + clientId: 1102, agencyModeId: 2, addressId: 122, zoneId: 3, diff --git a/db/tests/vn/timeBusiness_calculateByUser.spec.js b/db/tests/vn/timeBusiness_calculateByUser.spec.js index 0b09447ef5..441f567ac4 100644 --- a/db/tests/vn/timeBusiness_calculateByUser.spec.js +++ b/db/tests/vn/timeBusiness_calculateByUser.spec.js @@ -14,7 +14,7 @@ describe('timeBusiness_calculateByUser()', () => { stmts.push('START TRANSACTION'); let params = { - workerID: 106, + workerID: 1106, start: start, end: end }; diff --git a/db/tests/vn/timeControl_calculateByUser.spec.js b/db/tests/vn/timeControl_calculateByUser.spec.js index ac442ab7b3..2aa16c7a43 100644 --- a/db/tests/vn/timeControl_calculateByUser.spec.js +++ b/db/tests/vn/timeControl_calculateByUser.spec.js @@ -23,7 +23,7 @@ describe('timeControl_calculateByUser()', () => { `); let params = { - workerID: 106, + workerID: 1106, start: start, end: end }; @@ -71,7 +71,7 @@ describe('timeControl_calculateByUser()', () => { tmp.timeBusinessCalculate `); - const workerID = 107; + const workerID = 1107; stmt = new ParameterizedSQL(` INSERT INTO vn.workerTimeControl(userFk, timed, manual, direction) diff --git a/db/tests/vn/workerTimeControlCheck.spec.js b/db/tests/vn/workerTimeControlCheck.spec.js index f70a0b1c3c..6838665f14 100644 --- a/db/tests/vn/workerTimeControlCheck.spec.js +++ b/db/tests/vn/workerTimeControlCheck.spec.js @@ -6,7 +6,7 @@ xdescribe('worker workerTimeControl_check()', () => { it(`should throw an error if the worker can't sign on that tablet`, async() => { let stmts = []; let stmt; - const workerId = 110; + const workerId = 1110; const tabletId = 2; let err; stmts.push('START TRANSACTION'); @@ -31,7 +31,7 @@ xdescribe('worker workerTimeControl_check()', () => { it('should check that the worker can sign on that tablet', async() => { let stmts = []; let stmt; - const workerId = 110; + const workerId = 1110; const tabletId = 1; let err; stmts.push('START TRANSACTION'); @@ -55,7 +55,7 @@ xdescribe('worker workerTimeControl_check()', () => { it('should throw an error if the worker with a special category has not finished the 9h break', async() => { // dayBreak to 9h in postgresql.professional_category - const workerId = 110; + const workerId = 1110; const tabletId = 1; let stmts = []; let stmt; @@ -92,7 +92,7 @@ xdescribe('worker workerTimeControl_check()', () => { it('should check f the worker with a special category has finished the 9h break', async() => { // dayBreak to 9h in postgresql.professional_category - const workerId = 110; + const workerId = 1110; const tabletId = 1; let stmts = []; let stmt; @@ -127,7 +127,7 @@ xdescribe('worker workerTimeControl_check()', () => { }); it('should throw an error if the worker has not finished the 12h break', async() => { - const workerId = 109; + const workerId = 1109; const tabletId = 1; let stmts = []; let stmt; @@ -163,7 +163,7 @@ xdescribe('worker workerTimeControl_check()', () => { }); it('should throw an error if the worker has finished the 12h break', async() => { - const workerId = 109; + const workerId = 1109; const tabletId = 1; let stmts = []; let stmt; @@ -198,7 +198,7 @@ xdescribe('worker workerTimeControl_check()', () => { }); it('should throw an error if the worker has odd entry records', async() => { - const workerId = 109; + const workerId = 1109; const tabletId = 1; let stmts = []; let stmt; @@ -231,7 +231,7 @@ xdescribe('worker workerTimeControl_check()', () => { }); it('should throw an error if the worker try to sign on a holiday day', async() => { - const workerId = 109; + const workerId = 1109; const tabletId = 1; let stmts = []; let stmt; @@ -274,7 +274,7 @@ xdescribe('worker workerTimeControl_check()', () => { }); it('should throw an error if the worker try to sign with your contract ended', async() => { - const workerId = 109; + const workerId = 1109; const tabletId = 1; let stmts = []; let stmt; @@ -316,7 +316,7 @@ xdescribe('worker workerTimeControl_check()', () => { }); it('should throw an error if the worker has not finished the 36h weekly break', async() => { - const workerId = 109; + const workerId = 1109; const tabletId = 1; let stmts = []; let stmt; @@ -377,7 +377,7 @@ xdescribe('worker workerTimeControl_check()', () => { }); it('should check if the worker has finished the 36h weekly break', async() => { - const workerId = 109; + const workerId = 1109; const tabletId = 1; let stmts = []; let stmt; @@ -423,7 +423,7 @@ xdescribe('worker workerTimeControl_check()', () => { }); it('should throw an error if the worker has not finished the 72h biweekly break', async() => { - const workerId = 109; + const workerId = 1109; const tabletId = 1; let stmts = []; let stmt; @@ -505,7 +505,7 @@ xdescribe('worker workerTimeControl_check()', () => { }); it('should check if the worker has finished the 72h biweekly break', async() => { - const workerId = 109; + const workerId = 1109; const tabletId = 1; let stmts = []; let stmt; diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index f65ebc95d2..f63d67f8ba 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -123,6 +123,7 @@ export default { addProvince: 'vn-autocomplete[ng-model="$ctrl.location.provinceFk"] vn-icon-button[icon="add_circle"]', addCity: 'vn-autocomplete[ng-model="$ctrl.location.townFk"] vn-icon-button[icon="add_circle"]', newProvinceName: 'vn-textfield[ng-model="$ctrl.province.name"]', + newProvinceAutonomy: 'vn-autocomplete[ng-model="$ctrl.province.autonomyFk"]', newCityName: 'vn-textfield[ng-model="$ctrl.city.name"]', newCityProvince: 'vn-autocomplete[ng-model="$ctrl.city.provinceFk"]', newPostcode: 'vn-textfield[ng-model="$ctrl.location.code"]', @@ -130,7 +131,6 @@ export default { city: 'vn-client-create vn-datalist[ng-model="$ctrl.client.city"]', province: 'vn-autocomplete[ng-model="$ctrl.client.provinceFk"]', country: 'vn-client-create vn-autocomplete[ng-model="$ctrl.client.countryFk"]', - dialogCountry: 'vn-autocomplete[ng-model="$ctrl.province.countryFk"]', userName: 'vn-client-create vn-textfield[ng-model="$ctrl.client.userName"]', email: 'vn-client-create vn-textfield[ng-model="$ctrl.client.email"]', salesPerson: 'vn-client-create vn-autocomplete[ng-model="$ctrl.client.salesPersonFk"]', @@ -152,6 +152,7 @@ export default { salesPerson: 'vn-client-basic-data vn-autocomplete[ng-model="$ctrl.client.salesPersonFk"]', channel: 'vn-client-basic-data vn-autocomplete[ng-model="$ctrl.client.contactChannelFk"]', transferor: 'vn-client-basic-data vn-autocomplete[ng-model="$ctrl.client.transferorFk"]', + businessType: 'vn-client-basic-data vn-autocomplete[ng-model="$ctrl.client.businessTypeFk"]', saveButton: 'vn-client-basic-data button[type=submit]' }, clientFiscalData: { @@ -185,9 +186,10 @@ export default { receivedB2BVNLCheckbox: 'vn-client-billing-data vn-check[label="Received B2B VNL"]', swiftBic: 'vn-client-billing-data vn-autocomplete[ng-model="$ctrl.client.bankEntityFk"]', newBankEntityButton: 'vn-client-billing-data vn-icon-button[vn-tooltip="New bank entity"] > button', - newBankEntityName: '.vn-dialog.shown vn-textfield[ng-model="$ctrl.newBankEntity.name"]', - newBankEntityBIC: '.vn-dialog.shown vn-textfield[ng-model="$ctrl.newBankEntity.bic"]', - newBankEntityCode: '.vn-dialog.shown vn-textfield[ng-model="$ctrl.newBankEntity.id"]', + newBankEntityName: '.vn-dialog.shown vn-textfield[ng-model="$ctrl.data.name"]', + newBankEntityBIC: '.vn-dialog.shown vn-textfield[ng-model="$ctrl.data.bic"]', + newBankEntityCountry: '.vn-dialog.shown vn-autocomplete[ng-model="$ctrl.data.countryFk"]', + newBankEntityCode: '.vn-dialog.shown vn-textfield[ng-model="$ctrl.data.id"]', acceptBankEntityButton: '.vn-dialog.shown button[response="accept"]', saveButton: 'vn-client-billing-data button[type=submit]', watcher: 'vn-client-billing-data vn-watcher' @@ -257,7 +259,9 @@ export default { }, clientLog: { lastModificationPreviousValue: 'vn-client-log vn-table vn-td.before', - lastModificationCurrentValue: 'vn-client-log vn-table vn-td.after' + lastModificationCurrentValue: 'vn-client-log vn-table vn-td.after', + penultimateModificationPreviousValue: 'vn-client-log vn-table vn-tr:nth-child(2) vn-td.before', + penultimateModificationCurrentValue: 'vn-client-log vn-table vn-tr:nth-child(2) vn-td.after' }, clientBalance: { @@ -320,7 +324,6 @@ export default { idCheckbox: '.vn-popover.shown vn-horizontal:nth-child(1) > vn-check', stemsCheckbox: '.vn-popover.shown vn-horizontal:nth-child(2) > vn-check', sizeCheckbox: '.vn-popover.shown vn-horizontal:nth-child(3) > vn-check', - nicheCheckbox: '.vn-popover.shown vn-horizontal:nth-child(4) > vn-check', typeCheckbox: '.vn-popover.shown vn-horizontal:nth-child(5) > vn-check', categoryCheckbox: '.vn-popover.shown vn-horizontal:nth-child(6) > vn-check', intrastadCheckbox: '.vn-popover.shown vn-horizontal:nth-child(7) > vn-check', @@ -417,17 +420,6 @@ export default { submitBarcodesButton: 'vn-item-barcode button[type=submit]', firstCodeRemoveButton: 'vn-item-barcode vn-horizontal:nth-child(1) vn-icon[icon="delete"]' }, - itemNiches: { - addNicheButton: 'vn-item-niche vn-icon[icon="add_circle"]', - firstWarehouse: 'vn-item-niche vn-autocomplete[ng-model="niche.warehouseFk"]', - firstCode: 'vn-item-niche vn-horizontal:nth-child(1) vn-textfield[ng-model="niche.code"]', - secondWarehouse: 'vn-item-niche vn-horizontal:nth-child(2) > vn-autocomplete[ng-model="niche.warehouseFk"]', - secondCode: 'vn-item-niche vn-horizontal:nth-child(2) vn-textfield[ng-model="niche.code"]', - secondNicheRemoveButton: 'vn-item-niche vn-horizontal:nth-child(2) > vn-none > vn-icon-button[icon="delete"]', - thirdWarehouse: 'vn-item-niche vn-horizontal:nth-child(3) > vn-autocomplete[ng-model="niche.warehouseFk"]', - thirdCode: 'vn-item-niche vn-horizontal:nth-child(3) vn-textfield[ng-model="niche.code"]', - submitNichesButton: 'vn-item-niche button[type=submit]' - }, itemBotanical: { genus: 'vn-item-botanical vn-autocomplete[ng-model="$ctrl.botanical.genusFk"]', species: 'vn-item-botanical vn-autocomplete[ng-model="$ctrl.botanical.specieFk"]', @@ -437,7 +429,6 @@ export default { basicData: 'vn-item-summary [name="basicData"]', vat: 'vn-item-summary [name="tax"]', tags: 'vn-item-summary [name="tags"]', - niche: 'vn-item-summary [name="niche"]', botanical: 'vn-item-summary [name="botanical"]', barcode: 'vn-item-summary [name="barcode"]' }, @@ -461,8 +452,8 @@ export default { itemDescriptorPopover: '.vn-popover.shown vn-item-descriptor', itemDescriptorPopoverItemDiaryButton: 'vn-item-descriptor a[href="#!/item/2/diary?warehouseFk=5&lineFk=16"]', popoverDiaryButton: '.vn-popover.shown vn-item-descriptor vn-icon[icon="icon-transaction"]', - firstSaleQuantity: 'vn-ticket-summary [name="sales"] vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(4)', - firstSaleDiscount: 'vn-ticket-summary [name="sales"] vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(7)', + firstSaleQuantity: 'vn-ticket-summary [name="sales"] vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(5)', + firstSaleDiscount: 'vn-ticket-summary [name="sales"] vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(8)', invoiceOutRef: 'vn-ticket-summary > vn-card > vn-horizontal > vn-one:nth-child(1) > vn-label-value:nth-child(7) > section > span', setOk: 'vn-ticket-summary vn-button[label="SET OK"] > button', descriptorTicketId: 'vn-ticket-descriptor > vn-descriptor-content > div > div.body > div.top > div' @@ -481,7 +472,7 @@ export default { thirdTicketCheckbox: 'vn-ticket-index vn-tbody > a:nth-child(3) > vn-td:nth-child(1) > vn-check', sixthTicketCheckbox: 'vn-ticket-index vn-tbody > a:nth-child(6) > vn-td:nth-child(1) > vn-check', payoutButton: 'vn-ticket-index vn-button[icon="icon-recovery"]', - payoutCompany: '.vn-dialog vn-autocomplete[ng-model="$ctrl.receipt.companyFk"]', + payoutCompany: '.vn-dialog vn-autocomplete[ng-model="$ctrl.companyFk"]', payoutBank: '.vn-dialog vn-autocomplete[ng-model="$ctrl.bankFk"]', payoutDescription: 'vn-textfield[ng-model="$ctrl.receipt.description"]', submitPayout: '.vn-dialog button[response="accept"]', @@ -565,13 +556,13 @@ export default { moreMenuUpdateDiscountInput: 'vn-input-number[ng-model="$ctrl.edit.discount"] input', transferQuantityInput: '.vn-popover.shown vn-table > div > vn-tbody > vn-tr > vn-td-editable > span > text', transferQuantityCell: '.vn-popover.shown vn-table > div > vn-tbody > vn-tr > vn-td-editable', - firstSaleId: 'vn-ticket-sale vn-tbody > vn-tr:nth-child(1) > vn-td:nth-child(5) > span', + firstSaleId: 'vn-ticket-sale vn-tbody > vn-tr:nth-child(1) > vn-td:nth-child(6) > span', firstSaleClaimIcon: 'vn-ticket-sale vn-table vn-tbody > vn-tr:nth-child(1) vn-icon[icon="icon-claims"]', firstSaleDescriptorImage: '.vn-popover.shown vn-item-descriptor img', firstSaleThumbnailImage: 'vn-ticket-sale:nth-child(1) vn-tr:nth-child(1) vn-td:nth-child(3) > img', firstSaleZoomedImage: 'body > div > div > img', firstSaleQuantity: 'vn-ticket-sale [ng-model="sale.quantity"]', - firstSaleQuantityCell: 'vn-ticket-sale vn-tr:nth-child(1) > vn-td-editable:nth-child(6)', + firstSaleQuantityCell: 'vn-ticket-sale vn-tr:nth-child(1) > vn-td-editable:nth-child(7)', firstSalePrice: 'vn-ticket-sale vn-table vn-tr:nth-child(1) > vn-td:nth-child(9) > span', firstSalePriceInput: '.vn-popover.shown input[ng-model="$ctrl.field"]', firstSaleDiscount: 'vn-ticket-sale vn-table vn-tr:nth-child(1) > vn-td:nth-child(10) > span', @@ -584,8 +575,8 @@ export default { secondSaleId: 'vn-ticket-sale:nth-child(2) vn-td-editable:nth-child(4) text > span', secondSaleIdAutocomplete: 'vn-ticket-sale vn-tr:nth-child(2) vn-autocomplete[ng-model="sale.itemFk"]', secondSaleQuantity: 'vn-ticket-sale vn-table vn-tr:nth-child(2) vn-input-number', - secondSaleQuantityCell: 'vn-ticket-sale > div > vn-card > vn-table > div > vn-tbody > vn-tr:nth-child(2) > vn-td-editable:nth-child(6)', - secondSaleConceptCell: 'vn-ticket-sale vn-tbody > :nth-child(2) > :nth-child(7)', + secondSaleQuantityCell: 'vn-ticket-sale > div > vn-card > vn-table > div > vn-tbody > vn-tr:nth-child(2) > vn-td-editable:nth-child(7)', + secondSaleConceptCell: 'vn-ticket-sale vn-tbody > :nth-child(2) > :nth-child(8)', secondSaleConceptInput: 'vn-ticket-sale vn-tbody > :nth-child(2) > vn-td-editable.ng-isolate-scope.selected vn-textfield', totalImport: 'vn-ticket-sale vn-one.taxes > p:nth-child(3) > strong', selectAllSalesCheckbox: 'vn-ticket-sale vn-thead vn-check', @@ -646,6 +637,12 @@ export default { saveServiceButton: 'button[type=submit]', saveServiceTypeButton: '.vn-dialog.shown tpl-buttons > button' }, + ticketDms: { + import: 'vn-ticket-dms-index vn-button[icon="file_copy"]', + document: 'vn-autocomplete[ng-model="$ctrl.dmsId"]', + saveImport: 'button[response="accept"]', + anyDocument: 'vn-ticket-dms-index > vn-data-viewer vn-tbody vn-tr' + }, createStateView: { state: 'vn-autocomplete[ng-model="$ctrl.stateFk"]', worker: 'vn-autocomplete[ng-model="$ctrl.workerFk"]', @@ -906,6 +903,19 @@ export default { invoiceOutIndex: { topbarSearch: 'vn-searchbar', searchResult: 'vn-invoice-out-index vn-card > vn-table > div > vn-tbody > a.vn-tr', + createInvoice: 'vn-invoice-out-index > div > vn-vertical > vn-button > button vn-icon[icon="add"]', + createManualInvoice: 'vn-item[name="manualInvoice"]', + createGlobalInvoice: 'vn-item[name="globalInvoice"]', + manualInvoiceForm: '.vn-invoice-out-manual', + manualInvoiceTicket: 'vn-autocomplete[ng-model="$ctrl.invoice.ticketFk"]', + manualInvoiceClient: 'vn-autocomplete[ng-model="$ctrl.invoice.clientFk"]', + manualInvoiceSerial: 'vn-autocomplete[ng-model="$ctrl.invoice.serial"]', + manualInvoiceTaxArea: 'vn-autocomplete[ng-model="$ctrl.invoice.taxArea"]', + saveInvoice: 'button[response="accept"]', + globalInvoiceForm: '.vn-invoice-out-global-invoicing', + globalInvoiceDate: '[ng-model="$ctrl.invoice.invoiceDate"]', + globalInvoiceFromClient: '[ng-model="$ctrl.invoice.fromClientId"]', + globalInvoiceToClient: '[ng-model="$ctrl.invoice.toClientId"]', }, invoiceOutDescriptor: { moreMenu: 'vn-invoice-out-descriptor vn-icon-button[icon=more_vert]', @@ -924,12 +934,15 @@ export default { ticketTwo: 'vn-invoice-out-summary > vn-card > vn-horizontal > vn-auto > vn-table > div > vn-tbody > vn-tr:nth-child(2)' }, invoiceInSummary: { + totalTaxableBase: 'vn-invoice-in-summary > vn-card > vn-horizontal > vn-auto > vn-horizontal > vn-one.taxes > span', supplierRef: 'vn-invoice-in-summary vn-label-value:nth-child(2) > section > span' }, invoiceInDescriptor: { + summaryIcon: 'vn-invoice-in-descriptor a[title="Preview"]', moreMenu: 'vn-invoice-in-descriptor vn-icon-button[icon=more_vert]', moreMenuDeleteInvoiceIn: '.vn-menu [name="deleteInvoice"]', - acceptDeleteButton: '.vn-confirm.shown button[response="accept"]' + moreMenuCloneInvoiceIn: '.vn-menu [name="cloneInvoice"]', + acceptButton: '.vn-confirm.shown button[response="accept"]' }, invoiceInBasicData: { issued: 'vn-invoice-in-basic-data vn-date-picker[ng-model="$ctrl.invoiceIn.issued"]', @@ -942,6 +955,17 @@ export default { company: 'vn-invoice-in-basic-data vn-autocomplete[ng-model="$ctrl.invoiceIn.companyFk"]', save: 'vn-invoice-in-basic-data button[type=submit]' }, + invoiceInTax: { + addTaxButton: 'vn-invoice-in-tax vn-icon-button[icon="add_circle"]', + thirdExpence: 'vn-invoice-in-tax vn-horizontal:nth-child(3) > vn-autocomplete[ng-model="invoiceInTax.expenseFk"]', + thirdTaxableBase: 'vn-invoice-in-tax vn-horizontal:nth-child(3) > vn-input-number[ng-model="invoiceInTax.taxableBase"]', + thirdTaxType: 'vn-invoice-in-tax vn-horizontal:nth-child(3) > vn-autocomplete[ng-model="invoiceInTax.taxTypeSageFk"]', + thirdTransactionType: 'vn-invoice-in-tax vn-horizontal:nth-child(3) > vn-autocomplete[ng-model="invoiceInTax.transactionTypeSageFk"]', + thirdRate: 'vn-invoice-in-tax > form > vn-card > vn-horizontal:nth-child(3) > vn-textfield', + thirdDeleteButton: 'vn-invoice-in-tax vn-horizontal:nth-child(3) vn-icon[icon="delete"]', + saveButton: 'vn-invoice-in-tax vn-submit', + + }, travelIndex: { anySearchResult: 'vn-travel-index vn-tbody > a', firstSearchResult: 'vn-travel-index vn-tbody > a:nth-child(1)', @@ -982,7 +1006,7 @@ export default { newThermographId: 'vn-textfield[ng-model="$ctrl.newThermograph.thermographId"]', newThermographModel: 'vn-autocomplete[ng-model="$ctrl.newThermograph.model"]', newThermographWarehouse: 'vn-autocomplete[ng-model="$ctrl.newThermograph.warehouseId"]', - newThermographTemperature: 'vn-autocomplete[ng-model="$ctrl.newThermograph.temperature"]', + newThermographTemperature: 'vn-autocomplete[ng-model="$ctrl.newThermograph.temperatureFk"]', createThermographButton: 'form button[response="accept"]', uploadIcon: 'vn-travel-thermograph-create vn-icon[icon="icon-attach"]', createdThermograph: 'vn-travel-thermograph-index vn-tbody > vn-tr', diff --git a/e2e/paths/02-client/01_create_client.spec.js b/e2e/paths/02-client/01_create_client.spec.js index ae002b0ea4..5860eca49d 100644 --- a/e2e/paths/02-client/01_create_client.spec.js +++ b/e2e/paths/02-client/01_create_client.spec.js @@ -42,7 +42,7 @@ describe('Client create path', () => { await page.waitToClick(selectors.createClientView.addPostCode); await page.waitToClick(selectors.createClientView.addProvince); await page.write(selectors.createClientView.newProvinceName, 'Massachusetts'); - await page.autocompleteSearch(selectors.createClientView.dialogCountry, 'España'); + await page.autocompleteSearch(selectors.createClientView.newProvinceAutonomy, 'Autonomy one'); await page.waitToClick(selectors.createClientView.saveNewProvicenButton); const message = await page.waitForSnackbar(); diff --git a/e2e/paths/02-client/02_edit_basic_data.spec.js b/e2e/paths/02-client/02_edit_basic_data.spec.js index f35483edfc..3a476e54fa 100644 --- a/e2e/paths/02-client/02_edit_basic_data.spec.js +++ b/e2e/paths/02-client/02_edit_basic_data.spec.js @@ -35,6 +35,7 @@ describe('Client Edit basicData path', () => { await page.write(selectors.clientBasicData.email, 'PWallace@verdnatura.es'); await page.autocompleteSearch(selectors.clientBasicData.channel, 'Rumors on the streets'); await page.autocompleteSearch(selectors.clientBasicData.transferor, 'Max Eisenhardt'); + await page.autocompleteSearch(selectors.clientBasicData.businessType, 'Eventos'); await page.waitToClick(selectors.clientBasicData.saveButton); const message = await page.waitForSnackbar(); @@ -55,6 +56,13 @@ describe('Client Edit basicData path', () => { expect(result).toEqual('David Haller'); }); + it('should confirm the business type have been edited', async() => { + const result = await page + .waitToGetProperty(selectors.clientBasicData.businessType, 'value'); + + expect(result).toEqual('Eventos'); + }); + it('should confirm the email have been edited', async() => { const result = await page .waitToGetProperty(selectors.clientBasicData.email, 'value'); diff --git a/e2e/paths/02-client/04_edit_billing_data.spec.js b/e2e/paths/02-client/04_edit_billing_data.spec.js index 24ee3c29ae..6bc48093e3 100644 --- a/e2e/paths/02-client/04_edit_billing_data.spec.js +++ b/e2e/paths/02-client/04_edit_billing_data.spec.js @@ -31,12 +31,12 @@ describe('Client Edit billing data path', () => { expect(message.text).toContain('That payment method requires an IBAN'); }); - // 2256: Windows (hidden mode): Entity code doesn't get the focus, '9999' is written in entity name. - xit(`should create a new BIC code`, async() => { + it(`should create a new BIC code`, async() => { await page.waitToClick(selectors.clientBillingData.newBankEntityButton); await page.write(selectors.clientBillingData.newBankEntityName, 'Gotham City Bank'); - await page.write(selectors.clientBillingData.newBankEntityCode, '9999'); await page.write(selectors.clientBillingData.newBankEntityBIC, 'GTHMCT'); + await page.autocompleteSearch(selectors.clientBillingData.newBankEntityCountry, 'España'); + await page.write(selectors.clientBillingData.newBankEntityCode, '9999'); await page.waitToClick(selectors.clientBillingData.acceptBankEntityButton); await page.waitForTextInField(selectors.clientBillingData.swiftBic, 'Gotham City Bank'); const newcode = await page.waitToGetProperty(selectors.clientBillingData.swiftBic, 'value'); @@ -44,7 +44,7 @@ describe('Client Edit billing data path', () => { expect(newcode).toEqual('GTHMCT Gotham City Bank'); }); - xit(`should confirm the IBAN pay method was sucessfully saved`, async() => { + it(`should confirm the IBAN pay method was sucessfully saved`, async() => { const payMethod = await page.waitToGetProperty(selectors.clientBillingData.payMethod, 'value'); expect(payMethod).toEqual('PayMethod with IBAN'); diff --git a/e2e/paths/02-client/07_edit_web_access.spec.js b/e2e/paths/02-client/07_edit_web_access.spec.js index b1af956386..bcd476f6b5 100644 --- a/e2e/paths/02-client/07_edit_web_access.spec.js +++ b/e2e/paths/02-client/07_edit_web_access.spec.js @@ -16,8 +16,15 @@ describe('Client Edit web access path', () => { await browser.close(); }); - it(`should uncheck the Enable web access checkbox and update the name`, async() => { + it('should uncheck the Enable web access checkbox', async() => { await page.waitToClick(selectors.clientWebAccess.enableWebAccessCheckbox); + await page.waitToClick(selectors.clientWebAccess.saveButton); + const message = await page.waitForSnackbar(); + + expect(message.text).toContain('Data saved!'); + }); + + it(`should update the name`, async() => { await page.clearInput(selectors.clientWebAccess.userName); await page.write(selectors.clientWebAccess.userName, 'Hulk'); await page.waitToClick(selectors.clientWebAccess.saveButton); @@ -26,9 +33,8 @@ describe('Client Edit web access path', () => { expect(message.text).toContain('Data saved!'); }); - it('should confirm web access is now unchecked', async() => { - await page.accessToSection('client.card.basicData'); - await page.accessToSection('client.card.webAccess'); + it('should reload the section and confirm web access is now unchecked', async() => { + await page.reloadSection('client.card.webAccess'); const result = await page.checkboxState(selectors.clientWebAccess.enableWebAccessCheckbox); expect(result).toBe('unchecked'); @@ -44,13 +50,23 @@ describe('Client Edit web access path', () => { await page.accessToSection('client.card.log'); }); - it(`should confirm the log is showing the updated data for the client`, async() => { + it(`should confirm the last log is showing the updated client name and no modifications on the active checkbox`, async() => { let lastModificationPreviousValue = await page .waitToGetProperty(selectors.clientLog.lastModificationPreviousValue, 'innerText'); let lastModificationCurrentValue = await page .waitToGetProperty(selectors.clientLog.lastModificationCurrentValue, 'innerText'); - expect(lastModificationPreviousValue).toEqual('name BruceBanner active true'); + expect(lastModificationPreviousValue).toEqual('name BruceBanner active false'); expect(lastModificationCurrentValue).toEqual('name Hulk active false'); }); + + it(`should confirm the penultimate log is showing the updated avtive field and no modifications on the client name`, async() => { + let penultimateModificationPreviousValue = await page + .waitToGetProperty(selectors.clientLog.penultimateModificationPreviousValue, 'innerText'); + let penultimateModificationCurrentValue = await page + .waitToGetProperty(selectors.clientLog.penultimateModificationCurrentValue, 'innerText'); + + expect(penultimateModificationPreviousValue).toEqual('name BruceBanner active true'); + expect(penultimateModificationCurrentValue).toEqual('name BruceBanner active false'); + }); }); diff --git a/e2e/paths/04-item/01_summary.spec.js b/e2e/paths/04-item/01_summary.spec.js index d6f784be85..a7526accb5 100644 --- a/e2e/paths/04-item/01_summary.spec.js +++ b/e2e/paths/04-item/01_summary.spec.js @@ -40,13 +40,6 @@ describe('Item summary path', () => { expect(result).toContain('Brown'); }); - it(`should check the item summary preview shows fields from niche`, async() => { - await page.waitForTextInElement(selectors.itemSummary.niche, 'A1'); - const result = await page.waitToGetProperty(selectors.itemSummary.niche, 'innerText'); - - expect(result).toContain('A1'); - }); - it(`should check the item summary preview shows fields from botanical`, async() => { await page.waitForTextInElement(selectors.itemSummary.botanical, 'Abelia'); const result = await page.waitToGetProperty(selectors.itemSummary.botanical, 'innerText'); @@ -126,12 +119,6 @@ describe('Item summary path', () => { expect(result).toContain('Silver'); }); - it(`should check the item summary shows fields from niches section`, async() => { - const result = await page.waitToGetProperty(selectors.itemSummary.niche, 'innerText'); - - expect(result).toContain('One A4'); - }); - it(`should check the item summary shows fields from botanical section`, async() => { const result = await page.waitToGetProperty(selectors.itemSummary.botanical, 'innerText'); diff --git a/e2e/paths/04-item/06_botanical.spec.js b/e2e/paths/04-item/05_botanical.spec.js similarity index 100% rename from e2e/paths/04-item/06_botanical.spec.js rename to e2e/paths/04-item/05_botanical.spec.js diff --git a/e2e/paths/04-item/05_niche.spec.js b/e2e/paths/04-item/05_niche.spec.js deleted file mode 100644 index e3d1d70be9..0000000000 --- a/e2e/paths/04-item/05_niche.spec.js +++ /dev/null @@ -1,66 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Item create niche path', () => { - let browser; - let page; - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyer', 'item'); - await page.accessToSearchResult('Ranged weapon longbow 2m'); - await page.accessToSection('item.card.niche'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it(`should click create a new niche and delete a former one`, async() => { - await page.waitForTextInField(selectors.itemNiches.firstWarehouse, 'Warehouse One'); - await page.waitToClick(selectors.itemNiches.addNicheButton); - await page.waitToClick(selectors.itemNiches.secondNicheRemoveButton); - await page.autocompleteSearch(selectors.itemNiches.thirdWarehouse, 'Warehouse Two'); - await page.write(selectors.itemNiches.thirdCode, 'A44'); - await page.waitToClick(selectors.itemNiches.submitNichesButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it(`should confirm the first niche is the expected one`, async() => { - await page.reloadSection('item.card.niche'); - await page.waitForTextInField(selectors.itemNiches.firstWarehouse, 'Warehouse One'); - let result = await page - .waitToGetProperty(selectors.itemNiches.firstWarehouse, 'value'); - - expect(result).toEqual('Warehouse One'); - - result = await page - .waitToGetProperty(selectors.itemNiches.firstCode, 'value'); - - expect(result).toEqual('A11'); - }); - - it(`should confirm the second niche is the expected one`, async() => { - let result = await page - .waitToGetProperty(selectors.itemNiches.secondWarehouse, 'value'); - - expect(result).toEqual('Warehouse Three'); - result = await page - .waitToGetProperty(selectors.itemNiches.secondCode, 'value'); - - expect(result).toEqual('A33'); - }); - - it(`should confirm the third niche is the expected one`, async() => { - let result = await page - .waitToGetProperty(selectors.itemNiches.thirdWarehouse, 'value'); - - expect(result).toEqual('Warehouse Two'); - result = await page - .waitToGetProperty(selectors.itemNiches.thirdCode, 'value'); - - expect(result).toEqual('A44'); - }); -}); diff --git a/e2e/paths/04-item/07_barcode.spec.js b/e2e/paths/04-item/06_barcode.spec.js similarity index 100% rename from e2e/paths/04-item/07_barcode.spec.js rename to e2e/paths/04-item/06_barcode.spec.js diff --git a/e2e/paths/04-item/08_create_and_clone.spec.js b/e2e/paths/04-item/07_create_and_clone.spec.js similarity index 100% rename from e2e/paths/04-item/08_create_and_clone.spec.js rename to e2e/paths/04-item/07_create_and_clone.spec.js diff --git a/e2e/paths/04-item/09_regularize.spec.js b/e2e/paths/04-item/08_regularize.spec.js similarity index 100% rename from e2e/paths/04-item/09_regularize.spec.js rename to e2e/paths/04-item/08_regularize.spec.js diff --git a/e2e/paths/04-item/10_index.spec.js b/e2e/paths/04-item/09_index.spec.js similarity index 96% rename from e2e/paths/04-item/10_index.spec.js rename to e2e/paths/04-item/09_index.spec.js index 3d7ab16327..262627e996 100644 --- a/e2e/paths/04-item/10_index.spec.js +++ b/e2e/paths/04-item/09_index.spec.js @@ -26,7 +26,6 @@ describe('Item index path', () => { await page.waitToClick(selectors.itemsIndex.idCheckbox); await page.waitToClick(selectors.itemsIndex.stemsCheckbox); await page.waitToClick(selectors.itemsIndex.sizeCheckbox); - await page.waitToClick(selectors.itemsIndex.nicheCheckbox); await page.waitToClick(selectors.itemsIndex.typeCheckbox); await page.waitToClick(selectors.itemsIndex.categoryCheckbox); await page.waitToClick(selectors.itemsIndex.intrastadCheckbox); @@ -59,7 +58,6 @@ describe('Item index path', () => { await page.waitToClick(selectors.itemsIndex.idCheckbox); await page.waitToClick(selectors.itemsIndex.stemsCheckbox); await page.waitToClick(selectors.itemsIndex.sizeCheckbox); - await page.waitToClick(selectors.itemsIndex.nicheCheckbox); await page.waitToClick(selectors.itemsIndex.typeCheckbox); await page.waitToClick(selectors.itemsIndex.categoryCheckbox); await page.waitToClick(selectors.itemsIndex.intrastadCheckbox); diff --git a/e2e/paths/04-item/11_item_log.spec.js b/e2e/paths/04-item/10_item_log.spec.js similarity index 100% rename from e2e/paths/04-item/11_item_log.spec.js rename to e2e/paths/04-item/10_item_log.spec.js diff --git a/e2e/paths/04-item/12_descriptor.spec.js b/e2e/paths/04-item/11_descriptor.spec.js similarity index 100% rename from e2e/paths/04-item/12_descriptor.spec.js rename to e2e/paths/04-item/11_descriptor.spec.js diff --git a/e2e/paths/04-item/13_request.spec.js b/e2e/paths/04-item/12_request.spec.js similarity index 100% rename from e2e/paths/04-item/13_request.spec.js rename to e2e/paths/04-item/12_request.spec.js diff --git a/e2e/paths/04-item/14_fixedPrice.spec.js b/e2e/paths/04-item/13_fixedPrice.spec.js similarity index 100% rename from e2e/paths/04-item/14_fixedPrice.spec.js rename to e2e/paths/04-item/13_fixedPrice.spec.js diff --git a/e2e/paths/05-ticket/16_summary.spec.js b/e2e/paths/05-ticket/16_summary.spec.js index 36ff0f8b86..5095b6f3d2 100644 --- a/e2e/paths/05-ticket/16_summary.spec.js +++ b/e2e/paths/05-ticket/16_summary.spec.js @@ -26,7 +26,7 @@ describe('Ticket Summary path', () => { const result = await page.waitToGetProperty(selectors.ticketSummary.header, 'innerText'); expect(result).toContain(`Ticket #${ticketId}`); - expect(result).toContain('Bruce Banner (109)'); + expect(result).toContain('Bruce Banner (1109)'); expect(result).toContain('Somewhere in Thailand'); }); diff --git a/e2e/paths/05-ticket/18_index_payout.spec.js b/e2e/paths/05-ticket/18_index_payout.spec.js index 3d83e6fca0..343ec1f43a 100644 --- a/e2e/paths/05-ticket/18_index_payout.spec.js +++ b/e2e/paths/05-ticket/18_index_payout.spec.js @@ -31,7 +31,7 @@ describe('Ticket index payout path', () => { it('should search for tickets of the same client then open the payout form', async() => { await page.waitToClick(selectors.ticketsIndex.openAdvancedSearchButton); - await page.write(selectors.ticketsIndex.advancedSearchClient, '101'); + await page.write(selectors.ticketsIndex.advancedSearchClient, '1101'); await page.keyboard.press('Enter'); await page.waitForNumberOfElements(selectors.ticketsIndex.anySearchResult, 6); await page.waitToClick(selectors.ticketsIndex.firstTicketCheckbox); @@ -56,7 +56,7 @@ describe('Ticket index payout path', () => { it('should navigate to the client balance section and check a new balance line was entered', async() => { await page.waitToClick(selectors.globalItems.homeButton); await page.selectModule('client'); - await page.accessToSearchResult('101'); + await page.accessToSearchResult('1101'); await page.accessToSection('client.card.balance.index'); await page.waitForSelector('vn-client-balance-index vn-tbody > vn-tr'); let result = await page.countElement('vn-client-balance-index vn-tbody > vn-tr'); diff --git a/e2e/paths/05-ticket/19_dms.spec.js b/e2e/paths/05-ticket/19_dms.spec.js new file mode 100644 index 0000000000..be2ac43381 --- /dev/null +++ b/e2e/paths/05-ticket/19_dms.spec.js @@ -0,0 +1,49 @@ +import selectors from '../../helpers/selectors.js'; +import getBrowser from '../../helpers/puppeteer'; + +describe('Ticket DMS path', () => { + let browser; + let page; + + beforeAll(async() => { + browser = await getBrowser(); + page = browser.page; + await page.loginAndModule('employee', 'ticket'); + await page.accessToSearchResult('1'); + await page.accessToSection('ticket.card.dms.index'); + }); + + afterAll(async() => { + await browser.close(); + }); + + it('should import a document', async() => { + await page.waitToClick(selectors.ticketDms.import); + await page.autocompleteSearch(selectors.ticketDms.document, '1'); + await page.waitToClick(selectors.ticketDms.saveImport); + const message = await page.waitForSnackbar(); + + expect(message.text).toContain('Data saved!'); + }); + + it(`should check there's a listed document now`, async() => { + const result = await page.countElement(selectors.ticketDms.anyDocument); + + expect(result).toEqual(1); + }); + + it('should attempt to import an existing document on this ticket', async() => { + await page.waitToClick(selectors.ticketDms.import); + await page.autocompleteSearch(selectors.ticketDms.document, '1'); + await page.waitToClick(selectors.ticketDms.saveImport); + const message = await page.waitForSnackbar(); + + expect(message.text).toContain('This document already exists on this ticket'); + }); + + it(`should check there's still one document`, async() => { + const result = await page.countElement(selectors.ticketDms.anyDocument); + + expect(result).toEqual(1); + }); +}); diff --git a/e2e/paths/07-order/02_basic_data.spec.js b/e2e/paths/07-order/02_basic_data.spec.js index 6acf48f780..90eaf269e9 100644 --- a/e2e/paths/07-order/02_basic_data.spec.js +++ b/e2e/paths/07-order/02_basic_data.spec.js @@ -76,7 +76,7 @@ describe('Order edit basic data path', () => { it('should be able to modify all the properties', async() => { await page.autocompleteSearch(selectors.orderBasicData.client, 'Tony Stark'); await page.autocompleteSearch(selectors.orderBasicData.address, 'Tony Stark'); - await page.autocompleteSearch(selectors.orderBasicData.agency, 'Silla247'); + await page.autocompleteSearch(selectors.orderBasicData.agency, 'Other agency'); await page.write(selectors.orderBasicData.observation, 'my observation'); await page.waitToClick(selectors.orderBasicData.saveButton); const message = await page.waitForSnackbar(); @@ -89,14 +89,14 @@ describe('Order edit basic data path', () => { const result = await page .waitToGetProperty(selectors.orderBasicData.client, 'value'); - expect(result).toEqual('104: Tony Stark'); + expect(result).toEqual('1104: Tony Stark'); }); it('should now confirm the agency have been edited', async() => { const result = await page .waitToGetProperty(selectors.orderBasicData.agency, 'value'); - expect(result).toEqual('7: Silla247'); + expect(result).toEqual('Other agency'); }); it('should now confirm the observations have been edited', async() => { diff --git a/e2e/paths/09-invoice-in/02_descriptor.spec.js b/e2e/paths/09-invoice-in/02_descriptor.spec.js index 2386dada4f..02bbce7ac1 100644 --- a/e2e/paths/09-invoice-in/02_descriptor.spec.js +++ b/e2e/paths/09-invoice-in/02_descriptor.spec.js @@ -10,16 +10,30 @@ describe('InvoiceIn descriptor path', () => { page = browser.page; await page.loginAndModule('administrative', 'invoiceIn'); await page.accessToSearchResult('10'); + await page.accessToSection('invoiceIn.card.basicData'); }); afterAll(async() => { await browser.close(); }); - it('should delete the invoiceIn using the descriptor more menu', async() => { + it('should clone the invoiceIn using the descriptor more menu', async() => { + await page.waitToClick(selectors.invoiceInDescriptor.moreMenu); + await page.waitToClick(selectors.invoiceInDescriptor.moreMenuCloneInvoiceIn); + await page.waitToClick(selectors.invoiceInDescriptor.acceptButton); + const message = await page.waitForSnackbar(); + + expect(message.text).toContain('InvoiceIn cloned'); + }); + + it('should have been redirected to the created invoiceIn summary', async() => { + await page.waitForState('invoiceIn.card.summary'); + }); + + it('should delete the cloned invoiceIn using the descriptor more menu', async() => { await page.waitToClick(selectors.invoiceInDescriptor.moreMenu); await page.waitToClick(selectors.invoiceInDescriptor.moreMenuDeleteInvoiceIn); - await page.waitToClick(selectors.invoiceInDescriptor.acceptDeleteButton); + await page.waitToClick(selectors.invoiceInDescriptor.acceptButton); const message = await page.waitForSnackbar(); expect(message.text).toContain('InvoiceIn deleted'); diff --git a/e2e/paths/09-invoice-in/03_basic_data.spec.js b/e2e/paths/09-invoice-in/03_basic_data.spec.js index 1fac4f0d94..0c3f914e42 100644 --- a/e2e/paths/09-invoice-in/03_basic_data.spec.js +++ b/e2e/paths/09-invoice-in/03_basic_data.spec.js @@ -26,7 +26,7 @@ describe('InvoiceIn basic data path', () => { await page.write(selectors.invoiceInBasicData.supplierRef, '9999'); await page.pickDate(selectors.invoiceInBasicData.bookEntried, now); await page.pickDate(selectors.invoiceInBasicData.booked, now); - await page.autocompleteSearch(selectors.invoiceInBasicData.currency, 'Dollar USA'); + await page.autocompleteSearch(selectors.invoiceInBasicData.currency, 'USD'); await page.autocompleteSearch(selectors.invoiceInBasicData.company, 'ORN'); await page.waitToClick(selectors.invoiceInBasicData.save); const message = await page.waitForSnackbar(); @@ -52,7 +52,7 @@ describe('InvoiceIn basic data path', () => { const result = await page .waitToGetProperty(selectors.invoiceInBasicData.currency, 'value'); - expect(result).toEqual('Dollar USA'); + expect(result).toEqual('USD'); }); it(`should confirm the invoiceIn company was edited`, async() => { diff --git a/e2e/paths/09-invoice-in/04_tax.spec.js b/e2e/paths/09-invoice-in/04_tax.spec.js new file mode 100644 index 0000000000..364a25d7e4 --- /dev/null +++ b/e2e/paths/09-invoice-in/04_tax.spec.js @@ -0,0 +1,78 @@ +import selectors from '../../helpers/selectors.js'; +import getBrowser from '../../helpers/puppeteer'; + +describe('InvoiceIn tax path', () => { + let browser; + let page; + + beforeAll(async() => { + browser = await getBrowser(); + page = browser.page; + await page.loginAndModule('developer', 'invoiceIn'); + await page.accessToSearchResult('2'); + await page.accessToSection('invoiceIn.card.tax'); + }); + + afterAll(async() => { + await browser.close(); + }); + + it('should add a new tax', async() => { + await page.waitToClick(selectors.invoiceInTax.addTaxButton); + await page.autocompleteSearch(selectors.invoiceInTax.thirdExpence, '6210000567'); + await page.write(selectors.invoiceInTax.thirdTaxableBase, '100'); + await page.autocompleteSearch(selectors.invoiceInTax.thirdTaxType, '6'); + await page.autocompleteSearch(selectors.invoiceInTax.thirdTransactionType, 'Operaciones exentas'); + await page.waitToClick(selectors.invoiceInTax.saveButton); + const message = await page.waitForSnackbar(); + + expect(message.text).toContain('Data saved!'); + }); + + it('should navigate to the summary and check the taxable base sum is correct', async() => { + await page.waitToClick(selectors.invoiceInDescriptor.summaryIcon); + await page.waitForState('invoiceIn.card.summary'); + const result = await page.waitToGetProperty(selectors.invoiceInSummary.totalTaxableBase, 'innerText'); + + expect(result).toEqual('Taxable base €1,323.16'); + }); + + it('should navigate back to the tax section and check the reciently added line contains the expected expense', async() => { + await page.accessToSection('invoiceIn.card.tax'); + const result = await page.waitToGetProperty(selectors.invoiceInTax.thirdExpence, 'value'); + + expect(result).toEqual('6210000567: Alquiler VNH'); + }); + + it('should check the reciently added line contains the expected taxable base', async() => { + const result = await page.waitToGetProperty(selectors.invoiceInTax.thirdTaxableBase, 'value'); + + expect(result).toEqual('100'); + }); + + it('should check the reciently added line contains the expected tax type', async() => { + const result = await page.waitToGetProperty(selectors.invoiceInTax.thirdTaxType, 'value'); + + expect(result).toEqual('6: H.P. IVA 4% CEE'); + }); + + it('should check the reciently added line contains the expected transaction type', async() => { + const result = await page.waitToGetProperty(selectors.invoiceInTax.thirdTransactionType, 'value'); + + expect(result).toEqual('37: Operaciones exentas'); + }); + + it('should check the reciently added line contains the expected rate', async() => { + const result = await page.waitToGetProperty(selectors.invoiceInTax.thirdRate, 'value'); + + expect(result).toEqual('€4.00'); + }); + + it('should delete the added line', async() => { + await page.waitToClick(selectors.invoiceInTax.thirdDeleteButton); + await page.waitToClick(selectors.invoiceInTax.saveButton); + const message = await page.waitForSnackbar(); + + expect(message.text).toContain('Data saved!'); + }); +}); diff --git a/e2e/paths/09-invoice-out/03_manualInvoice.spec.js b/e2e/paths/09-invoice-out/03_manualInvoice.spec.js new file mode 100644 index 0000000000..396f84bfb5 --- /dev/null +++ b/e2e/paths/09-invoice-out/03_manualInvoice.spec.js @@ -0,0 +1,65 @@ +import selectors from '../../helpers/selectors.js'; +import getBrowser from '../../helpers/puppeteer'; + +describe('InvoiceOut manual invoice path', () => { + let browser; + let page; + + beforeAll(async() => { + browser = await getBrowser(); + page = browser.page; + await page.loginAndModule('administrative', 'invoiceOut'); + }); + + afterAll(async() => { + await browser.close(); + }); + + it('should open the manual invoice form', async() => { + await page.waitToClick(selectors.invoiceOutIndex.createInvoice); + await page.waitToClick(selectors.invoiceOutIndex.createManualInvoice); + await page.waitForSelector(selectors.invoiceOutIndex.manualInvoiceForm); + }); + + it('should create an invoice from a ticket', async() => { + await page.autocompleteSearch(selectors.invoiceOutIndex.manualInvoiceTicket, '7'); + await page.autocompleteSearch(selectors.invoiceOutIndex.manualInvoiceSerial, 'Global nacional'); + await page.autocompleteSearch(selectors.invoiceOutIndex.manualInvoiceTaxArea, 'national'); + await page.waitToClick(selectors.invoiceOutIndex.saveInvoice); + const message = await page.waitForSnackbar(); + + expect(message.text).toContain('Data saved!'); + }); + + it(`should have been redirected to the created invoice summary`, async() => { + await page.waitForState('invoiceOut.card.summary'); + }); + + it(`should navigate back to the invoiceOut index`, async() => { + await page.waitToClick(selectors.globalItems.applicationsMenuButton); + await page.waitForSelector(selectors.globalItems.applicationsMenuVisible); + await page.waitToClick(selectors.globalItems.invoiceOutButton); + await page.waitForSelector(selectors.invoiceOutIndex.topbarSearch); + await page.waitForState('invoiceOut.index'); + }); + + it('should now open the manual invoice form', async() => { + await page.waitToClick(selectors.invoiceOutIndex.createInvoice); + await page.waitToClick(selectors.invoiceOutIndex.createManualInvoice); + await page.waitForSelector(selectors.invoiceOutIndex.manualInvoiceForm); + }); + + it('should create an invoice from a client', async() => { + await page.autocompleteSearch(selectors.invoiceOutIndex.manualInvoiceClient, 'Charles Xavier'); + await page.autocompleteSearch(selectors.invoiceOutIndex.manualInvoiceSerial, 'Global nacional'); + await page.autocompleteSearch(selectors.invoiceOutIndex.manualInvoiceTaxArea, 'national'); + await page.waitToClick(selectors.invoiceOutIndex.saveInvoice); + const message = await page.waitForSnackbar(); + + expect(message.text).toContain('Data saved!'); + }); + + it(`should have been redirected to the created invoice summary`, async() => { + await page.waitForState('invoiceOut.card.summary'); + }); +}); diff --git a/e2e/paths/09-invoice-out/04_globalInvoice.spec.js b/e2e/paths/09-invoice-out/04_globalInvoice.spec.js new file mode 100644 index 0000000000..b62c889db1 --- /dev/null +++ b/e2e/paths/09-invoice-out/04_globalInvoice.spec.js @@ -0,0 +1,51 @@ +import selectors from '../../helpers/selectors.js'; +import getBrowser from '../../helpers/puppeteer'; + +describe('InvoiceOut global invoice path', () => { + let browser; + let page; + + beforeAll(async() => { + browser = await getBrowser(); + page = browser.page; + await page.loginAndModule('administrative', 'invoiceOut'); + await page.waitToClick('[icon="search"]'); + await page.waitForTimeout(1000); // index search needs time to return results + }); + + afterAll(async() => { + await browser.close(); + }); + + let invoicesBefore; + + it('should count the amount of invoices listed before globla invoces are made', async() => { + invoicesBefore = await page.countElement(selectors.invoiceOutIndex.searchResult); + + expect(invoicesBefore).toBeGreaterThanOrEqual(4); + }); + + it('should open the global invoice form', async() => { + await page.waitToClick(selectors.invoiceOutIndex.createInvoice); + await page.waitToClick(selectors.invoiceOutIndex.createGlobalInvoice); + await page.waitForSelector(selectors.invoiceOutIndex.globalInvoiceForm); + }); + + it('should create a global invoice for charles xavier today', async() => { + await page.pickDate(selectors.invoiceOutIndex.globalInvoiceDate); + await page.autocompleteSearch(selectors.invoiceOutIndex.globalInvoiceFromClient, 'Petter Parker'); + await page.autocompleteSearch(selectors.invoiceOutIndex.globalInvoiceToClient, 'Petter Parker'); + await page.waitToClick(selectors.invoiceOutIndex.saveInvoice); + const message = await page.waitForSnackbar(); + + expect(message.text).toContain('Data saved!'); + }); + + it('should count the amount of invoices listed after globla invocing', async() => { + await page.waitToClick('[icon="search"]'); + await page.waitForTimeout(1000); // index search needs time to return results + const currentInvoices = await page.countElement(selectors.invoiceOutIndex.searchResult); + + expect(currentInvoices).toBeGreaterThan(invoicesBefore); + }); +}); diff --git a/e2e/paths/10-travel/03_descriptor.spec.js b/e2e/paths/10-travel/03_descriptor.spec.js index d7d38c7af3..619228f354 100644 --- a/e2e/paths/10-travel/03_descriptor.spec.js +++ b/e2e/paths/10-travel/03_descriptor.spec.js @@ -119,7 +119,7 @@ describe('Travel descriptor path', () => { await page.waitToClick(selectors.travelDescriptor.acceptClonation); const message = await page.waitForSnackbar(); - expect(message.text).toContain('A travel with this data already exists'); + expect(message.text).toContain('Unable to clone this travel'); }); it('should update the landed date to a future date to enable cloneWithEntries', async() => { diff --git a/e2e/paths/10-travel/05_thermograph.spec.js b/e2e/paths/10-travel/05_thermograph.spec.js index 97077554f7..a99dc8352c 100644 --- a/e2e/paths/10-travel/05_thermograph.spec.js +++ b/e2e/paths/10-travel/05_thermograph.spec.js @@ -32,7 +32,7 @@ describe('Travel thermograph path', () => { await page.write(selectors.travelThermograph.newThermographId, thermographName); await page.autocompleteSearch(selectors.travelThermograph.newThermographModel, 'TEMPMATE'); await page.autocompleteSearch(selectors.travelThermograph.newThermographWarehouse, 'Warehouse Two'); - await page.autocompleteSearch(selectors.travelThermograph.newThermographTemperature, 'WARM'); + await page.autocompleteSearch(selectors.travelThermograph.newThermographTemperature, 'Warm'); await page.waitToClick(selectors.travelThermograph.createThermographButton); }); diff --git a/e2e/paths/12-entry/07_buys.spec.js b/e2e/paths/12-entry/07_buys.spec.js index e5617b8bd4..4042c99b6c 100644 --- a/e2e/paths/12-entry/07_buys.spec.js +++ b/e2e/paths/12-entry/07_buys.spec.js @@ -29,9 +29,6 @@ describe('Entry import, create and edit buys path', () => { }); it('should fill the form, import the designated JSON file and select items for each import and confirm import', async() => { - await page.write(selectors.entryBuys.ref, 'a reference'); - await page.write(selectors.entryBuys.observation, 'an observation'); - let currentDir = process.cwd(); let filePath = `${currentDir}/e2e/assets/07_import_buys.json`; @@ -41,6 +38,9 @@ describe('Entry import, create and edit buys path', () => { ]); await fileChooser.accept([filePath]); + await page.waitForTextInField(selectors.entryBuys.ref, '200573095, 200573106, 200573117, 200573506'); + await page.waitForTextInField(selectors.entryBuys.observation, '729-6340 2846'); + await page.autocompleteSearch(selectors.entryBuys.firstImportedItem, 'Ranged Reinforced weapon pistol 9mm'); await page.autocompleteSearch(selectors.entryBuys.secondImportedItem, 'Melee Reinforced weapon heavy shield 1x0.5m'); await page.autocompleteSearch(selectors.entryBuys.thirdImportedItem, 'Container medical box 1m'); diff --git a/front/core/components/calendar/index.html b/front/core/components/calendar/index.html index eb6d196bad..086fe4338a 100644 --- a/front/core/components/calendar/index.html +++ b/front/core/components/calendar/index.html @@ -19,28 +19,42 @@ ng-if="$ctrl.displayControls">
-
-
- {{::day.localeChar}} -
+
+
+
+
+ {{::day.localeChar}} +
+
-
-
-
- {{::day | date: 'd'}} -
-
+ +
+
+
+
+ {{::week}} +
+
+
+
+
+
+ {{::day | date: 'd'}} +
+
+
\ No newline at end of file diff --git a/front/core/components/calendar/index.js b/front/core/components/calendar/index.js index 17bf529417..85b51fd042 100644 --- a/front/core/components/calendar/index.js +++ b/front/core/components/calendar/index.js @@ -12,11 +12,12 @@ import './style.scss'; * @event move Emitted when month changes */ export default class Calendar extends FormInput { - constructor($element, $scope, vnWeekDays) { + constructor($element, $scope, vnWeekDays, moment) { super($element, $scope); this.weekDays = vnWeekDays.locales; this.defaultDate = new Date(); this.displayControls = true; + this.moment = moment; } /** @@ -54,15 +55,23 @@ export default class Calendar extends FormInput { ); } + lastDay() { + return new Date( + this.defaultDate.getFullYear(), + this.defaultDate.getMonth() + 1, + 0 + ).getDate(); + } + /** * Repaints the calendar. */ repaint() { const firstWeekday = this.firstDay(this.defaultDate).getDay() - 1; - let weekdayOffset = firstWeekday >= 0 ? firstWeekday : 6; + this.weekdayOffset = firstWeekday >= 0 ? firstWeekday : 6; let dayIndex = new Date(this.defaultDate.getTime()); - dayIndex.setDate(1 - weekdayOffset); + dayIndex.setDate(1 - this.weekdayOffset); this.days = []; @@ -70,27 +79,55 @@ export default class Calendar extends FormInput { this.days.push(new Date(dayIndex.getTime())); dayIndex.setDate(dayIndex.getDate() + 1); } + + this.getWeekdays(); + } + + getWeekdays() { + if (!this.moment) return; + + const totalSlots = this.lastDay() + this.weekdayOffset; + const weeks = Math.ceil(totalSlots / 7); + + const dated = this.moment(this.defaultDate); + const firstWeekNumber = dated.set('date', 1).isoWeek(); + + const weekNumbers = []; + for (let w = 0; w < weeks; w++) { + let weekNumber = firstWeekNumber; + if (dated.get('month') == 0 && firstWeekNumber > 1 && w > 0) + weekNumber = 0; + + weekNumbers.push(weekNumber + w); + } + + this.weekNumbers = weekNumbers; } /** * Gets CSS classes to apply to the specified day. * - * @param {Date} day The day + * @param {Date} date The date * @return {Object} The CSS classes to apply */ - getDayClasses(day) { - let wday = day.getDay(); - let month = day.getMonth(); + getDayClasses(date) { + let day = date.getDate(); + let wday = date.getDay(); + let month = date.getMonth(); + + const currentDay = new Date().getDate(); + const currentMonth = new Date().getMonth(); let classes = { + today: day === currentDay && month === currentMonth, weekend: wday === 6 || wday === 0, previous: month < this.month, current: month == this.month, next: month > this.month, - event: this.hasEvents({$day: day}) + event: this.hasEvents({$day: date}) }; - let userClass = this.getClass({$day: day}); + let userClass = this.getClass({$day: date}); if (userClass) classes[userClass] = true; return classes; @@ -181,7 +218,7 @@ export default class Calendar extends FormInput { } } } -Calendar.$inject = ['$element', '$scope', 'vnWeekDays']; +Calendar.$inject = ['$element', '$scope', 'vnWeekDays', 'moment']; ngModule.vnComponent('vnCalendar', { template: require('./index.html'), @@ -193,6 +230,7 @@ ngModule.vnComponent('vnCalendar', { formatDay: '&?', displayControls: ' .weekdays { + & #days-header { + flex-direction: row; + display: flex + } + & #days-header > .week-numbers { + width: 10% + } + & #days-header > .weekdays { display: flex; color: $color-font-secondary; margin-bottom: 8px; @@ -27,17 +34,49 @@ font-weight: bold; font-size: .8rem; text-align: center; + width: 90%; & > section { width: 14.28%; cursor: pointer; } } - & > .days { + & #days-header.hide-weeks { + & > .weekdays { + width: 100% + } + } + & > #days-container { + flex-direction: row; + display: flex + } + & > #days-container > .weeks { display: flex; + flex-direction: column; + color: $color-font-secondary; + font-weight: bold; + font-size: .8rem; + width: 10%; + + & > .day { + height: 40px; + display: flex; + justify-content: center; + align-items: center; + } + } + & #days-container.hide-weeks { + & > .days { + width: 100% + } + } + #days-container > .days { + display: flex; + flex-direction: row; justify-content: center; align-items: center; flex-wrap: wrap; + width: 90%; & > .day { width: 14.28%; @@ -46,6 +85,17 @@ justify-content: center; align-items: center; + &.today { + color: $color-font-bg; + & > .day-number { + border: 2px solid $color-font-link; + + &:hover { + background-color: lighten($color-font-link, 20%); + opacity: .8 + } + } + } &.weekend { color: $color-font-secondary; } diff --git a/front/core/components/pagination/pagination.html b/front/core/components/pagination/pagination.html index 5bc1b67f69..6809018dde 100644 --- a/front/core/components/pagination/pagination.html +++ b/front/core/components/pagination/pagination.html @@ -1,10 +1,9 @@
- - + diff --git a/front/core/locale/es.yml b/front/core/locale/es.yml index d2d3b62622..d849fcdd28 100644 --- a/front/core/locale/es.yml +++ b/front/core/locale/es.yml @@ -62,5 +62,5 @@ Go up: Ir arriba Loading...: Cargando... No results found: Sin resultados No data: Sin datos -Load more: Cargar más -Undo changes: Deshacer cambios \ No newline at end of file +Undo changes: Deshacer cambios +Load more results: Cargar más resultados \ No newline at end of file diff --git a/front/core/styles/icons/salixfont.css b/front/core/styles/icons/salixfont.css index 0a036b3d0f..d6466a0ebd 100644 --- a/front/core/styles/icons/salixfont.css +++ b/front/core/styles/icons/salixfont.css @@ -239,9 +239,6 @@ .icon-mandatory:before { content: "\e921"; } -.icon-niche:before { - content: "\e922"; -} .icon-no036:before { content: "\e923"; } diff --git a/front/core/styles/icons/salixfont.svg b/front/core/styles/icons/salixfont.svg index cc359f2c26..7ff0f037d9 100644 --- a/front/core/styles/icons/salixfont.svg +++ b/front/core/styles/icons/salixfont.svg @@ -8,7 +8,7 @@ - + @@ -34,18 +34,17 @@ - - + + - - + - - + + @@ -55,13 +54,13 @@ - + - + @@ -79,7 +78,7 @@ - + @@ -90,11 +89,11 @@ - + - - - + + + @@ -102,10 +101,9 @@ - - - - + + + diff --git a/front/core/vendor.js b/front/core/vendor.js index d7e7f1e63a..1c6d3217e3 100644 --- a/front/core/vendor.js +++ b/front/core/vendor.js @@ -9,13 +9,15 @@ import 'angular-translate-loader-partial'; import '@uirouter/angularjs'; import 'mg-crud'; import 'oclazyload'; +import 'angular-moment'; export const ngDeps = [ 'ngAnimate', 'pascalprecht.translate', 'ui.router', 'mgCrud', - 'oc.lazyLoad' + 'oc.lazyLoad', + 'angularMoment' ]; import * as validator from 'validator'; diff --git a/front/package-lock.json b/front/package-lock.json deleted file mode 100644 index 3321046feb..0000000000 --- a/front/package-lock.json +++ /dev/null @@ -1,115 +0,0 @@ -{ - "name": "salix-front", - "version": "1.0.0", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "@uirouter/angularjs": { - "version": "1.0.29", - "resolved": "https://registry.npmjs.org/@uirouter/angularjs/-/angularjs-1.0.29.tgz", - "integrity": "sha512-RImWnBarNixkMto0o8stEaGwZmvhv5cnuOLXyMU2pY8MP2rgEF74ZNJTLeJCW14LR7XDUxVH8Mk8bPI6lxedmQ==", - "requires": { - "@uirouter/core": "6.0.7" - } - }, - "@uirouter/core": { - "version": "6.0.7", - "resolved": "https://registry.npmjs.org/@uirouter/core/-/core-6.0.7.tgz", - "integrity": "sha512-KUTJxL+6q0PiBnFx4/Z+Hsyg0pSGiaW5yZQeJmUxknecjpTbnXkLU8H2EqRn9N2B+qDRa7Jg8RcgeNDPY72O1w==" - }, - "angular": { - "version": "1.8.2", - "resolved": "https://registry.npmjs.org/angular/-/angular-1.8.2.tgz", - "integrity": "sha512-IauMOej2xEe7/7Ennahkbb5qd/HFADiNuLSESz9Q27inmi32zB0lnAsFeLEWcox3Gd1F6YhNd1CP7/9IukJ0Gw==" - }, - "angular-animate": { - "version": "1.8.2", - "resolved": "https://registry.npmjs.org/angular-animate/-/angular-animate-1.8.2.tgz", - "integrity": "sha512-Jbr9+grNMs9Kj57xuBU3Ju3NOPAjS1+g2UAwwDv7su1lt0/PLDy+9zEwDiu8C8xJceoTbmBNKiWGPJGBdCQLlA==" - }, - "angular-translate": { - "version": "2.18.4", - "resolved": "https://registry.npmjs.org/angular-translate/-/angular-translate-2.18.4.tgz", - "integrity": "sha512-KohNrkH6J9PK+VW0L/nsRTcg5Fw70Ajwwe3Jbfm54Pf9u9Fd+wuingoKv+h45mKf38eT+Ouu51FPua8VmZNoCw==", - "requires": { - "angular": "^1.8.0" - } - }, - "angular-translate-loader-partial": { - "version": "2.18.4", - "resolved": "https://registry.npmjs.org/angular-translate-loader-partial/-/angular-translate-loader-partial-2.18.4.tgz", - "integrity": "sha512-bsjR+FbB0sdA2528E/ugwKdlPPQhA1looxLxI3otayBTFXBpED33besfSZhYAISLgNMSL038vSssfRUen9qD8w==", - "requires": { - "angular-translate": "~2.18.4" - } - }, - "argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "requires": { - "sprintf-js": "~1.0.2" - } - }, - "esprima": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==" - }, - "js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", - "requires": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" - } - }, - "mg-crud": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/mg-crud/-/mg-crud-1.1.2.tgz", - "integrity": "sha1-p6AWGzWSPK7/8ZpIBpS2V1vDggw=", - "requires": { - "angular": "^1.6.1" - } - }, - "oclazyload": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/oclazyload/-/oclazyload-0.6.3.tgz", - "integrity": "sha1-Kjirv/QJDAihEBZxkZRbWfLoJ5w=" - }, - "require-yaml": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/require-yaml/-/require-yaml-0.0.1.tgz", - "integrity": "sha1-LhsY2RPDuqcqWk03O28Tjd0sMr0=", - "requires": { - "js-yaml": "^4.0.0" - }, - "dependencies": { - "argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" - }, - "js-yaml": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.0.0.tgz", - "integrity": "sha512-pqon0s+4ScYUvX30wxQi3PogGFAlUyH0awepWvwkj4jD4v+ova3RiYw8bmA6x2rDrEaj8i/oWKoRxpVNW+Re8Q==", - "requires": { - "argparse": "^2.0.1" - } - } - } - }, - "sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=" - }, - "validator": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/validator/-/validator-6.3.0.tgz", - "integrity": "sha1-R84j7Y1Ord+p1LjvAHG2zxB418g=" - } - } -} diff --git a/front/package.json b/front/package.json index 3ef90bf414..77af30f6c8 100644 --- a/front/package.json +++ b/front/package.json @@ -12,8 +12,10 @@ "@uirouter/angularjs": "^1.0.20", "angular": "^1.7.5", "angular-animate": "^1.7.8", + "angular-moment": "^1.3.0", "angular-translate": "^2.18.1", "angular-translate-loader-partial": "^2.18.1", + "croppie": "^2.6.5", "js-yaml": "^3.13.1", "mg-crud": "^1.1.2", "oclazyload": "^0.6.3", diff --git a/front/salix/components/bank-entity/index.html b/front/salix/components/bank-entity/index.html index 3a77866074..211b773175 100644 --- a/front/salix/components/bank-entity/index.html +++ b/front/salix/components/bank-entity/index.html @@ -1,40 +1,46 @@ - - -

Please, ensure you put the correct data!

- - - - - - - - - - -
- - - - -
+ + New bank entity + + +

Please, ensure you put the correct data!

+ + + + + + + + + + + + +
+ + + + \ No newline at end of file diff --git a/front/salix/components/bank-entity/index.js b/front/salix/components/bank-entity/index.js index 192ebe0467..2610180179 100644 --- a/front/salix/components/bank-entity/index.js +++ b/front/salix/components/bank-entity/index.js @@ -1,35 +1,24 @@ import ngModule from '../../module'; -import Component from 'core/lib/component'; +import Dialog from 'core/components/dialog'; import './style.scss'; -class Controller extends Component { - open() { - this.$.bankEntityDialog.show(); - } +class Controller extends Dialog { + responseHandler(response) { + if (response !== 'accept') + return super.responseHandler(response); - resetData() { - this.data = {}; - } + if (!this.data.countryFk) + throw new Error(`The country can't be empty`); - onAccept() { - try { - if (!this.data.countryFk) - throw new Error(`The country can't be empty`); - - this.$http.post(`bankEntities`, this.data).then(res => { - this.vnApp.showMessage(this.$t('The bank entity has been created. You can save the data now')); - this.emit('response', {$response: res.data}); - }); - } catch (e) { - this.vnApp.showError(this.$t(e.message)); - return false; - } - return true; + return this.$http.post(`bankEntities`, this.data) + .then(res => this.data.id = res.data.id) + .then(() => super.responseHandler(response)) + .then(() => this.vnApp.showSuccess(this.$t('Data saved!'))); } } ngModule.vnComponent('vnNewBankEntity', { - template: require('./index.html'), + slotTemplate: require('./index.html'), controller: Controller, bindings: { data: '<', diff --git a/front/salix/components/bank-entity/index.spec.js b/front/salix/components/bank-entity/index.spec.js index c288c30527..f93325231f 100644 --- a/front/salix/components/bank-entity/index.spec.js +++ b/front/salix/components/bank-entity/index.spec.js @@ -5,49 +5,35 @@ describe('Salix Component vnNewBankEntity', () => { let $httpBackend; let $scope; let $element; - let vnApp; beforeEach(ngModule('salix')); - beforeEach(inject(($componentController, $rootScope, _$httpBackend_, _vnApp_) => { + beforeEach(inject(($componentController, $rootScope, _$httpBackend_) => { $httpBackend = _$httpBackend_; - vnApp = _vnApp_; - jest.spyOn(vnApp, 'showError'); $scope = $rootScope.$new(); - $element = angular.element(''); - controller = $componentController('vnNewBankEntity', {$element, $scope}); + $element = angular.element(''); + const $transclude = { + $$boundTransclude: { + $$slots: [] + } + }; + controller = $componentController('vnNewBankEntity', {$element, $scope, $transclude}); + controller.vnApp = {showSuccess: jest.fn()}; })); - describe('resetData()', () => { - it('should reset the location in the controller', () => { - expect(controller.data).toBeUndefined(); - - controller.resetData(); - - expect(controller.data).toEqual({}); - }); - }); - - describe('onAccept()', () => { - it('should throw an error if there is no country id in the location', () => { - jest.spyOn(controller.vnApp, 'showMessage'); - - controller.data = {}; - - controller.onAccept(); - - expect(controller.vnApp.showError).toHaveBeenCalledWith(`The country can't be empty`); - }); - - it('should do add the new bank entity', () => { + describe('responseHandler()', () => { + it('should show a success message after the query to bankEntities', () => { controller.data = { countryFk: 1 }; - $httpBackend.expectPOST('bankEntities', controller.data).respond(200, controller.data); + $httpBackend.expectPOST('bankEntities', controller.data).respond({id: 1}); - controller.onAccept(); + controller.responseHandler('accept'); $httpBackend.flush(); + + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); + expect(controller.data.id).toEqual(1); }); }); }); diff --git a/front/salix/components/bank-entity/locale/es.yml b/front/salix/components/bank-entity/locale/es.yml index fe5160572a..874a423930 100644 --- a/front/salix/components/bank-entity/locale/es.yml +++ b/front/salix/components/bank-entity/locale/es.yml @@ -9,4 +9,5 @@ The country can't be empty: El país no puede quedar vacío The postcode has been created. You can save the data now: Se ha creado el código postal. Ahora puedes guardar los datos The city has been created: Se ha creado la ciudad The province has been created: Se ha creado la provincia -The bank entity has been created. You can save the data now: Se ha creado la entidad bancaria. Puedes guardar los datos ahora \ No newline at end of file +The bank entity has been created. You can save the data now: Se ha creado la entidad bancaria. Puedes guardar los datos ahora +Entity code: Código de la entidad \ No newline at end of file diff --git a/front/salix/components/log/index.html b/front/salix/components/log/index.html index 15a7b38b34..c78e00f445 100644 --- a/front/salix/components/log/index.html +++ b/front/salix/components/log/index.html @@ -8,7 +8,7 @@ Date Author - Model + Model Action Name Before @@ -17,7 +17,7 @@ - + {{::log.creationDate | date:'dd/MM/yyyy HH:mm'}}
diff --git a/front/salix/components/upload-photo/croppie.scss b/front/salix/components/upload-photo/croppie.scss new file mode 100644 index 0000000000..1d736f896f --- /dev/null +++ b/front/salix/components/upload-photo/croppie.scss @@ -0,0 +1,252 @@ +@import "./variables"; + + +.croppie-container { + width: 100%; + height: 100%; +} + +.croppie-container .cr-image { + z-index: -1; + position: absolute; + top: 0; + left: 0; + transform-origin: 0 0; + max-height: none; + max-width: none; +} + +.croppie-container .cr-boundary { + border: 2px solid $color-primary; + position: relative; + overflow: hidden; + margin: 0 auto; + z-index: 1; + width: 100%; + height: 100%; +} + +.croppie-container .cr-viewport, +.croppie-container .cr-resizer { + position: absolute; + border: 2px solid #fff; + margin: auto; + top: 0; + bottom: 0; + right: 0; + left: 0; + box-shadow: 0 0 2000px 2000px rgba(0, 0, 0, 0.5); + z-index: 0; +} + +.croppie-container .cr-resizer { + z-index: 2; + box-shadow: none; + pointer-events: none; +} + +.croppie-container .cr-resizer-vertical, +.croppie-container .cr-resizer-horisontal { + position: absolute; + pointer-events: all; +} + +.croppie-container .cr-resizer-vertical::after, +.croppie-container .cr-resizer-horisontal::after { + display: block; + position: absolute; + box-sizing: border-box; + border: 1px solid black; + background: #fff; + width: 10px; + height: 10px; + content: ''; +} + +.croppie-container .cr-resizer-vertical { + bottom: -5px; + cursor: row-resize; + width: 100%; + height: 10px; +} + +.croppie-container .cr-resizer-vertical::after { + left: 50%; + margin-left: -5px; +} + +.croppie-container .cr-resizer-horisontal { + right: -5px; + cursor: col-resize; + width: 10px; + height: 100%; +} + +.croppie-container .cr-resizer-horisontal::after { + top: 50%; + margin-top: -5px; +} + +.croppie-container .cr-original-image { + display: none; +} + +.croppie-container .cr-vp-circle { + border-radius: 50%; +} + +.croppie-container .cr-overlay { + z-index: 1; + position: absolute; + cursor: move; + touch-action: none; +} + +.croppie-container .cr-slider-wrap { + margin: 15px auto; + text-align: center; +} + +.croppie-result { + position: relative; + overflow: hidden; +} + +.croppie-result img { + position: absolute; +} + +.croppie-container .cr-image, +.croppie-container .cr-overlay, +.croppie-container .cr-viewport { + -webkit-transform: translateZ(0); + -moz-transform: translateZ(0); + -ms-transform: translateZ(0); + transform: translateZ(0); +} + +/*************************************/ +/***** STYLING RANGE INPUT ***********/ +/*************************************/ +/*http://brennaobrien.com/blog/2014/05/style-input-type-range-in-every-browser.html */ +/*************************************/ + +.cr-slider { + -webkit-appearance: none; +/*removes default webkit styles*/ + /*border: 1px solid white; *//*fix for FF unable to apply focus style bug */ + width: 300px; +/*required for proper track sizing in FF*/ + max-width: 100%; + padding-top: 8px; + padding-bottom: 8px; + background-color: transparent; +} + +.cr-slider::-webkit-slider-runnable-track { + width: 100%; + height: 3px; + background: rgba(0, 0, 0, 0.2); + border: 0; +} + +.cr-slider::-webkit-slider-thumb { + -webkit-appearance: none; + border: none; + height: 16px; + width: 16px; + border-radius: 50%; + background: $color-primary; + margin-top: -6px; +} + +.cr-slider:focus { + outline: none; +} +/* +.cr-slider:focus::-webkit-slider-runnable-track { +background: #ccc; +} +*/ + +.cr-slider::-moz-range-track { + width: 100%; + height: 3px; + background: rgba(0, 0, 0, 0.5); + border: 0; + border-radius: 3px; +} + +.cr-slider::-moz-range-thumb { + border: none; + height: 16px; + width: 16px; + border-radius: 50%; + background: #ddd; + margin-top: -6px; +} + +/*hide the outline behind the border*/ +.cr-slider:-moz-focusring { + outline: 1px solid white; + outline-offset: -1px; +} + +.cr-slider::-ms-track { + width: 100%; + height: 5px; + background: transparent; +/*remove bg colour from the track, we'll use ms-fill-lower and ms-fill-upper instead */ + border-color: transparent;/*leave room for the larger thumb to overflow with a transparent border */ + border-width: 6px 0; + color: transparent;/*remove default tick marks*/ +} +.cr-slider::-ms-fill-lower { + background: rgba(0, 0, 0, 0.5); + border-radius: 10px; +} +.cr-slider::-ms-fill-upper { + background: rgba(0, 0, 0, 0.5); + border-radius: 10px; +} +.cr-slider::-ms-thumb { + border: none; + height: 16px; + width: 16px; + border-radius: 50%; + background: #ddd; + margin-top:1px; +} +.cr-slider:focus::-ms-fill-lower { + background: rgba(0, 0, 0, 0.5); +} +.cr-slider:focus::-ms-fill-upper { + background: rgba(0, 0, 0, 0.5); +} +/*******************************************/ + +/***********************************/ +/* Rotation Tools */ +/***********************************/ +.cr-rotate-controls { + position: absolute; + bottom: 5px; + left: 5px; + z-index: 1; +} +.cr-rotate-controls button { + border: 0; + background: none; +} +.cr-rotate-controls i:before { + display: inline-block; + font-style: normal; + font-weight: 900; + font-size: 22px; +} +.cr-rotate-l i:before { + content: '↺'; +} +.cr-rotate-r i:before { + content: '↻'; +} diff --git a/front/salix/components/upload-photo/index.html b/front/salix/components/upload-photo/index.html index c36eb7fe10..3dd6cdb278 100644 --- a/front/salix/components/upload-photo/index.html +++ b/front/salix/components/upload-photo/index.html @@ -1,36 +1,84 @@ + message="Edit photo"> - -
-
- - - - - - - - - - - - + + + + + +
+ + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/front/salix/components/upload-photo/index.js b/front/salix/components/upload-photo/index.js index 924a6a8a44..29d23bd66d 100644 --- a/front/salix/components/upload-photo/index.js +++ b/front/salix/components/upload-photo/index.js @@ -1,24 +1,80 @@ import ngModule from '../../module'; import Component from 'core/lib/component'; +import Croppie from 'croppie'; import './style.scss'; +import './croppie.scss'; /** * Small card with basing entity information and actions. */ export default class UploadPhoto extends Component { + constructor($element, $) { + super($element, $); + + this.viewportTypes = [ + { + code: 'normal', + description: this.$t('Normal'), + viewport: { + width: 400, + height: 400 + }, + output: { + width: 1200, + height: 1200 + } + + }, + { + code: 'panoramic', + description: this.$t('Panoramic'), + viewport: { + width: 675, + height: 450 + }, + output: { + width: 1350, + height: 900 + } + } + ]; + this.viewportType = 'normal'; + this.uploadMethod = 'computer'; + this.getAllowedContentTypes(); + } + /** * Opens the dialog and sets the default data * @param {*} collection - Collection name * @param {*} id - Entity id */ show(collection, id) { + this.editor = null; this.newPhoto = { id: id, collection: collection, fileName: id }; this.$.dialog.show(); - this.getAllowedContentTypes(); + } + + get viewportSelection() { + return this._viewportSelection; + } + + set viewportSelection(value) { + this._viewportSelection = value; + + const hasFile = this.newPhoto.files || this.newPhoto.url; + if (!value || !hasFile) return; + + let file; + if (this.uploadMethod == 'computer') + file = this.newPhoto.files[0]; + else if (this.uploadMethod == 'URL') + file = this.newPhoto.url; + + this.updatePhotoPreview(file); } getAllowedContentTypes() { @@ -40,13 +96,42 @@ export default class UploadPhoto extends Component { * @param {string} value */ updatePhotoPreview(value) { - if (value && value[0]) { - const reader = new FileReader(); - reader.onload = e => this.$.photo.src = e.target.result; - reader.readAsDataURL(value[0]); + if (value) { + this.displayEditor(); + + if (this.uploadMethod == 'computer') { + const reader = new FileReader(); + reader.onload = e => this.editor.bind({url: e.target.result}); + reader.readAsDataURL(value); + } else if (this.uploadMethod == 'URL') + this.editor.bind({url: value}); } } + displayEditor() { + const viewportType = this.viewportSelection; + const viewport = viewportType.viewport; + const boundaryWidth = viewport.width + 200; + const boundaryHeight = viewport.height + 200; + + const container = document.getElementById('photoContainer'); + if (this.editor) this.editor.destroy(); + this.editor = new Croppie(container, { + viewport: {width: viewport.width, height: viewport.height}, + boundary: {width: boundaryWidth, height: boundaryHeight}, + enableOrientation: true, + showZoomer: true + }); + } + + rotateLeft() { + this.editor.rotate(90); + } + + rotateRight() { + this.editor.rotate(-90); + } + /** * Dialog response handler * @@ -57,12 +142,22 @@ export default class UploadPhoto extends Component { if (!this.newPhoto.files) throw new Error(`Select an image`); - this.makeRequest(); + const viewportType = this.viewportSelection; + const output = viewportType.output; + const options = { + type: 'blob', + size: { + width: output.width, + height: output.height + } + }; + return this.editor.result(options) + .then(blob => this.newPhoto.blob = blob) + .then(() => this.makeRequest()); } catch (e) { this.vnApp.showError(this.$t(e.message)); return false; } - return true; } /** @@ -79,10 +174,13 @@ export default class UploadPhoto extends Component { params: this.newPhoto, headers: {'Content-Type': undefined}, timeout: this.canceler.promise, - transformRequest: files => { + transformRequest: ([file]) => { const formData = new FormData(); - for (let i = 0; i < files.length; i++) - formData.append(files[i].name, files[i]); + const now = new Date(); + const timestamp = now.getTime(); + const fileName = `${file.name}_${timestamp}`; + + formData.append('blob', this.newPhoto.blob, fileName); return formData; }, diff --git a/front/salix/components/upload-photo/index.spec.js b/front/salix/components/upload-photo/index.spec.js index 0ae7a54257..f2aad6a5ca 100644 --- a/front/salix/components/upload-photo/index.spec.js +++ b/front/salix/components/upload-photo/index.spec.js @@ -6,7 +6,9 @@ describe('Salix', () => { let $scope; let $httpBackend; - beforeEach(ngModule('salix')); + beforeEach(ngModule('salix', $translateProvider => { + $translateProvider.translations('en', {}); + })); beforeEach(inject(($componentController, $rootScope, _$httpBackend_) => { $scope = $rootScope.$new(); @@ -14,12 +16,71 @@ describe('Salix', () => { const $element = angular.element(''); controller = $componentController('vnUploadPhoto', {$element, $scope}); controller.newPhoto = {}; + controller.$t = m => m; })); afterEach(() => { $scope.$destroy(); }); + describe('viewportSelection()', () => { + it('should call to the updatePhotoPreview() method when uploadMethod property is set to "computer"', () => { + controller.updatePhotoPreview = jest.fn(); + + const files = [{name: 'test.jpg'}]; + controller.newPhoto.files = files; + + controller.uploadMethod = 'computer'; + controller.viewportSelection = {code: 'normal'}; + + const firstFile = files[0]; + + expect(controller.updatePhotoPreview).toHaveBeenCalledWith(firstFile); + }); + + it('should call to the updatePhotoPreview() method when uploadMethod property is set to "URL"', () => { + controller.updatePhotoPreview = jest.fn(); + + const url = 'http://gothamcity.com/batman.png'; + controller.newPhoto.url = url; + + controller.uploadMethod = 'URL'; + controller.viewportSelection = {code: 'normal'}; + + expect(controller.updatePhotoPreview).toHaveBeenCalledWith(url); + }); + }); + + describe('displayEditor()', () => { + it('should define the editor property', () => { + controller.viewportSelection = { + code: 'normal', + description: 'Normal', + viewport: { + width: 400, + height: 400 + }, + output: { + width: 1200, + height: 1200 + } + }; + const element = document.createElement('div'); + + jest.spyOn(document, 'getElementById').mockReturnValue(element); + + controller.displayEditor(); + + const editor = controller.editor; + + expect(editor).toBeDefined(); + expect(editor.options.viewport.width).toEqual(400); + expect(editor.options.viewport.width).toEqual(400); + expect(editor.options.boundary.width).toEqual(600); + expect(editor.options.boundary.height).toEqual(600); + }); + }); + describe('onUploadAccept()', () => { it('should throw an error message containing "Select an image"', () => { jest.spyOn(controller.vnApp, 'showError'); @@ -29,13 +90,33 @@ describe('Salix', () => { expect(controller.vnApp.showError).toHaveBeenCalledWith('Select an image'); }); - it('should call to the makeRequest() method', () => { + it('should call to the makeRequest() method', done => { + controller.editor = { + result: () => {} + }; + jest.spyOn(controller, 'makeRequest'); + jest.spyOn(controller.editor, 'result').mockReturnValue(new Promise(resolve => resolve('blobFile'))); + + controller.viewportSelection = { + code: 'normal', + description: 'Normal', + viewport: { + width: 400, + height: 400 + }, + output: { + width: 1200, + height: 1200 + } + }; controller.newPhoto.files = [0]; - controller.onUploadAccept(); - - expect(controller.makeRequest).toHaveBeenCalledWith(); + controller.onUploadAccept().then(() => { + expect(controller.newPhoto.blob).toEqual('blobFile'); + expect(controller.makeRequest).toHaveBeenCalledWith(); + done(); + }).catch(done.fail); }); }); @@ -44,7 +125,11 @@ describe('Salix', () => { jest.spyOn(controller.vnApp, 'showSuccess'); jest.spyOn(controller, 'emit'); + $httpBackend.expectGET('ImageContainers/allowedContentTypes').respond(200, ['image/jpg']); + controller.newPhoto.files = [{name: 'hola'}]; + controller.newPhoto.blob = new Blob([]); + $httpBackend.expectRoute('POST', 'Images/upload').respond(200); controller.makeRequest(); $httpBackend.flush(); diff --git a/front/salix/components/upload-photo/locale/es.yml b/front/salix/components/upload-photo/locale/es.yml index d2e696ba9c..bcc3801d88 100644 --- a/front/salix/components/upload-photo/locale/es.yml +++ b/front/salix/components/upload-photo/locale/es.yml @@ -1,3 +1,8 @@ -Upload new photo: Subir una nueva foto +Edit photo: Editar foto Select an image: Selecciona una imagen -File name: Nombre del fichero \ No newline at end of file +File name: Nombre del fichero +Rotate left: Girar a la izquierda +Rotate right: Girar a la derecha +Panoramic: Panorámico +Select from computer: Seleccionar desde ordenador +Import from external URL: Importar desde URL externa \ No newline at end of file diff --git a/front/salix/components/upload-photo/style.scss b/front/salix/components/upload-photo/style.scss index 609364a2c1..52e58208ca 100644 --- a/front/salix/components/upload-photo/style.scss +++ b/front/salix/components/upload-photo/style.scss @@ -1,26 +1,11 @@ @import "./variables"; .upload-photo { - .photo { - position: relative; - margin: 0 auto; - text-align: center; - & > div { - border: 3px solid $color-primary; - max-width: 256px; - max-height: 256px; - border-radius: 50%; - overflow: hidden - } - - & > div > img[ng-src] { - width: 256px; - height: 256px; - display: block - } + & > vn-horizontal { + align-items: initial; } - + & > vn-spinner { display: block; height: 40px; @@ -28,10 +13,13 @@ } vn-input-file { - max-width: 256px; div.control { overflow: hidden } } + + .form { + align-items: initial; + } } diff --git a/front/salix/components/user-popover/index.html b/front/salix/components/user-popover/index.html index 22d86f1aaa..0fa6800c55 100644 --- a/front/salix/components/user-popover/index.html +++ b/front/salix/components/user-popover/index.html @@ -63,7 +63,7 @@ show-field="bank" order="id" value-field="id" - search-function="{or: [{id: $search}, {bank: {like: '%'+ $search +'%'}}]}"> + search-function="$ctrl.bankSearchFunc($search)"> {{id}}: {{bank}} { }); describe('getImageUrl()', () => { - it('should return de url image', () => { + it('should return the url image', () => { const url = $root.imagePath('user', '160x160', userId); expect(url).toBeDefined(); expect(url).toEqual(`/api/Images/user/160x160/${userId}/download?access_token=null`); }); }); + + describe('bankSearchFunc()', () => { + it('should return the filter by id property for an input of a number', () => { + const bankId = 1; + const result = controller.bankSearchFunc(bankId); + + expect(result).toEqual({id: bankId}); + }); + + it('should return the filter by bank property for an input of an string', () => { + const bankName = 'Bank of America'; + const result = controller.bankSearchFunc(bankName); + + expect(result).toEqual({bank: {like: '%' + bankName + '%'}}); + }); + }); }); }); diff --git a/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js b/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js index 5319b185a4..e2f842a15d 100644 --- a/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js +++ b/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js @@ -1,19 +1,29 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Model rewriteDbError()', () => { it('should extend rewriteDbError properties to any model passed', () => { - let exampleModel = app.models.ItemNiche; + const exampleModel = models.ItemTag; expect(exampleModel.rewriteDbError).toBeDefined(); }); it('should handle a duplicated warehouse error', async() => { - let itemNiche = {itemFk: 1, warehouseFK: 1, code: 'A11'}; + const tx = await models.Ticket.beginTransaction({}); + let error; - await app.models.ItemNiche.create(itemNiche).catch(e => { + + try { + const options = {transaction: tx}; + + const itemTag = {itemFk: 1, tagFk: 56, value: 'Ranged weapon', priority: 1}; + await models.ItemTag.create(itemTag, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); error = e; - }).finally(() => { - expect(error.message).toEqual(`The warehouse can't be repeated`); - }); + } + + expect(error.message).toEqual(`The tag can't be repeated`); }); }); diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 9bef13527a..70f3984a6d 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -57,7 +57,14 @@ "The postcode doesn't exist. Please enter a correct one": "The postcode doesn't exist. Please enter a correct one", "Can't create stowaway for this ticket": "Can't create stowaway for this ticket", "Swift / BIC can't be empty": "Swift / BIC can't be empty", - "Bought units from buy request": "Bought {{quantity}} units of {{concept}} [{{itemId}}]({{{urlItem}}}) for the ticket id [{{ticketId}}]({{{url}}})", + "Deleted sales from ticket": "I have deleted the following lines from the ticket [{{ticketId}}]({{{ticketUrl}}}): {{{deletions}}}", + "Added sale to ticket": "I have added the following line to the ticket [{{ticketId}}]({{{ticketUrl}}}): {{{addition}}}", + "Changed sale discount": "I have changed the following lines discounts from the ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", + "Created claim": "I have created the claim [{{claimId}}]({{{claimUrl}}}) for the following lines from the ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", + "Changed sale price": "I have changed the price of [{{itemId}} {{concept}}]({{{itemUrl}}}) ({{quantity}}) from {{oldPrice}}€ ➔ *{{newPrice}}€* of the ticket [{{ticketId}}]({{{ticketUrl}}})", + "Changed sale quantity": "I have changed the quantity of [{{itemId}} {{concept}}]({{{itemUrl}}}) from {{oldQuantity}} ➔ *{{newQuantity}}* of the ticket [{{ticketId}}]({{{ticketUrl}}})", + "Changed sale reserved state": "I have changed the following lines reserved state from the ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", + "Bought units from buy request": "Bought {{quantity}} units of [{{itemId}} {{concept}}]({{{urlItem}}}) for the ticket id [{{ticketId}}]({{{url}}})", "MESSAGE_INSURANCE_CHANGE": "I have changed the insurence credit of client [{{clientName}} ({{clientId}})]({{{url}}}) to *{{credit}} €*", "Changed client paymethod": "I have changed the pay method for client [{{clientName}} ({{clientId}})]({{{url}}})", "Sent units from ticket": "I sent *{{quantity}}* units of [{{concept}} ({{itemId}})]({{{itemUrl}}}) to *\"{{nickname}}\"* coming from ticket id [{{ticketId}}]({{{ticketUrl}}})", @@ -88,7 +95,7 @@ "The nif cannot be empty": "The nif cannot be empty", "Amount cannot be zero": "Amount cannot be zero", "Company has to be official": "Company has to be official", - "A travel with this data already exists": "A travel with this data already exists", + "Unable to clone this travel": "Unable to clone this travel", "The observation type can't be repeated": "The observation type can't be repeated", "New ticket request has been created with price": "New ticket request has been created *'{{description}}'* for day *{{shipped}}*, with a quantity of *{{quantity}}* and a price of *{{price}} €*", "New ticket request has been created": "New ticket request has been created *'{{description}}'* for day *{{shipped}}*, with a quantity of *{{quantity}}*", @@ -98,5 +105,15 @@ "Client assignment has changed": "I did change the salesperson ~*\"<{{previousWorkerName}}>\"*~ by *\"<{{currentWorkerName}}>\"* from the client [{{clientName}} ({{clientId}})]({{{url}}})", "None": "None", "error densidad = 0": "error densidad = 0", - "nickname": "nickname" + "This document already exists on this ticket": "This document already exists on this ticket", + "serial non editable": "This serial doesn't allow to set a reference", + "nickname": "nickname", + "State": "State", + "regular": "regular", + "reserved": "reserved", + "Global invoicing failed": "[Global invoicing] Wasn't able to invoice some of the clients", + "A ticket with a negative base can't be invoiced": "A ticket with a negative base can't be invoiced", + "This client is not invoiceable": "This client is not invoiceable", + "INACTIVE_PROVIDER": "Inactive provider", + "reference duplicated": "reference duplicated" } \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index e2194b8ada..7a670d2edd 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -54,7 +54,7 @@ "This address doesn't exist": "Este consignatario no existe", "You can't create an order for a inactive client": "You can't create an order for a inactive client", "You can't create an order for a client that doesn't has tax data verified": "You can't create an order for a client that doesn't has tax data verified", - "You must delete the claim id %d first": "Antes debes borrar la reclamacion %d", + "You must delete the claim id %d first": "Antes debes borrar la reclamación %d", "You don't have enough privileges": "No tienes suficientes permisos", "Cannot check Equalization Tax in this NIF/CIF": "No se puede marcar RE en este NIF/CIF", "You can't make changes on the basic data of an confirmed order or with rows": "No puedes cambiar los datos basicos de una orden con artículos", @@ -122,7 +122,17 @@ "Swift / BIC can't be empty": "Swift / BIC no puede estar vacío", "Customs agent is required for a non UEE member": "El agente de aduanas es requerido para los clientes extracomunitarios", "Incoterms is required for a non UEE member": "El incoterms es requerido para los clientes extracomunitarios", - "Bought units from buy request": "Se ha comprado {{quantity}} unidades de {{concept}} [{{itemId}}]({{{urlItem}}}) para el ticket id [{{ticketId}}]({{{url}}})", + "Deleted sales from ticket": "He eliminado las siguientes lineas del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{deletions}}}", + "Added sale to ticket": "He añadido la siguiente linea al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{addition}}}", + "Changed sale discount": "He cambiado el descuento de las siguientes lineas al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", + "Created claim": "He creado la reclamación [{{claimId}}]({{{claimUrl}}}) de las siguientes lineas del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", + "Changed sale price": "He cambiado el precio de [{{itemId}} {{concept}}]({{{itemUrl}}}) ({{quantity}}) de {{oldPrice}}€ ➔ *{{newPrice}}€* del ticket [{{ticketId}}]({{{ticketUrl}}})", + "Changed sale quantity": "He cambiado la cantidad de [{{itemId}} {{concept}}]({{{itemUrl}}}) de {{oldQuantity}} ➔ *{{newQuantity}}* del ticket [{{ticketId}}]({{{ticketUrl}}})", + "State": "Estado", + "regular": "normal", + "reserved": "reservado", + "Changed sale reserved state": "He cambiado el estado reservado de las siguientes lineas al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", + "Bought units from buy request": "Se ha comprado {{quantity}} unidades de [{{itemId}} {{concept}}]({{{urlItem}}}) para el ticket id [{{ticketId}}]({{{url}}})", "MESSAGE_INSURANCE_CHANGE": "He cambiado el crédito asegurado del cliente [{{clientName}} ({{clientId}})]({{{url}}}) a *{{credit}} €*", "Changed client paymethod": "He cambiado la forma de pago del cliente [{{clientName}} ({{clientId}})]({{{url}}})", "Sent units from ticket": "Envio *{{quantity}}* unidades de [{{concept}} ({{itemId}})]({{{itemUrl}}}) a *\"{{nickname}}\"* provenientes del ticket id [{{ticketId}}]({{{ticketUrl}}})", @@ -133,7 +143,7 @@ "ORDER_ROW_UNAVAILABLE": "No hay disponibilidad de este producto", "Distance must be lesser than 1000": "La distancia debe ser inferior a 1000", "This ticket is deleted": "Este ticket está eliminado", - "A travel with this data already exists": "Ya existe un travel con estos datos", + "Unable to clone this travel": "No ha sido posible clonar este travel", "This thermograph id already exists": "La id del termógrafo ya existe", "Choose a date range or days forward": "Selecciona un rango de fechas o días en adelante", "ORDER_ALREADY_CONFIRMED": "ORDER_ALREADY_CONFIRMED", @@ -181,5 +191,23 @@ "This specie already exist": "Esta especie ya existe", "Client assignment has changed": "He cambiado el comercial ~*\"<{{previousWorkerName}}>\"*~ por *\"<{{currentWorkerName}}>\"* del cliente [{{clientName}} ({{clientId}})]({{{url}}})", "None": "Ninguno", - "The contract was not active during the selected date": "El contrato no estaba activo durante la fecha seleccionada" + "The contract was not active during the selected date": "El contrato no estaba activo durante la fecha seleccionada", + "This document already exists on this ticket": "Este documento ya existe en el ticket", + "Some of the selected tickets are not billable": "Algunos de los tickets seleccionados no son facturables", + "You can't invoice tickets from multiple clients": "No puedes facturar tickets de multiples clientes", + "nickname": "nickname", + "INACTIVE_PROVIDER": "Proveedor inactivo", + "This client is not invoiceable": "Este cliente no es facturable", + "serial non editable": "Esta serie no permite asignar la referencia", + "Max shipped required": "La fecha límite es requerida", + "Can't invoice to future": "No se puede facturar a futuro", + "Can't invoice to past": "No se puede facturar a pasado", + "This ticket is already invoiced": "Este ticket ya está facturado", + "A ticket with an amount of zero can't be invoiced": "No se puede facturar un ticket con importe cero", + "A ticket with a negative base can't be invoiced": "No se puede facturar un ticket con una base negativa", + "Global invoicing failed": "[Facturación global] No se han podido facturar algunos clientes", + "Wasn't able to invoice the following clients": "No se han podido facturar los siguientes clientes", + "Can't verify data unless the client has a business type": "No se puede verificar datos de un cliente que no tiene tipo de negocio", + "You don't have enough privileges to set this credit amount": "No tienes suficientes privilegios para establecer esta cantidad de crédito", + "You can't change the credit set to zero from a manager": "No puedes cambiar el cŕedito establecido a cero por un gerente" } \ No newline at end of file diff --git a/loopback/server/datasources.json b/loopback/server/datasources.json index 87fff60e15..0df03882c3 100644 --- a/loopback/server/datasources.json +++ b/loopback/server/datasources.json @@ -18,20 +18,15 @@ "acquireTimeout": 20000 }, "osticket": { - "connector": "vn-mysql", - "database": "vn", - "debug": false, - "host": "localhost", - "port": "3306", - "username": "root", - "password": "root" + "connector": "memory", + "timezone": "local" }, "tempStorage": { "name": "tempStorage", "connector": "loopback-component-storage", - "provider": "filesystem", + "provider": "filesystem", "root": "./storage/tmp", - "maxFileSize": "262144000", + "maxFileSize": "262144000", "allowedContentTypes": [ "application/x-7z-compressed", "application/x-zip-compressed", @@ -41,17 +36,17 @@ "application/zip", "application/rar", "multipart/x-zip", - "image/png", - "image/jpeg", + "image/png", + "image/jpeg", "image/jpg" ] }, "dmsStorage": { "name": "dmsStorage", "connector": "loopback-component-storage", - "provider": "filesystem", + "provider": "filesystem", "root": "./storage/dms", - "maxFileSize": "262144000", + "maxFileSize": "262144000", "allowedContentTypes": [ "application/x-7z-compressed", "application/x-zip-compressed", @@ -61,32 +56,32 @@ "application/zip", "application/rar", "multipart/x-zip", - "image/png", - "image/jpeg", + "image/png", + "image/jpeg", "image/jpg" ] }, "imageStorage": { "name": "imageStorage", "connector": "loopback-component-storage", - "provider": "filesystem", + "provider": "filesystem", "root": "./storage/image", - "maxFileSize": "52428800", + "maxFileSize": "52428800", "allowedContentTypes": [ - "image/png", - "image/jpeg", + "image/png", + "image/jpeg", "image/jpg" ] }, "invoiceStorage": { "name": "invoiceStorage", "connector": "loopback-component-storage", - "provider": "filesystem", + "provider": "filesystem", "root": "./storage/pdfs/invoice", - "maxFileSize": "52428800", + "maxFileSize": "52428800", "allowedContentTypes": [ "application/octet-stream", "application/pdf" ] } -} +} \ No newline at end of file diff --git a/modules/claim/back/methods/claim-dms/specs/removeFile.spec.js b/modules/claim/back/methods/claim-dms/specs/removeFile.spec.js index b1cd5686ad..1cd3b16cb6 100644 --- a/modules/claim/back/methods/claim-dms/specs/removeFile.spec.js +++ b/modules/claim/back/methods/claim-dms/specs/removeFile.spec.js @@ -3,7 +3,7 @@ const app = require('vn-loopback/server/server'); describe('TicketDms removeFile()', () => { const ticketDmsId = 1; it(`should return an error for a user without enough privileges`, async() => { - let clientId = 101; + let clientId = 1101; let ctx = {req: {accessToken: {userId: clientId}}}; let error; diff --git a/modules/claim/back/methods/claim/createFromSales.js b/modules/claim/back/methods/claim/createFromSales.js index 32d1edd97e..f22aabbf36 100644 --- a/modules/claim/back/methods/claim/createFromSales.js +++ b/modules/claim/back/methods/claim/createFromSales.js @@ -3,17 +3,20 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('createFromSales', { description: 'Create a claim', - accepts: [{ - arg: 'ticketId', - type: 'Number', - required: true, - description: 'The origin ticket id' - }, { - arg: 'sales', - type: ['Object'], - required: true, - description: 'The claimed sales' - }], + accepts: [ + { + arg: 'ticketId', + type: 'number', + required: true, + description: 'The origin ticket id' + }, + { + arg: 'sales', + type: ['object'], + required: true, + description: 'The claimed sales' + } + ], returns: { type: 'object', root: true @@ -25,8 +28,10 @@ module.exports = Self => { }); Self.createFromSales = async(ctx, ticketId, sales, options) => { + const $t = ctx.req.__; // $translate + const models = Self.app.models; let tx; - let myOptions = {}; + const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); @@ -35,11 +40,23 @@ module.exports = Self => { tx = await Self.beginTransaction({}); myOptions.transaction = tx; } - const models = Self.app.models; const userId = ctx.req.accessToken.userId; try { - const ticket = await models.Ticket.findById(ticketId, null, myOptions); + const ticket = await models.Ticket.findById(ticketId, { + include: { + relation: 'client', + scope: { + include: { + relation: 'salesPersonUser', + scope: { + fields: ['id', 'name'] + } + } + } + } + }, myOptions); + if (ticket.isDeleted) throw new UserError(`You can't create a claim for a removed ticket`); @@ -49,6 +66,8 @@ module.exports = Self => { ticketCreated: ticket.shipped, workerFk: userId }, myOptions); + + let changesMade = ''; const promises = []; for (const sale of sales) { @@ -59,10 +78,25 @@ module.exports = Self => { }, myOptions); promises.push(newClaimBeginning); + changesMade += `\r\n-${sale.itemFk}: ${sale.concept} (${sale.quantity})`; } await Promise.all(promises); + const salesPerson = ticket.client().salesPersonUser(); + if (salesPerson) { + const origin = ctx.req.headers.origin; + + const message = $t('Created claim', { + claimId: newClaim.id, + ticketId: ticketId, + ticketUrl: `${origin}/#!/ticket/${ticketId}/sale`, + claimUrl: `${origin}/#!/claim/${newClaim.id}/summary`, + changes: changesMade + }); + await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); + } + if (tx) await tx.commit(); return newClaim; diff --git a/modules/claim/back/methods/claim/filter.js b/modules/claim/back/methods/claim/filter.js index 50d20410bd..16f23433b3 100644 --- a/modules/claim/back/methods/claim/filter.js +++ b/modules/claim/back/methods/claim/filter.js @@ -79,10 +79,14 @@ module.exports = Self => { } }); - Self.filter = async(ctx, filter) => { - let conn = Self.dataSource.connector; + Self.filter = async(ctx, filter, options) => { + const conn = Self.dataSource.connector; + const myOptions = {}; - let where = buildFilter(ctx.args, (param, value) => { + if (typeof options == 'object') + Object.assign(myOptions, options); + + const where = buildFilter(ctx.args, (param, value) => { switch (param) { case 'search': return /^\d+$/.test(value) @@ -111,10 +115,9 @@ module.exports = Self => { filter = mergeFilters(ctx.args.filter, {where}); - let stmts = []; - let stmt; + const stmts = []; - stmt = new ParameterizedSQL( + const stmt = new ParameterizedSQL( `SELECT cl.id, c.name, cl.clientFk, cl.workerFk, u.name AS userName, cs.description, cl.created FROM claim cl LEFT JOIN client c ON c.id = cl.clientFk @@ -124,10 +127,11 @@ module.exports = Self => { ); stmt.merge(conn.makeSuffix(filter)); - let itemsIndex = stmts.push(stmt) - 1; + const itemsIndex = stmts.push(stmt) - 1; + + const sql = ParameterizedSQL.join(stmts, ';'); + const result = await conn.executeStmt(sql, myOptions); - let sql = ParameterizedSQL.join(stmts, ';'); - let result = await conn.executeStmt(sql); return itemsIndex === 0 ? result : result[itemsIndex]; }; }; diff --git a/modules/claim/back/methods/claim/getSummary.js b/modules/claim/back/methods/claim/getSummary.js index 9b04d29a9e..512e4a77f1 100644 --- a/modules/claim/back/methods/claim/getSummary.js +++ b/modules/claim/back/methods/claim/getSummary.js @@ -19,12 +19,16 @@ module.exports = Self => { } }); - Self.getSummary = async id => { - let promises = []; - let summary = {}; + Self.getSummary = async(id, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const promises = []; + const summary = {}; // Claim - let filter = { where: {id: id}, include: [ @@ -61,13 +65,14 @@ module.exports = Self => { ] }; - promises.push(Self.app.models.Claim.find(filter)); + promises.push(Self.app.models.Claim.find(filter, myOptions)); // Claim detail filter = { where: {claimFk: id}, include: [ - {relation: 'sale', + { + relation: 'sale', scope: { fields: ['concept', 'ticketFk', 'price', 'quantity', 'discount', 'itemFk'], include: { @@ -77,7 +82,7 @@ module.exports = Self => { } ] }; - promises.push(Self.app.models.ClaimBeginning.find(filter)); + promises.push(Self.app.models.ClaimBeginning.find(filter, myOptions)); // Claim developments filter = { @@ -109,7 +114,7 @@ module.exports = Self => { } ] }; - promises.push(Self.app.models.ClaimDevelopment.find(filter)); + promises.push(Self.app.models.ClaimDevelopment.find(filter, myOptions)); // Claim action filter = { @@ -126,9 +131,9 @@ module.exports = Self => { {relation: 'claimBeggining'} ] }; - promises.push(Self.app.models.ClaimEnd.find(filter)); + promises.push(Self.app.models.ClaimEnd.find(filter, myOptions)); - let res = await Promise.all(promises); + const res = await Promise.all(promises); [summary.claim] = res[0]; summary.salesClaimed = res[1]; diff --git a/modules/claim/back/methods/claim/isEditable.js b/modules/claim/back/methods/claim/isEditable.js index ce68153b5c..cd14d70c78 100644 --- a/modules/claim/back/methods/claim/isEditable.js +++ b/modules/claim/back/methods/claim/isEditable.js @@ -19,15 +19,21 @@ module.exports = Self => { } }); - Self.isEditable = async(ctx, id) => { + Self.isEditable = async(ctx, id, options) => { const userId = ctx.req.accessToken.userId; - const isClaimManager = await Self.app.models.Account.hasRole(userId, 'claimManager'); + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const isClaimManager = await Self.app.models.Account.hasRole(userId, 'claimManager', myOptions); + const claim = await Self.app.models.Claim.findById(id, { fields: ['claimStateFk'], include: [{ relation: 'claimState' }] - }); + }, myOptions); const isClaimResolved = claim && claim.claimState().code == 'resolved'; diff --git a/modules/claim/back/methods/claim/regularizeClaim.js b/modules/claim/back/methods/claim/regularizeClaim.js index 16ef1adfe8..2106ab2108 100644 --- a/modules/claim/back/methods/claim/regularizeClaim.js +++ b/modules/claim/back/methods/claim/regularizeClaim.js @@ -77,12 +77,13 @@ module.exports = Self => { }, myOptions); if (!ticketFk) { - ticketFk = await createTicket(ctx, { + ctx.args = { clientId: address.clientFk, warehouseId: sale.ticket().warehouseFk, companyId: sale.ticket().companyFk, addressId: addressId - }, myOptions); + }; + ticketFk = await createTicket(ctx, myOptions); } await models.Sale.create({ @@ -153,22 +154,13 @@ module.exports = Self => { return ticket && ticket.id; } - async function createTicket(ctx, params, options) { - params.shipped = new Date(); - params.landed = new Date(); - params.agencyModeId = null; - params.routeId = null; + async function createTicket(ctx, options) { + ctx.args.shipped = new Date(); + ctx.args.landed = new Date(); + ctx.args.agencyModeId = null; + ctx.args.routeId = null; - const ticket = await Self.app.models.Ticket.new(ctx, - params.clientId, - params.shipped, - params.landed, - params.warehouseId, - params.companyId, - params.addressId, - params.agencyModeId, - params.routeId, - options); + const ticket = await Self.app.models.Ticket.new(ctx, options); return ticket.id; } diff --git a/modules/claim/back/methods/claim/specs/createFromSales.spec.js b/modules/claim/back/methods/claim/specs/createFromSales.spec.js index f089140252..849ccf8f51 100644 --- a/modules/claim/back/methods/claim/specs/createFromSales.spec.js +++ b/modules/claim/back/methods/claim/specs/createFromSales.spec.js @@ -7,7 +7,13 @@ describe('Claim createFromSales()', () => { instance: 0, quantity: 10 }]; - const ctx = {req: {accessToken: {userId: 1}}}; + const ctx = { + req: { + accessToken: {userId: 1}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; it('should create a new claim', async() => { const tx = await app.models.Claim.beginTransaction({}); diff --git a/modules/claim/back/methods/claim/specs/filter.spec.js b/modules/claim/back/methods/claim/specs/filter.spec.js index 187fffaa4e..b26afe8c4d 100644 --- a/modules/claim/back/methods/claim/specs/filter.spec.js +++ b/modules/claim/back/methods/claim/specs/filter.spec.js @@ -2,26 +2,59 @@ const app = require('vn-loopback/server/server'); describe('claim filter()', () => { it('should return 1 result filtering by id', async() => { - let result = await app.models.Claim.filter({args: {filter: {}, search: 1}}); + const tx = await app.models.Claim.beginTransaction({}); - expect(result.length).toEqual(1); - expect(result[0].id).toEqual(1); + try { + const options = {transaction: tx}; + + const result = await app.models.Claim.filter({args: {filter: {}, search: 1}}, null, options); + + expect(result.length).toEqual(1); + expect(result[0].id).toEqual(1); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return 1 result filtering by string', async() => { - let result = await app.models.Claim.filter({args: {filter: {}, search: 'Tony Stark'}}); + const tx = await app.models.Claim.beginTransaction({}); - expect(result.length).toEqual(1); - expect(result[0].id).toEqual(4); + try { + const options = {transaction: tx}; + + const result = await app.models.Claim.filter({args: {filter: {}, search: 'Tony Stark'}}, null, options); + + expect(result.length).toEqual(1); + expect(result[0].id).toEqual(4); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return 4 results filtering by worker id', async() => { - let result = await app.models.Claim.filter({args: {filter: {}, workerFk: 18}}); + const tx = await app.models.Claim.beginTransaction({}); - expect(result.length).toEqual(4); - expect(result[0].id).toEqual(1); - expect(result[1].id).toEqual(2); - expect(result[2].id).toEqual(3); - expect(result[3].id).toEqual(4); + try { + const options = {transaction: tx}; + + const result = await app.models.Claim.filter({args: {filter: {}, workerFk: 18}}, null, options); + + expect(result.length).toEqual(4); + expect(result[0].id).toEqual(1); + expect(result[1].id).toEqual(2); + expect(result[2].id).toEqual(3); + expect(result[3].id).toEqual(4); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/claim/back/methods/claim/specs/getSummary.spec.js b/modules/claim/back/methods/claim/specs/getSummary.spec.js index 4459033772..541f42cfbe 100644 --- a/modules/claim/back/methods/claim/specs/getSummary.spec.js +++ b/modules/claim/back/methods/claim/specs/getSummary.spec.js @@ -2,12 +2,23 @@ const app = require('vn-loopback/server/server'); describe('claim getSummary()', () => { it('should return summary with claim, salesClaimed, developments and actions defined ', async() => { - let result = await app.models.Claim.getSummary(1); - let keys = Object.keys(result); + const tx = await app.models.Claim.beginTransaction({}); - expect(keys).toContain('claim'); - expect(keys).toContain('salesClaimed'); - expect(keys).toContain('developments'); - expect(keys).toContain('actions'); + try { + const options = {transaction: tx}; + + const result = await app.models.Claim.getSummary(1, options); + const keys = Object.keys(result); + + expect(keys).toContain('claim'); + expect(keys).toContain('salesClaimed'); + expect(keys).toContain('developments'); + expect(keys).toContain('actions'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/claim/back/methods/claim/specs/isEditable.spec.js b/modules/claim/back/methods/claim/specs/isEditable.spec.js index 19436e16fa..3afea78434 100644 --- a/modules/claim/back/methods/claim/specs/isEditable.spec.js +++ b/modules/claim/back/methods/claim/specs/isEditable.spec.js @@ -4,30 +4,74 @@ describe('claim isEditable()', () => { const salesPerdonId = 18; const claimManagerId = 72; it('should return false if the given claim does not exist', async() => { - let ctx = {req: {accessToken: {userId: claimManagerId}}}; - let result = await app.models.Claim.isEditable(ctx, 99999); + const tx = await app.models.Claim.beginTransaction({}); - expect(result).toEqual(false); + try { + const options = {transaction: tx}; + + const ctx = {req: {accessToken: {userId: claimManagerId}}}; + const result = await app.models.Claim.isEditable(ctx, 99999, options); + + expect(result).toEqual(false); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should not be able to edit a resolved claim for a salesPerson', async() => { - let ctx = {req: {accessToken: {userId: salesPerdonId}}}; - let result = await app.models.Claim.isEditable(ctx, 4); + const tx = await app.models.Claim.beginTransaction({}); - expect(result).toEqual(false); + try { + const options = {transaction: tx}; + + const ctx = {req: {accessToken: {userId: salesPerdonId}}}; + const result = await app.models.Claim.isEditable(ctx, 4, options); + + expect(result).toEqual(false); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should be able to edit a resolved claim for a claimManager', async() => { - let ctx = {req: {accessToken: {userId: claimManagerId}}}; - let result = await app.models.Claim.isEditable(ctx, 4); + const tx = await app.models.Claim.beginTransaction({}); - expect(result).toEqual(true); + try { + const options = {transaction: tx}; + + const ctx = {req: {accessToken: {userId: claimManagerId}}}; + const result = await app.models.Claim.isEditable(ctx, 4, options); + + expect(result).toEqual(true); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should be able to edit a claim for a claimManager', async() => { - let ctx = {req: {accessToken: {userId: salesPerdonId}}}; - let result = await app.models.Claim.isEditable(ctx, 1); + const tx = await app.models.Claim.beginTransaction({}); - expect(result).toEqual(true); + try { + const options = {transaction: tx}; + + const ctx = {req: {accessToken: {userId: salesPerdonId}}}; + const result = await app.models.Claim.isEditable(ctx, 1, options); + + expect(result).toEqual(true); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js index 5430019226..8ea310772e 100644 --- a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js @@ -1,6 +1,6 @@ const app = require('vn-loopback/server/server'); -describe('regularizeClaim()', () => { +describe('claim regularizeClaim()', () => { const ctx = { req: { accessToken: {userId: 18}, diff --git a/modules/claim/back/methods/claim/specs/updateClaim.spec.js b/modules/claim/back/methods/claim/specs/updateClaim.spec.js index a5de92ccff..de7209c18c 100644 --- a/modules/claim/back/methods/claim/specs/updateClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/updateClaim.spec.js @@ -4,7 +4,7 @@ describe('Update Claim', () => { const newDate = new Date(); const originalData = { ticketFk: 3, - clientFk: 101, + clientFk: 1101, ticketCreated: newDate, workerFk: 18, claimStateFk: 2, diff --git a/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js b/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js index 8cdcea4dab..4cd4ce528c 100644 --- a/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js +++ b/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js @@ -4,7 +4,7 @@ describe('Update Claim', () => { const newDate = new Date(); const original = { ticketFk: 3, - clientFk: 101, + clientFk: 1101, ticketCreated: newDate, workerFk: 18, claimStateFk: 2, diff --git a/modules/claim/front/action/index.spec.js b/modules/claim/front/action/index.spec.js index 06154e5b67..9fb9b75ebf 100644 --- a/modules/claim/front/action/index.spec.js +++ b/modules/claim/front/action/index.spec.js @@ -148,7 +148,7 @@ describe('claim', () => { return resolve(true); })); - controller.claim.clientFk = 101; + controller.claim.clientFk = 1101; controller.claim.id = 11; controller.onUpdateGreugeAccept().then(() => { @@ -166,7 +166,7 @@ describe('claim', () => { const freightPickUpPrice = 11; const greugeTypeId = 7; const expectedData = { - clientFk: 101, + clientFk: 1101, description: `claim: ${controller.claim.id}`, amount: freightPickUpPrice, greugeTypeFk: greugeTypeId, diff --git a/modules/claim/front/descriptor/index.spec.js b/modules/claim/front/descriptor/index.spec.js index bca47409c9..669a739545 100644 --- a/modules/claim/front/descriptor/index.spec.js +++ b/modules/claim/front/descriptor/index.spec.js @@ -6,7 +6,7 @@ describe('Item Component vnClaimDescriptor', () => { const claim = { id: 2, - clientFk: 101, + clientFk: 1101, client: {email: 'client@email'} }; diff --git a/modules/claim/front/photos/index.spec.js b/modules/claim/front/photos/index.spec.js index 38e77d13fa..84df48b447 100644 --- a/modules/claim/front/photos/index.spec.js +++ b/modules/claim/front/photos/index.spec.js @@ -16,7 +16,7 @@ describe('Claim', () => { controller.$.model = crudModel; controller.claim = { id: 1, - client: {id: 101, name: 'Bruce Wayne'} + client: {id: 1101, name: 'Bruce Wayne'} }; })); diff --git a/modules/client/back/methods/client-dms/removeFile.js b/modules/client/back/methods/client-dms/removeFile.js index 5ff1236308..786a329289 100644 --- a/modules/client/back/methods/client-dms/removeFile.js +++ b/modules/client/back/methods/client-dms/removeFile.js @@ -4,12 +4,12 @@ module.exports = Self => { accessType: 'WRITE', accepts: { arg: 'id', - type: 'Number', + type: 'number', description: 'The document id', http: {source: 'path'} }, returns: { - type: 'Object', + type: 'object', root: true }, http: { @@ -18,13 +18,33 @@ module.exports = Self => { } }); - Self.removeFile = async(ctx, id) => { + Self.removeFile = async(ctx, id, options) => { const models = Self.app.models; - const clientDms = await Self.findById(id); + let tx; + const myOptions = {}; - await models.Dms.removeFile(ctx, clientDms.dmsFk); + if (typeof options == 'object') + Object.assign(myOptions, options); - return clientDms.destroy(); + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const clientDms = await Self.findById(id, null, myOptions); + + await models.Dms.removeFile(ctx, clientDms.dmsFk, myOptions); + + const destroyedClient = await clientDms.destroy(myOptions); + + if (tx) await tx.commit(); + + return destroyedClient; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } }; }; diff --git a/modules/client/back/methods/client-dms/specs/removeFile.spec.js b/modules/client/back/methods/client-dms/specs/removeFile.spec.js index 01cf1977b1..6dac712932 100644 --- a/modules/client/back/methods/client-dms/specs/removeFile.spec.js +++ b/modules/client/back/methods/client-dms/specs/removeFile.spec.js @@ -1,17 +1,24 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('ClientDms removeFile()', () => { - const clientDmsFk = 3; it(`should return an error for a user without enough privileges`, async() => { - let clientId = 101; - let ctx = {req: {accessToken: {userId: clientId}}}; + const tx = await models.Client.beginTransaction({}); let error; - await app.models.ClientDms.removeFile(ctx, clientDmsFk).catch(e => { + + try { + const options = {transaction: tx}; + const clientDmsFk = 3; + const clientId = 1101; + const ctx = {req: {accessToken: {userId: clientId}}}; + + await models.ClientDms.removeFile(ctx, clientDmsFk, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); error = e; - }).finally(() => { - expect(error.message).toEqual(`You don't have enough privileges`); - }); + } expect(error).toBeDefined(); }); diff --git a/modules/client/back/methods/client/addressesPropagateRe.js b/modules/client/back/methods/client/addressesPropagateRe.js index 31cafa6546..bd6742cbb5 100644 --- a/modules/client/back/methods/client/addressesPropagateRe.js +++ b/modules/client/back/methods/client/addressesPropagateRe.js @@ -12,7 +12,7 @@ module.exports = function(Self) { }, { arg: 'data', - type: 'Object', + type: 'object', required: true, description: 'data with new value', http: {source: 'body'} @@ -29,12 +29,21 @@ module.exports = function(Self) { } }); - Self.addressesPropagateRe = async(id, data) => { - if (data.hasOwnProperty('isEqualizated')) { - let client = await Self.app.models.Client.findById(id); + Self.addressesPropagateRe = async(id, data, options) => { + const models = Self.app.models; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const isEqualizated = Object.prototype.hasOwnProperty.call(data, 'isEqualizated'); + if (isEqualizated) { + const client = await models.Client.findById(id, null, myOptions); + if (client) { - await Self.app.models.Address.updateAll({clientFk: id}, data); - await client.updateAttributes({hasToInvoiceByAddress: false}); + await models.Address.updateAll({clientFk: id}, data, myOptions); + await client.updateAttributes({hasToInvoiceByAddress: false}, myOptions); + return true; } } diff --git a/modules/client/back/methods/client/canBeInvoiced.js b/modules/client/back/methods/client/canBeInvoiced.js index 1f695aba81..d8a126ed20 100644 --- a/modules/client/back/methods/client/canBeInvoiced.js +++ b/modules/client/back/methods/client/canBeInvoiced.js @@ -5,7 +5,7 @@ module.exports = function(Self) { accepts: [ { arg: 'id', - type: 'string', + type: 'number', required: true, description: 'Client id', http: {source: 'path'} @@ -22,8 +22,18 @@ module.exports = function(Self) { } }); - Self.canBeInvoiced = async id => { - let client = await Self.app.models.Client.findById(id, {fields: ['id', 'isTaxDataChecked', 'hasToInvoice']}); + Self.canBeInvoiced = async(id, options) => { + const models = Self.app.models; + + let myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const client = await models.Client.findById(id, { + fields: ['id', 'isTaxDataChecked', 'hasToInvoice'] + }, myOptions); + if (client.isTaxDataChecked && client.hasToInvoice) return true; diff --git a/modules/client/back/methods/client/canCreateTicket.js b/modules/client/back/methods/client/canCreateTicket.js index a47a5f6f34..fa10c0172e 100644 --- a/modules/client/back/methods/client/canCreateTicket.js +++ b/modules/client/back/methods/client/canCreateTicket.js @@ -20,8 +20,15 @@ module.exports = Self => { } }); - Self.canCreateTicket = async id => { - const client = await Self.app.models.Client.findById(id); + Self.canCreateTicket = async(id, options) => { + const models = Self.app.models; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const client = await models.Client.findById(id, null, myOptions); + const canCreateTicket = client && client.isActive; if (!canCreateTicket) return false; diff --git a/modules/client/back/methods/client/confirmTransaction.js b/modules/client/back/methods/client/confirmTransaction.js index 467a8627ba..a1969d6fd7 100644 --- a/modules/client/back/methods/client/confirmTransaction.js +++ b/modules/client/back/methods/client/confirmTransaction.js @@ -9,7 +9,7 @@ module.exports = Self => { description: 'Transaction id' }], returns: { - type: 'Object', + type: 'object', root: true }, http: { @@ -18,23 +18,32 @@ module.exports = Self => { } }); - Self.confirmTransaction = async(ctx, id) => { - let userId = ctx.req.accessToken.userId; - let tx = await Self.beginTransaction({}); + Self.confirmTransaction = async(ctx, id, options) => { + const models = Self.app.models; + const userId = ctx.req.accessToken.userId; + + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } try { - let options = {transaction: tx}; + const oldTpvTransaction = await models.TpvTransaction.findById(id, null, myOptions); - let oldTpvTransaction = await Self.app.models.TpvTransaction.findById(id, null, options); + const confirm = await Self.rawSql('CALL hedera.tpvTransaction_confirmById(?)', [id], myOptions); - let confirm = await Self.rawSql('CALL hedera.tpvTransaction_confirmById(?)', [id], options); + const tpvTransaction = await models.TpvTransaction.findById(id, null, myOptions); - let tpvTransaction = await Self.app.models.TpvTransaction.findById(id, null, options); + const oldInstance = {status: oldTpvTransaction.status}; + const newInstance = {status: tpvTransaction.status}; - let oldInstance = {status: oldTpvTransaction.status}; - let newInstance = {status: tpvTransaction.status}; - - let logRecord = { + const logRecord = { originFk: tpvTransaction.clientFk, userFk: userId, action: 'update', @@ -44,12 +53,13 @@ module.exports = Self => { newInstance: newInstance }; - await Self.app.models.ClientLog.create(logRecord, options); + await models.ClientLog.create(logRecord, myOptions); + + if (tx) await tx.commit(); - await tx.commit(); return confirm; } catch (e) { - await tx.rollback(); + if (tx) await tx.rollback(); throw e; } }; diff --git a/modules/client/back/methods/client/consumption.js b/modules/client/back/methods/client/consumption.js index 8430c4661c..0e94608a31 100644 --- a/modules/client/back/methods/client/consumption.js +++ b/modules/client/back/methods/client/consumption.js @@ -10,44 +10,52 @@ module.exports = Self => { accepts: [ { arg: 'filter', - type: 'Object', + type: 'object', description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string' - }, { + }, + { arg: 'search', - type: 'String', + type: 'string', description: `If it's and integer searchs by id, otherwise it searchs by name` - }, { + }, + { arg: 'itemId', - type: 'Number', + type: 'number', description: 'Item id' - }, { + }, + { arg: 'categoryId', - type: 'Number', + type: 'number', description: 'Category id' - }, { + }, + { arg: 'typeId', - type: 'Number', + type: 'number', description: 'Item type id', - }, { + }, + { arg: 'buyerId', - type: 'Number', + type: 'number', description: 'Buyer id' - }, { + }, + { arg: 'from', - type: 'Date', + type: 'date', description: `The from date filter` - }, { + }, + { arg: 'to', - type: 'Date', + type: 'date', description: `The to date filter` - }, { + }, + { arg: 'grouped', - type: 'Boolean', + type: 'boolean', description: 'Group by item' } ], returns: { - type: ['Object'], + type: ['object'], root: true }, http: { @@ -56,7 +64,12 @@ module.exports = Self => { } }); - Self.consumption = async(ctx, filter) => { + Self.consumption = async(ctx, filter, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + const conn = Self.dataSource.connector; const args = ctx.args; const where = buildFilter(ctx.args, (param, value) => { @@ -83,7 +96,7 @@ module.exports = Self => { }); filter = mergeFilters(filter, {where}); - let stmt = new ParameterizedSQL('SELECT'); + const stmt = new ParameterizedSQL('SELECT'); if (args.grouped) stmt.merge(`SUM(s.quantity) AS quantity,`); else @@ -121,6 +134,6 @@ module.exports = Self => { stmt.merge(conn.makePagination(filter)); - return conn.executeStmt(stmt); + return conn.executeStmt(stmt, myOptions); }; }; diff --git a/modules/client/back/methods/client/createAddress.js b/modules/client/back/methods/client/createAddress.js index 450b167224..8e6db2a22d 100644 --- a/modules/client/back/methods/client/createAddress.js +++ b/modules/client/back/methods/client/createAddress.js @@ -62,7 +62,7 @@ module.exports = function(Self) { }], returns: { root: true, - type: 'Object' + type: 'object' }, http: { verb: 'post', @@ -70,18 +70,26 @@ module.exports = function(Self) { } }); - Self.createAddress = async(ctx, clientFk) => { + Self.createAddress = async(ctx, clientFk, options) => { const models = Self.app.models; const args = ctx.args; - const tx = await models.Address.beginTransaction({}); + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } try { - const options = {transaction: tx}; const province = await models.Province.findById(args.provinceFk, { include: { relation: 'country' } - }, options); + }, myOptions); const isUeeMember = province.country().isUeeMember; if (!isUeeMember && !args.incotermsFk) @@ -91,19 +99,20 @@ module.exports = function(Self) { throw new UserError(`Customs agent is required for a non UEE member`); delete args.ctx; // Remove unwanted properties - const newAddress = await models.Address.create(args, options); - const client = await Self.findById(clientFk, null, options); + const newAddress = await models.Address.create(args, myOptions); + const client = await Self.findById(clientFk, null, myOptions); if (args.isDefaultAddress) { await client.updateAttributes({ defaultAddressFk: newAddress.id - }, options); + }, myOptions); } - await tx.commit(); + if (tx) await tx.commit(); + return newAddress; } catch (e) { - await tx.rollback(); + if (tx) await tx.rollback(); throw e; } }; diff --git a/modules/client/back/methods/client/createReceipt.js b/modules/client/back/methods/client/createReceipt.js index 7eb47e70a1..131a1d61f1 100644 --- a/modules/client/back/methods/client/createReceipt.js +++ b/modules/client/back/methods/client/createReceipt.js @@ -48,19 +48,26 @@ module.exports = function(Self) { } }); - Self.createReceipt = async ctx => { + Self.createReceipt = async(ctx, options) => { const models = Self.app.models; const args = ctx.args; - const tx = await models.Address.beginTransaction({}); + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } try { - const options = {transaction: tx}; - delete args.ctx; // Remove unwanted properties - const newReceipt = await models.Receipt.create(args, options); - const clientOriginal = await models.Client.findById(args.clientFk); - const bank = await models.Bank.findById(args.bankFk); - const accountingType = await models.AccountingType.findById(bank.accountingTypeFk); + const newReceipt = await models.Receipt.create(args, myOptions); + const originalClient = await models.Client.findById(args.clientFk, null, myOptions); + const bank = await models.Bank.findById(args.bankFk, null, myOptions); + const accountingType = await models.AccountingType.findById(bank.accountingTypeFk, null, myOptions); if (accountingType.code == 'compensation') { if (!args.compensationAccount) @@ -70,14 +77,16 @@ module.exports = function(Self) { where: { account: args.compensationAccount } - }); + }, myOptions); + let clientCompensation = {}; + if (!supplierCompensation) { clientCompensation = await models.Client.findOne({ where: { accountingAccount: args.compensationAccount } - }); + }, myOptions); } if (!supplierCompensation && !clientCompensation) throw new UserError('Invalid account'); @@ -87,20 +96,21 @@ module.exports = function(Self) { [ args.compensationAccount, args.bankFk, - accountingType.receiptDescription + clientOriginal.accountingAccount, + accountingType.receiptDescription + originalClient.accountingAccount, args.amountPaid, args.companyFk, - clientOriginal.accountingAccount + originalClient.accountingAccount ], - options); + myOptions + ); } else if (accountingType.isAutoConciliated == true) { - const description = `${clientOriginal.id} : ${clientOriginal.socialName} - ${accountingType.receiptDescription}`; + const description = `${originalClient.id} : ${originalClient.socialName} - ${accountingType.receiptDescription}`; const [xdiarioNew] = await Self.rawSql( `SELECT xdiario_new(?, CURDATE(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ledger;`, [ null, bank.account, - clientOriginal.accountingAccount, + originalClient.accountingAccount, description, args.amountPaid, 0, @@ -112,13 +122,14 @@ module.exports = function(Self) { false, args.companyFk ], - options); + myOptions + ); await Self.rawSql( `SELECT xdiario_new(?, CURDATE(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, [ xdiarioNew.ledger, - clientOriginal.accountingAccount, + originalClient.accountingAccount, bank.account, description, 0, @@ -131,13 +142,15 @@ module.exports = function(Self) { false, args.companyFk ], - options); + myOptions + ); } - await tx.commit(); + if (tx) await tx.commit(); + return newReceipt; } catch (e) { - await tx.rollback(); + if (tx) await tx.rollback(); throw e; } }; diff --git a/modules/client/back/methods/client/createWithUser.js b/modules/client/back/methods/client/createWithUser.js index 79713b467a..f32979d52b 100644 --- a/modules/client/back/methods/client/createWithUser.js +++ b/modules/client/back/methods/client/createWithUser.js @@ -16,22 +16,29 @@ module.exports = function(Self) { } }); - Self.createWithUser = async data => { - let firstEmail = data.email ? data.email.split(',')[0] : null; - let user = { + Self.createWithUser = async(data, options) => { + const models = Self.app.models; + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + const firstEmail = data.email ? data.email.split(',')[0] : null; + const user = { name: data.userName, email: firstEmail, password: parseInt(Math.random() * 100000000000000) }; - const Account = Self.app.models.Account; - const Address = Self.app.models.Address; - const tx = await Account.beginTransaction({}); try { - let options = {transaction: tx}; - - let account = await Account.create(user, options); - let client = await Self.create({ + const account = await models.Account.create(user, myOptions); + const client = await Self.create({ id: account.id, name: data.name, fi: data.fi, @@ -44,9 +51,9 @@ module.exports = function(Self) { provinceFk: data.provinceFk, countryFk: data.countryFk, isEqualizated: data.isEqualizated - }, options); + }, myOptions); - let address = await Address.create({ + const address = await models.Address.create({ clientFk: client.id, nickname: client.name, city: client.city, @@ -55,16 +62,17 @@ module.exports = function(Self) { provinceFk: client.provinceFk, isEqualizated: client.isEqualizated, isActive: true - }, options); + }, myOptions); await client.updateAttributes({ defaultAddressFk: address.id - }, options); + }, myOptions); + + if (tx) await tx.commit(); - await tx.commit(); return client; } catch (e) { - await tx.rollback(); + if (tx) await tx.rollback(); throw e; } }; diff --git a/modules/client/back/methods/client/getAverageInvoiced.js b/modules/client/back/methods/client/getAverageInvoiced.js index 5c806879cd..95d01a88cf 100644 --- a/modules/client/back/methods/client/getAverageInvoiced.js +++ b/modules/client/back/methods/client/getAverageInvoiced.js @@ -19,9 +19,14 @@ module.exports = Self => { } }); - Self.getAverageInvoiced = async clientFk => { - let query = `SELECT invoiced FROM vn.annualAverageInvoiced WHERE clientFk = ?`; - let [invoiced] = await Self.rawSql(query, [clientFk]); + Self.getAverageInvoiced = async(clientFk, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const query = `SELECT invoiced FROM vn.annualAverageInvoiced WHERE clientFk = ?`; + const [invoiced] = await Self.rawSql(query, [clientFk], myOptions); return invoiced; }; diff --git a/modules/client/back/methods/client/getCard.js b/modules/client/back/methods/client/getCard.js index 5379f4e0e1..c3ce00bf3f 100644 --- a/modules/client/back/methods/client/getCard.js +++ b/modules/client/back/methods/client/getCard.js @@ -9,7 +9,7 @@ module.exports = function(Self) { http: {source: 'path'} }, returns: { - type: 'Object', + type: 'object', root: true }, http: { @@ -18,8 +18,13 @@ module.exports = function(Self) { } }); - Self.getCard = async function(id) { - let client = await Self.findOne({ + Self.getCard = async(id, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const client = await Self.findOne({ where: { id: id }, @@ -29,38 +34,44 @@ module.exports = function(Self) { scope: { fields: ['id', 'name'] } - }, { + }, + { relation: 'province', scope: { fields: ['id', 'name'] } - }, { - }, { + }, + { relation: 'salesPersonUser', scope: { fields: ['id', 'name'] } - }, { + }, + { relation: 'country', scope: { fields: ['id', 'country'] } - }, { + }, + { relation: 'payMethod', scope: { fields: ['id', 'name'] } - }, { + }, + { relation: 'account', scope: { fields: ['id', 'name', 'active'] } } ] - }); + }, myOptions); - let query = `SELECT vn.clientGetDebt(?, CURDATE()) AS debt`; - client.debt = (await Self.rawSql(query, [id]))[0].debt; + const query = `SELECT vn.clientGetDebt(?, CURDATE()) AS debt`; + const data = await Self.rawSql(query, [id], myOptions); + + client.debt = data[0].debt; return client; }; diff --git a/modules/client/back/methods/client/getDebt.js b/modules/client/back/methods/client/getDebt.js index c4f1677310..8eb0f2480e 100644 --- a/modules/client/back/methods/client/getDebt.js +++ b/modules/client/back/methods/client/getDebt.js @@ -19,9 +19,14 @@ module.exports = Self => { } }); - Self.getDebt = async clientFk => { - let query = `SELECT vn.clientGetDebt(?, CURDATE()) AS debt`; - let [debt] = await Self.rawSql(query, [clientFk]); + Self.getDebt = async(clientFk, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const query = `SELECT vn.clientGetDebt(?, CURDATE()) AS debt`; + const [debt] = await Self.rawSql(query, [clientFk], myOptions); return debt; }; diff --git a/modules/client/back/methods/client/getMana.js b/modules/client/back/methods/client/getMana.js index 88e337e321..8b6604e210 100644 --- a/modules/client/back/methods/client/getMana.js +++ b/modules/client/back/methods/client/getMana.js @@ -19,9 +19,14 @@ module.exports = Self => { } }); - Self.getMana = async clientFk => { - let query = `SELECT vn.clientGetMana(?) AS mana`; - let [mana] = await Self.rawSql(query, [clientFk]); + Self.getMana = async(clientFk, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const query = `SELECT vn.clientGetMana(?) AS mana`; + const [mana] = await Self.rawSql(query, [clientFk], myOptions); return mana; }; diff --git a/modules/client/back/methods/client/getTransactions.js b/modules/client/back/methods/client/getTransactions.js index ab8a233475..45183bbdc9 100644 --- a/modules/client/back/methods/client/getTransactions.js +++ b/modules/client/back/methods/client/getTransactions.js @@ -7,12 +7,12 @@ module.exports = Self => { accessType: 'READ', accepts: [{ arg: 'filter', - type: 'Object', + type: 'object', description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', http: {source: 'query'} }], returns: { - type: ['Object'], + type: ['object'], root: true }, http: { @@ -21,9 +21,14 @@ module.exports = Self => { } }); - Self.getTransactions = async filter => { - let conn = Self.dataSource.connector; - let stmt = new ParameterizedSQL(` + Self.getTransactions = async(filter, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const conn = Self.dataSource.connector; + const stmt = new ParameterizedSQL(` SELECT t.id, t.clientFk, @@ -39,6 +44,6 @@ module.exports = Self => { stmt.merge(conn.makeSuffix(filter, 't')); - return await Self.rawStmt(stmt); + return Self.rawStmt(stmt, myOptions); }; }; diff --git a/modules/client/back/methods/client/hasCustomerRole.js b/modules/client/back/methods/client/hasCustomerRole.js index 559de1fc73..d668399362 100644 --- a/modules/client/back/methods/client/hasCustomerRole.js +++ b/modules/client/back/methods/client/hasCustomerRole.js @@ -2,23 +2,13 @@ module.exports = Self => { Self.remoteMethod('hasCustomerRole', { description: 'Comprueba si un usuario tiene el rol de cliente', accessType: 'READ', - accepts: [ - { - arg: 'id', - type: 'string', - required: true, - description: 'The user id', - http: {source: 'path'} - }, { - arg: 'context', - type: 'object', - required: true, - description: 'Filter defining where', - http: function(context) { - return context.req.query; - } - } - ], + accepts: [{ + arg: 'id', + type: 'string', + required: true, + description: 'The user id', + http: {source: 'path'} + }], returns: { type: 'boolean', root: true @@ -29,17 +19,19 @@ module.exports = Self => { } }); - Self.hasCustomerRole = (id, context, callback) => { - let query = ` + Self.hasCustomerRole = (id, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const query = ` SELECT COUNT(*) > 0 isCustomer FROM salix.Account A JOIN salix.Role r ON r.id = A.roleFK WHERE r.name = 'customer' AND A.id IN (?)`; - Self.rawSql(query, [id]).then( - instances => callback(null, instances[0]), - err => callback(err) - ); + return Self.rawSql(query, [id], myOptions); }; }; diff --git a/modules/client/back/methods/client/isValidClient.js b/modules/client/back/methods/client/isValidClient.js index 692da79ee8..a3bb0151f0 100644 --- a/modules/client/back/methods/client/isValidClient.js +++ b/modules/client/back/methods/client/isValidClient.js @@ -9,14 +9,6 @@ module.exports = Self => { required: true, description: 'The user id', http: {source: 'path'} - }, { - arg: 'context', - type: 'object', - required: true, - description: 'Filter defining where', - http: function(context) { - return context.req.query; - } } ], returns: { @@ -29,8 +21,13 @@ module.exports = Self => { } }); - Self.isValidClient = async id => { - let query = ` + Self.isValidClient = async(id, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const query = ` SELECT r.name FROM salix.Account a JOIN vn.client c ON a.id = c.id @@ -38,9 +35,9 @@ module.exports = Self => { JOIN salix.Role r ON r.id = rm.roleId WHERE a.id = ? AND c.isActive AND c.isTaxDataChecked`; - let roleNames = await Self.rawSql(query, [id]); + const roleNames = await Self.rawSql(query, [id], myOptions); - let isEmployee = roleNames.findIndex(role => { + const isEmployee = roleNames.findIndex(role => { return role.name === 'employee'; }); diff --git a/modules/client/back/methods/client/lastActiveTickets.js b/modules/client/back/methods/client/lastActiveTickets.js index 7444dff45b..da38dbee85 100644 --- a/modules/client/back/methods/client/lastActiveTickets.js +++ b/modules/client/back/methods/client/lastActiveTickets.js @@ -2,19 +2,22 @@ module.exports = Self => { Self.remoteMethod('lastActiveTickets', { description: 'Returns the last three active tickets of a client', accessType: 'READ', - accepts: [{ - arg: 'id', - type: 'Number', - required: true, - description: 'Client id', - http: {source: 'path'} - }, { - arg: 'ticketId', - type: 'Number', - required: true - }], + accepts: [ + { + arg: 'id', + type: 'number', + required: true, + description: 'Client id', + http: {source: 'path'} + }, + { + arg: 'ticketId', + type: 'number', + required: true + } + ], returns: { - type: ['Object'], + type: ['object'], root: true }, http: { @@ -23,8 +26,13 @@ module.exports = Self => { } }); - Self.lastActiveTickets = async(id, ticketId) => { - const ticket = await Self.app.models.Ticket.findById(ticketId); + Self.lastActiveTickets = async(id, ticketId, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const ticket = await Self.app.models.Ticket.findById(ticketId, null, myOptions); const query = ` SELECT t.id, @@ -47,7 +55,7 @@ module.exports = Self => { ORDER BY t.shipped LIMIT 10`; - return Self.rawSql(query, [id, ticketId, ticket.warehouseFk]); + return Self.rawSql(query, [id, ticketId, ticket.warehouseFk], myOptions); }; }; diff --git a/modules/client/back/methods/client/listWorkers.js b/modules/client/back/methods/client/listWorkers.js deleted file mode 100644 index 8fa4c085eb..0000000000 --- a/modules/client/back/methods/client/listWorkers.js +++ /dev/null @@ -1,30 +0,0 @@ -module.exports = function(Self) { - Self.remoteMethod('listWorkers', { - description: 'List workers', - accessType: 'READ', - returns: { - arg: 'data', - type: 'Worker', - root: true - }, - http: { - path: `/listWorkers`, - verb: 'GET' - } - }); - - Self.listWorkers = function() { - let query = - `SELECT w.id, - CONCAT(w.firstName, IFNULL(CONCAT(" ", w.lastName), "")) \`name\` - FROM worker w - JOIN account.user u ON w.userFk = u.id - JOIN account.roleRole rr ON rr.role = u.role - JOIN account.role r ON r.id = rr.inheritsFrom - WHERE u.active - AND r.\`name\` = 'employee' - ORDER BY w.lastName ASC`; - - return Self.rawSql(query); - }; -}; diff --git a/modules/client/back/methods/client/sendSms.js b/modules/client/back/methods/client/sendSms.js index a39d4c75a9..cc11d17be8 100644 --- a/modules/client/back/methods/client/sendSms.js +++ b/modules/client/back/methods/client/sendSms.js @@ -5,23 +5,23 @@ module.exports = Self => { accessType: 'WRITE', accepts: [{ arg: 'id', - type: 'Number', + type: 'number', required: true, description: 'The ticket id', http: {source: 'path'} }, { arg: 'destination', - type: 'String', + type: 'string', required: true, }, { arg: 'message', - type: 'String', + type: 'string', required: true, }], returns: { - type: 'Object', + type: 'object', root: true }, http: { @@ -30,11 +30,17 @@ module.exports = Self => { } }); - Self.sendSms = async(ctx, id, destination, message) => { + Self.sendSms = async(ctx, id, destination, message, options) => { + const models = Self.app.models; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + const userId = ctx.req.accessToken.userId; - let sms = await Self.app.models.Sms.send(ctx, id, destination, message); - let logRecord = { + const sms = await models.Sms.send(ctx, id, destination, message); + const logRecord = { originFk: id, userFk: userId, action: 'insert', @@ -48,7 +54,7 @@ module.exports = Self => { } }; - const clientLog = await Self.app.models.ClientLog.create(logRecord); + const clientLog = await models.ClientLog.create(logRecord, myOptions); sms.logId = clientLog.id; diff --git a/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js b/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js index 2ec91125d5..069c7bd250 100644 --- a/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js +++ b/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js @@ -1,40 +1,30 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Client addressesPropagateRe', () => { - let client; - beforeEach(async() => { - client = await app.models.Client.findById(101); - await app.models.Address.update({clientFk: 101}, {isEqualizated: false}); - await client.updateAttributes({hasToInvoiceByAddress: true}); - }); - - afterAll(async done => { - await app.models.Address.update({clientFk: 101}, {isEqualizated: false}); - await client.updateAttributes({hasToInvoiceByAddress: true}); - - done(); - }); - it('should propagate the isEqualizated on both addresses of Mr Wayne and set hasToInvoiceByAddress to false', async() => { - let id = 101; - let data = { - isEqualizated: true - }; + const tx = await models.Client.beginTransaction({}); - let resultAddress = await app.models.Address.find({where: {clientFk: id}}); - let resultClient = await app.models.Client.find({where: {id: id}}); + try { + const options = {transaction: tx}; - expect(resultAddress[0].isEqualizated).toBeFalsy(); - expect(resultAddress[1].isEqualizated).toBeFalsy(); - expect(resultClient[0].hasToInvoiceByAddress).toBeTruthy(); + let id = 1101; + let data = { + isEqualizated: true + }; - await app.models.Client.addressesPropagateRe(id, data); + await models.Client.addressesPropagateRe(id, data, options); - resultAddress = await app.models.Address.find({where: {clientFk: id}}); - resultClient = await app.models.Client.find({where: {id: id}}); + const addresses = await models.Address.find({where: {clientFk: id}}, options); + const client = await models.Client.findById(id, null, options); - expect(resultAddress[0].isEqualizated).toBeTruthy(); - expect(resultAddress[1].isEqualizated).toBeTruthy(); - expect(resultClient[0].hasToInvoiceByAddress).toBeFalsy(); + expect(addresses[0].isEqualizated).toBeTruthy(); + expect(addresses[1].isEqualizated).toBeTruthy(); + expect(client.hasToInvoiceByAddress).toBeFalsy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/client/specs/canBeInvoiced.spec.js b/modules/client/back/methods/client/specs/canBeInvoiced.spec.js new file mode 100644 index 0000000000..7b0640d2a5 --- /dev/null +++ b/modules/client/back/methods/client/specs/canBeInvoiced.spec.js @@ -0,0 +1,75 @@ +const models = require('vn-loopback/server/server').models; +const LoopBackContext = require('loopback-context'); + +describe('client canBeInvoiced()', () => { + const userId = 19; + const clientId = 1101; + const activeCtx = { + accessToken: {userId: userId} + }; + + beforeAll(async done => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); + + done(); + }); + + it('should return falsy for a client without the data checked', async() => { + const tx = await models.Client.beginTransaction({}); + + try { + const options = {transaction: tx}; + + const client = await models.Client.findById(clientId, null, options); + await client.updateAttribute('isTaxDataChecked', false, options); + + const canBeInvoiced = await models.Client.canBeInvoiced(clientId, options); + + expect(canBeInvoiced).toEqual(false); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should return falsy for a client with invoicing disabled', async() => { + const tx = await models.Client.beginTransaction({}); + + try { + const options = {transaction: tx}; + + const client = await models.Client.findById(clientId, null, options); + await client.updateAttribute('hasToInvoice', false, options); + + const canBeInvoiced = await models.Client.canBeInvoiced(clientId, options); + + expect(canBeInvoiced).toEqual(false); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should return truthy for an invoiceable client', async() => { + const tx = await models.Client.beginTransaction({}); + + try { + const options = {transaction: tx}; + + const canBeInvoiced = await models.Client.canBeInvoiced(clientId, options); + + expect(canBeInvoiced).toEqual(true); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); +}); diff --git a/modules/client/back/methods/client/specs/canCreateTicket.spec.js b/modules/client/back/methods/client/specs/canCreateTicket.spec.js index 9eb1db3346..eb3bdec508 100644 --- a/modules/client/back/methods/client/specs/canCreateTicket.spec.js +++ b/modules/client/back/methods/client/specs/canCreateTicket.spec.js @@ -1,17 +1,39 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Client canCreateTicket', () => { it('should receive true if the client is active', async() => { - let id = 105; - let canCreateTicket = await app.models.Client.canCreateTicket(id); + const tx = await models.Client.beginTransaction({}); - expect(canCreateTicket).toBeTruthy(); + try { + const options = {transaction: tx}; + + const id = 1105; + const canCreateTicket = await models.Client.canCreateTicket(id, null, options); + + expect(canCreateTicket).toBeTruthy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it(`should receive false if the client isn't active`, async() => { - let id = 106; - let canCreateTicket = await app.models.Client.canCreateTicket(id); + const tx = await models.Client.beginTransaction({}); - expect(canCreateTicket).toBe(false); + try { + const options = {transaction: tx}; + + const id = 1106; + const canCreateTicket = await models.Client.canCreateTicket(id, null, options); + + expect(canCreateTicket).toBe(false); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/client/specs/confirmTransaction.spec.js b/modules/client/back/methods/client/specs/confirmTransaction.spec.js index 5fe638001b..50e6806b5e 100644 --- a/modules/client/back/methods/client/specs/confirmTransaction.spec.js +++ b/modules/client/back/methods/client/specs/confirmTransaction.spec.js @@ -1,24 +1,27 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Client confirmTransaction', () => { - const transactionId = 2; - - afterAll(async done => { - await app.models.Client.rawSql(` - CALL hedera.tpvTransaction_undo(?)`, [transactionId]); - - done(); - }); - it('should call confirmTransaction() method to mark transaction as confirmed', async() => { - let ctx = {req: {accessToken: {userId: 1}}}; - await app.models.Client.confirmTransaction(ctx, transactionId); + const tx = await models.Client.beginTransaction({}); + const transactionId = 2; - let [receipt] = await app.models.Client.rawSql( - `SELECT receiptFk - FROM hedera.tpvTransaction - WHERE id = ?`, [transactionId]); + try { + const options = {transaction: tx}; - expect(receipt.receiptFk).toBeGreaterThan(0); + let ctx = {req: {accessToken: {userId: 1}}}; + await models.Client.confirmTransaction(ctx, transactionId, options); + + let [receipt] = await models.Client.rawSql( + `SELECT receiptFk + FROM hedera.tpvTransaction + WHERE id = ?`, [transactionId], options); + + expect(receipt.receiptFk).toBeGreaterThan(0); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/client/specs/consumption.spec.js b/modules/client/back/methods/client/specs/consumption.spec.js index f70c093707..47a495d799 100644 --- a/modules/client/back/methods/client/specs/consumption.spec.js +++ b/modules/client/back/methods/client/specs/consumption.spec.js @@ -1,60 +1,93 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('client consumption() filter', () => { it('should return a list of buyed items by ticket', async() => { - const ctx = {req: {accessToken: {userId: 9}}, args: {}}; - const filter = { - where: { - clientFk: 101 - }, - order: 'itemTypeFk, itemName, itemSize' - }; - const result = await app.models.Client.consumption(ctx, filter); + const tx = await models.Client.beginTransaction({}); - expect(result.length).toEqual(10); + try { + const options = {transaction: tx}; + + const ctx = {req: {accessToken: {userId: 9}}, args: {}}; + const filter = { + where: { + clientFk: 1101 + }, + order: 'itemTypeFk, itemName, itemSize' + }; + const result = await models.Client.consumption(ctx, filter, options); + + expect(result.length).toEqual(10); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return a list of tickets grouped by item', async() => { - const ctx = {req: {accessToken: {userId: 9}}, - args: { - grouped: true - } - }; - const filter = { - where: { - clientFk: 101 - }, - order: 'itemFk' - }; - const result = await app.models.Client.consumption(ctx, filter); + const tx = await models.Client.beginTransaction({}); - const firstRow = result[0]; - const secondRow = result[1]; - const thirdRow = result[2]; + try { + const options = {transaction: tx}; - expect(result.length).toEqual(3); - expect(firstRow.quantity).toEqual(10); - expect(secondRow.quantity).toEqual(15); - expect(thirdRow.quantity).toEqual(20); + const ctx = {req: {accessToken: {userId: 9}}, + args: { + grouped: true + } + }; + const filter = { + where: { + clientFk: 1101 + }, + order: 'itemFk' + }; + const result = await models.Client.consumption(ctx, filter, options); + + const firstRow = result[0]; + const secondRow = result[1]; + const thirdRow = result[2]; + + expect(result.length).toEqual(3); + expect(firstRow.quantity).toEqual(10); + expect(secondRow.quantity).toEqual(15); + expect(thirdRow.quantity).toEqual(20); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return a list of tickets from the item id 4', async() => { - const ctx = {req: {accessToken: {userId: 9}}, - args: { - itemId: 4 - } - }; - const filter = { - where: { - clientFk: 101 - }, - order: 'itemTypeFk, itemName, itemSize' - }; - const result = await app.models.Client.consumption(ctx, filter); + const tx = await models.Client.beginTransaction({}); - const expectedItemId = 4; - const firstRow = result[0]; + try { + const options = {transaction: tx}; - expect(firstRow.itemFk).toEqual(expectedItemId); + const ctx = {req: {accessToken: {userId: 9}}, + args: { + itemId: 4 + } + }; + const filter = { + where: { + clientFk: 1101 + }, + order: 'itemTypeFk, itemName, itemSize' + }; + const result = await models.Client.consumption(ctx, filter, options); + + const expectedItemId = 4; + const firstRow = result[0]; + + expect(firstRow.itemFk).toEqual(expectedItemId); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/client/specs/createAddress.spec.js b/modules/client/back/methods/client/specs/createAddress.spec.js index 654d41b838..d6178ae0d8 100644 --- a/modules/client/back/methods/client/specs/createAddress.spec.js +++ b/modules/client/back/methods/client/specs/createAddress.spec.js @@ -1,113 +1,139 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Address createAddress', () => { - const clientFk = 101; + const clientFk = 1101; const provinceFk = 5; const incotermsFk = 'FAS'; const customAgentOneId = 1; it('should throw a non uee member error if no incoterms is defined', async() => { - const expectedResult = 'My edited address'; - const ctx = { - args: { - provinceFk: provinceFk, - nickname: expectedResult, - street: 'Wall Street', - city: 'New York', - customsAgentFk: customAgentOneId - } - }; + const tx = await models.Client.beginTransaction({}); + + let error; try { - await app.models.Client.createAddress(ctx, clientFk); + const options = {transaction: tx}; + + const expectedResult = 'My edited address'; + const ctx = { + args: { + provinceFk: provinceFk, + nickname: expectedResult, + street: 'Wall Street', + city: 'New York', + customsAgentFk: customAgentOneId + } + }; + + await models.Client.createAddress(ctx, clientFk, options); + + await tx.rollback(); } catch (e) { - err = e; + await tx.rollback(); + error = e; } - expect(err).toBeDefined(); - expect(err.message).toEqual('Incoterms is required for a non UEE member'); + expect(error).toBeDefined(); + expect(error.message).toEqual('Incoterms is required for a non UEE member'); }); it('should throw a non uee member error if no customsAgent is defined', async() => { - const expectedResult = 'My edited address'; - const ctx = { - args: { - provinceFk: provinceFk, - nickname: expectedResult, - street: 'Wall Street', - city: 'New York', - incotermsFk: incotermsFk - } - }; + const tx = await models.Client.beginTransaction({}); + + let error; try { - await app.models.Client.createAddress(ctx, clientFk); + const options = {transaction: tx}; + + const expectedResult = 'My edited address'; + const ctx = { + args: { + provinceFk: provinceFk, + nickname: expectedResult, + street: 'Wall Street', + city: 'New York', + incotermsFk: incotermsFk + } + }; + + await models.Client.createAddress(ctx, clientFk, options); + + await tx.rollback(); } catch (e) { - err = e; + await tx.rollback(); + error = e; } - expect(err).toBeDefined(); - expect(err.message).toEqual('Customs agent is required for a non UEE member'); - }); - - it('should verify that client defaultAddressFk is untainted', async() => { - const client = await app.models.Client.findById(clientFk); - - expect(client.defaultAddressFk).toEqual(1); + expect(error).toBeDefined(); + expect(error.message).toEqual('Customs agent is required for a non UEE member'); }); it('should create a new address and set as a client default address', async() => { - const ctx = { - args: { - clientFk: 101, - provinceFk: 1, - nickname: 'My address', - street: 'Wall Street', - city: 'New York', - phone: 678678678, - mobile: 678678678, - postalCode: 46680, - agencyModeFk: 1, - incotermsFk: incotermsFk, - customsAgentFk: customAgentOneId, - isDefaultAddress: true - } - }; + const tx = await models.Client.beginTransaction({}); - const address = await app.models.Client.createAddress(ctx, clientFk); - const client = await app.models.Client.findById(clientFk); + try { + const options = {transaction: tx}; - expect(client.defaultAddressFk).toEqual(address.id); + const ctx = { + args: { + clientFk: 1101, + provinceFk: 1, + nickname: 'My address', + street: 'Wall Street', + city: 'New York', + phone: 678678678, + mobile: 678678678, + postalCode: 46680, + agencyModeFk: 1, + incotermsFk: incotermsFk, + customsAgentFk: customAgentOneId, + isDefaultAddress: true + } + }; - // restores - await client.updateAttributes({defaultAddressFk: 1}); - await address.destroy(); + const address = await models.Client.createAddress(ctx, clientFk, options); + const client = await models.Client.findById(clientFk, null, options); + + expect(client.defaultAddressFk).toEqual(address.id); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should create a new address and set all properties', async() => { - const ctx = { - args: { - clientFk: 101, - provinceFk: 1, - nickname: 'My address', - street: 'Wall Street', - city: 'New York', - phone: '678678678', - mobile: '678678678', - postalCode: '46680', - agencyModeFk: 1, - incotermsFk: incotermsFk, - customsAgentFk: customAgentOneId, - isDefaultAddress: true - } - }; + const tx = await models.Client.beginTransaction({}); - address = await app.models.Client.createAddress(ctx, clientFk); + try { + const options = {transaction: tx}; - expect(address).toEqual(jasmine.objectContaining(ctx.args)); - // restores - const client = await app.models.Client.findById(clientFk); - await client.updateAttributes({defaultAddressFk: 1}); - await address.destroy(); + const ctx = { + args: { + clientFk: 1101, + provinceFk: 1, + nickname: 'My address', + street: 'Wall Street', + city: 'New York', + phone: '678678678', + mobile: '678678678', + postalCode: '46680', + agencyModeFk: 1, + incotermsFk: incotermsFk, + customsAgentFk: customAgentOneId, + isDefaultAddress: true + } + }; + + address = await models.Client.createAddress(ctx, clientFk, options); + + expect(address).toEqual(jasmine.objectContaining(ctx.args)); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/client/specs/createReceipt.spec.js b/modules/client/back/methods/client/specs/createReceipt.spec.js index 8d35064a22..915836a38d 100644 --- a/modules/client/back/methods/client/specs/createReceipt.spec.js +++ b/modules/client/back/methods/client/specs/createReceipt.spec.js @@ -1,8 +1,8 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('Client createReceipt', () => { - const clientFk = 108; + const clientFk = 1108; const payed = Date(); const companyFk = 442; const amountPaid = 12.50; @@ -27,49 +27,56 @@ describe('Client createReceipt', () => { }); it('should create a new receipt', async() => { - const bankFk = 1; - ctx.args = { - clientFk: clientFk, - payed: payed, - companyFk: companyFk, - bankFk: bankFk, - amountPaid: amountPaid, - description: description - }; + const tx = await models.Client.beginTransaction({}); - const receipt = await app.models.Client.createReceipt(ctx); - delete ctx.args.payed; + try { + const options = {transaction: tx}; - const till = await app.models.Till.findOne({ - where: { + const bankFk = 1; + ctx.args = { + clientFk: clientFk, + payed: payed, + companyFk: companyFk, bankFk: bankFk, - in: amountPaid, - number: clientFk - } - }); + amountPaid: amountPaid, + description: description + }; - expect(receipt).toEqual(jasmine.objectContaining(ctx.args)); + const receipt = await models.Client.createReceipt(ctx, options); + delete ctx.args.payed; - // restores - await receipt.destroy(); - await till.destroy(); + expect(receipt).toEqual(jasmine.objectContaining(ctx.args)); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should throw Compensation account is empty', async() => { - const bankFk = 3; + const tx = await models.Client.beginTransaction({}); - ctx.args = { - clientFk: clientFk, - payed: payed, - companyFk: companyFk, - bankFk: bankFk, - amountPaid: amountPaid, - description: description - }; + let error; try { - await app.models.Client.createReceipt(ctx); + const options = {transaction: tx}; + + const bankFk = 3; + ctx.args = { + clientFk: clientFk, + payed: payed, + companyFk: companyFk, + bankFk: bankFk, + amountPaid: amountPaid, + description: description + }; + + await models.Client.createReceipt(ctx, options); + + await tx.rollback(); } catch (e) { + await tx.rollback(); error = e; } @@ -78,21 +85,29 @@ describe('Client createReceipt', () => { }); it('should throw Invalid account if compensationAccount does not belongs to a client nor a supplier', async() => { + const tx = await models.Client.beginTransaction({}); + let error; - const bankFk = 3; - ctx.args = { - clientFk: clientFk, - payed: payed, - companyFk: companyFk, - bankFk: bankFk, - amountPaid: amountPaid, - description: description, - compensationAccount: 'non existing account' - }; try { - await app.models.Client.createReceipt(ctx); + const options = {transaction: tx}; + + const bankFk = 3; + ctx.args = { + clientFk: clientFk, + payed: payed, + companyFk: companyFk, + bankFk: bankFk, + amountPaid: amountPaid, + description: description, + compensationAccount: 'non existing account' + }; + + await models.Client.createReceipt(ctx, options); + + await tx.rollback(); } catch (e) { + await tx.rollback(); error = e; } @@ -101,84 +116,80 @@ describe('Client createReceipt', () => { }); it('should create a new receipt with a compensation for a client', async() => { - const bankFk = 3; + const tx = await models.Client.beginTransaction({}); - ctx.args = { - clientFk: clientFk, - payed: payed, - companyFk: companyFk, - bankFk: bankFk, - amountPaid: amountPaid, - description: description, - compensationAccount: '4300000001' - }; - const receipt = await app.models.Client.createReceipt(ctx); - const receiptCompensated = await app.models.Receipt.findOne({ - where: { - clientFk: 1, - bankFk: ctx.args.bankFk - } - }); + try { + const options = {transaction: tx}; - const till = await app.models.Till.findOne({ - where: { + const bankFk = 3; + + ctx.args = { + clientFk: clientFk, + payed: payed, + companyFk: companyFk, bankFk: bankFk, - in: amountPaid, - number: clientFk - } - }); + amountPaid: amountPaid, + description: description, + compensationAccount: '4300000001' + }; + const receipt = await models.Client.createReceipt(ctx, options); + const receiptCompensated = await models.Receipt.findOne({ + where: { + clientFk: 1, + bankFk: ctx.args.bankFk + } + }, options); - delete ctx.args.payed; + delete ctx.args.payed; - expect(receipt).toEqual(jasmine.objectContaining(ctx.args)); - expect(receipt.amountPaid).toEqual(-receiptCompensated.amountPaid); + expect(receipt).toEqual(jasmine.objectContaining(ctx.args)); + expect(receipt.amountPaid).toEqual(-receiptCompensated.amountPaid); - // restores - await receipt.destroy(); - await receiptCompensated.destroy(); - await till.destroy(); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should create a new receipt with a compensation for a supplier', async() => { - const bankFk = 3; + const tx = await models.Client.beginTransaction({}); - ctx.args = { - clientFk: clientFk, - payed: payed, - companyFk: companyFk, - bankFk: bankFk, - amountPaid: amountPaid, - description: description, - compensationAccount: '4100000001' - }; - const receipt = await app.models.Client.createReceipt(ctx); + try { + const options = {transaction: tx}; - const paymentCompensated = await app.models.Payment.findOne({ - where: { - clientFk: ctx.args.sale, - payed: ctx.args.payed, - amountPaid: ctx.args.amountPaid, - bankFk: ctx.args.bankFk - } - }); + const bankFk = 3; - const till = await app.models.Till.findOne({ - where: { - bankFk: ctx.args.bankFk, - in: amountPaid, - number: clientFk - } - }); + ctx.args = { + clientFk: clientFk, + payed: payed, + companyFk: companyFk, + bankFk: bankFk, + amountPaid: amountPaid, + description: description, + compensationAccount: '4100000001' + }; + const receipt = await models.Client.createReceipt(ctx, options); - delete ctx.args.payed; + const paymentCompensated = await models.Payment.findOne({ + where: { + clientFk: ctx.args.sale, + payed: ctx.args.payed, + amountPaid: ctx.args.amountPaid, + bankFk: ctx.args.bankFk + } + }, options); - expect(receipt).toEqual(jasmine.objectContaining(ctx.args)); + delete ctx.args.payed; - expect(paymentCompensated.amountPaid).toEqual(paymentCompensated.amountPaid); + expect(receipt).toEqual(jasmine.objectContaining(ctx.args)); - // restores - await receipt.destroy(); - await paymentCompensated.destroy(); - await till.destroy(); + expect(paymentCompensated.amountPaid).toEqual(paymentCompensated.amountPaid); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/client/specs/createWithUser.spec.js b/modules/client/back/methods/client/specs/createWithUser.spec.js index 35de8b300e..f85ad19297 100644 --- a/modules/client/back/methods/client/specs/createWithUser.spec.js +++ b/modules/client/back/methods/client/specs/createWithUser.spec.js @@ -1,28 +1,7 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Client Create', () => { - const clientName = 'Wade'; - const AccountName = 'Deadpool'; - - afterEach(async done => { - let address = await app.models.Address.findOne({where: {nickname: clientName}}); - let client = await app.models.Client.findOne({where: {name: clientName}}); - let account = await app.models.Account.findOne({where: {name: AccountName}}); - - if (address && client && account) { - try { - await app.models.Address.destroyById(address.id); - await app.models.Client.destroyById(client.id); - await app.models.Account.destroyById(account.id); - } catch (error) { - console.error(error); - } - } - - done(); - }); - - let newAccount = { + const newAccount = { userName: 'Deadpool', email: 'Deadpool@marvel.com', fi: '16195279J', @@ -33,34 +12,68 @@ describe('Client Create', () => { }; it(`should not find Deadpool as he's not created yet`, async() => { - let account = await app.models.Account.findOne({where: {name: newAccount.userName}}); - let client = await app.models.Client.findOne({where: {name: newAccount.name}}); + const tx = await models.Client.beginTransaction({}); - expect(account).toEqual(null); - expect(client).toEqual(null); + try { + const options = {transaction: tx}; + + const account = await models.Account.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(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should create a new account', async() => { - let client = await app.models.Client.createWithUser(newAccount); - let account = await app.models.Account.findOne({where: {name: newAccount.userName}}); + const tx = await models.Client.beginTransaction({}); - expect(account.name).toEqual(newAccount.userName); + try { + const options = {transaction: tx}; - expect(client.id).toEqual(account.id); - expect(client.name).toEqual(newAccount.name); - expect(client.email).toEqual(newAccount.email); - expect(client.fi).toEqual(newAccount.fi); - expect(client.socialName).toEqual(newAccount.socialName); + const client = await models.Client.createWithUser(newAccount, options); + const account = await models.Account.findOne({where: {name: newAccount.userName}}, options); + + expect(account.name).toEqual(newAccount.userName); + expect(client.id).toEqual(account.id); + expect(client.name).toEqual(newAccount.name); + expect(client.email).toEqual(newAccount.email); + expect(client.fi).toEqual(newAccount.fi); + expect(client.socialName).toEqual(newAccount.socialName); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should not be able to create a user if exists', async() => { - await app.models.Client.createWithUser(newAccount); + const tx = await models.Client.beginTransaction({}); + + let error; + try { - let client = await app.models.Client.createWithUser(newAccount); + const options = {transaction: tx}; + + await models.Client.createWithUser(newAccount, options); + const client = await models.Client.createWithUser(newAccount, options); expect(client).toBeNull(); - } catch (err) { - expect(err.details.codes.name[0]).toEqual('uniqueness'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; } + + const errorName = error.details.codes.name[0]; + + expect(errorName).toEqual('uniqueness'); }); }); diff --git a/modules/client/back/methods/client/specs/getAverageInvoiced.spec.js b/modules/client/back/methods/client/specs/getAverageInvoiced.spec.js index fd30270e7e..74a7613896 100644 --- a/modules/client/back/methods/client/specs/getAverageInvoiced.spec.js +++ b/modules/client/back/methods/client/specs/getAverageInvoiced.spec.js @@ -1,9 +1,20 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('client getAverageInvoiced()', () => { it('should call the getAverageInvoiced method', async() => { - const {invoiced} = await app.models.Client.getAverageInvoiced(101); + const tx = await models.Client.beginTransaction({}); - expect(invoiced).toEqual(1500); + try { + const options = {transaction: tx}; + + const {invoiced} = await models.Client.getAverageInvoiced(1101, options); + + expect(invoiced).toEqual(1500); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/client/specs/getCard.spec.js b/modules/client/back/methods/client/specs/getCard.spec.js index e8ac7b3bcc..e713c9883c 100644 --- a/modules/client/back/methods/client/specs/getCard.spec.js +++ b/modules/client/back/methods/client/specs/getCard.spec.js @@ -1,12 +1,23 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; -describe('Client get', () => { +describe('Client getCard()', () => { it('should receive a formated card of Bruce Wayne', async() => { - let id = 101; - let result = await app.models.Client.getCard(id); + const tx = await models.Client.beginTransaction({}); - expect(result.id).toEqual(101); - expect(result.name).toEqual('Bruce Wayne'); - expect(result.debt).toEqual(887.38); + try { + const options = {transaction: tx}; + + const id = 1101; + const result = await models.Client.getCard(id, options); + + expect(result.id).toEqual(id); + expect(result.name).toEqual('Bruce Wayne'); + expect(result.debt).toEqual(jasmine.any(Number)); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/client/specs/getDebt.spec.js b/modules/client/back/methods/client/specs/getDebt.spec.js index 9d3061ebbe..471d45a6d3 100644 --- a/modules/client/back/methods/client/specs/getDebt.spec.js +++ b/modules/client/back/methods/client/specs/getDebt.spec.js @@ -1,10 +1,21 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('client getDebt()', () => { it('should return the client debt', async() => { - let result = await app.models.Client.getDebt(101); + const tx = await models.Client.beginTransaction({}); - expect(result.debt).toEqual(887.38); + try { + const options = {transaction: tx}; + + const result = await models.Client.getDebt(1101, options); + + expect(result.debt).toEqual(jasmine.any(Number)); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/client/specs/getMana.spec.js b/modules/client/back/methods/client/specs/getMana.spec.js index e6fb09c909..093e491a31 100644 --- a/modules/client/back/methods/client/specs/getMana.spec.js +++ b/modules/client/back/methods/client/specs/getMana.spec.js @@ -1,9 +1,20 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('client getMana()', () => { it('should call the getMana method', async() => { - let result = await app.models.Client.getMana(105); + const tx = await models.Client.beginTransaction({}); - expect(result.mana).toEqual(0.34); + try { + const options = {transaction: tx}; + + const result = await models.Client.getMana(1105, options); + + expect(result.mana).toEqual(0.34); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/client/specs/getTransactions.spec.js b/modules/client/back/methods/client/specs/getTransactions.spec.js index f04cf90507..0387eb59a6 100644 --- a/modules/client/back/methods/client/specs/getTransactions.spec.js +++ b/modules/client/back/methods/client/specs/getTransactions.spec.js @@ -1,10 +1,21 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Client getTransations', () => { it('should call getTransations() method to receive a list of Web Payments from Bruce Wayne', async() => { - let filter = {where: {clientFk: 101}}; - let result = await app.models.Client.getTransactions(filter); + const tx = await models.Client.beginTransaction({}); - expect(result[1].id).toBeTruthy(); + try { + const options = {transaction: tx}; + + const filter = {where: {clientFk: 1101}}; + const result = await models.Client.getTransactions(filter, options); + + expect(result[1].id).toBeTruthy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/client/specs/hasCustomerRole.spec.js b/modules/client/back/methods/client/specs/hasCustomerRole.spec.js index 87306afa7e..08b13a88eb 100644 --- a/modules/client/back/methods/client/specs/hasCustomerRole.spec.js +++ b/modules/client/back/methods/client/specs/hasCustomerRole.spec.js @@ -1,59 +1,78 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Client hasCustomerRole', () => { - it('should call the hasCustomerRole() method with a customer id', done => { - let id = 101; - let params = {}; + it('should call the hasCustomerRole() method with a customer id', async() => { + const tx = await models.Client.beginTransaction({}); - let callback = (error, result) => { - if (error) return done.fail(error); + try { + const options = {transaction: tx}; + + const id = 1101; + + const [result] = await models.Client.hasCustomerRole(id, options); expect(result).toEqual(jasmine.objectContaining({isCustomer: 1})); - done(); - }; - app.models.Client.hasCustomerRole(id, params, callback); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); - it('should call the hasCustomerRole() method with a non customer id', done => { - let id = 8; - let params = {}; + it('should call the hasCustomerRole() method with a non customer id', async() => { + const tx = await models.Client.beginTransaction({}); - let callback = (error, result) => { - if (error) return done.fail(error); + try { + const options = {transaction: tx}; + + const id = 8; + const [result] = await models.Client.hasCustomerRole(id, options); expect(result).toEqual(jasmine.objectContaining({isCustomer: 0})); - done(); - }; - app.models.Client.hasCustomerRole(id, params, callback); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); - it('should call the hasCustomerRole() method with an unreal id', done => { - let id = 999; - let params = {}; + it('should call the hasCustomerRole() method with an unreal id', async() => { + const tx = await models.Client.beginTransaction({}); - let callback = (error, result) => { - if (error) return done.fail(error); + try { + const options = {transaction: tx}; + + const id = 999; + + const [result] = await models.Client.hasCustomerRole(id, options); expect(result).toEqual(jasmine.objectContaining({isCustomer: 0})); - done(); - }; - app.models.Client.hasCustomerRole(id, params, callback); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); - it('should call the hasCustomerRole() method with an invalid id', done => { - let id = 'WRONG!'; - let params = {}; + it('should call the hasCustomerRole() method with an invalid id', async() => { + const tx = await models.Client.beginTransaction({}); - let callback = (error, result) => { - if (error) return done.fail(error); + try { + const options = {transaction: tx}; + + const id = 'WRONG!'; + + const [result] = await models.Client.hasCustomerRole(id, options); expect(result).toEqual(jasmine.objectContaining({isCustomer: 0})); - done(); - }; - app.models.Client.hasCustomerRole(id, params, callback); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/client/specs/isValidClient.spec.js b/modules/client/back/methods/client/specs/isValidClient.spec.js index 71d7473f1b..e7bf8fa8aa 100644 --- a/modules/client/back/methods/client/specs/isValidClient.spec.js +++ b/modules/client/back/methods/client/specs/isValidClient.spec.js @@ -1,45 +1,111 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Client isValidClient', () => { it('should call the isValidClient() method with a client id and receive true', async() => { - let id = 101; - let result = await app.models.Client.isValidClient(id); + const tx = await models.Client.beginTransaction({}); - expect(result).toBeTruthy(); + try { + const options = {transaction: tx}; + + const id = 1101; + const result = await models.Client.isValidClient(id, options); + + expect(result).toBeTruthy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should call the isValidClient() method with an employee id to receive false', async() => { - let id = 1; - let result = await app.models.Client.isValidClient(id); + const tx = await models.Client.beginTransaction({}); - expect(result).toBeFalsy(); + try { + const options = {transaction: tx}; + + const id = 1; + const result = await models.Client.isValidClient(id, options); + + expect(result).toBeFalsy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should call the isValidClient() method with an unexistant id and receive false', async() => { - let id = 999; - let result = await app.models.Client.isValidClient(id); + const tx = await models.Client.beginTransaction({}); - expect(result).toBeFalsy(); + try { + const options = {transaction: tx}; + + const id = 999; + const result = await models.Client.isValidClient(id, options); + + expect(result).toBeFalsy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should call the isValidClient() method with an invalid id and receive false', async() => { - let id = 'Pepinillos'; - let result = await app.models.Client.isValidClient(id); + const tx = await models.Client.beginTransaction({}); - expect(result).toBeFalsy(); + try { + const options = {transaction: tx}; + + const id = 'Pepinillos'; + const result = await models.Client.isValidClient(id, options); + + expect(result).toBeFalsy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should call the isValidClient() method with a customer id which isnt active and return false', async() => { - let id = '106'; - let result = await app.models.Client.isValidClient(id); + const tx = await models.Client.beginTransaction({}); - expect(result).toBeFalsy(); + try { + const options = {transaction: tx}; + + const id = '1106'; + const result = await models.Client.isValidClient(id, options); + + expect(result).toBeFalsy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should call the isValidClient() method with a customer id which his data isnt verified and return false', async() => { - let id = '110'; - let result = await app.models.Client.isValidClient(id); + const tx = await models.Client.beginTransaction({}); - expect(result).toBeFalsy(); + try { + const options = {transaction: tx}; + + const id = '110'; + const result = await models.Client.isValidClient(id, options); + + expect(result).toBeFalsy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/client/specs/lastActiveTickets.spec.js b/modules/client/back/methods/client/specs/lastActiveTickets.spec.js index 8d06e0584e..7bddb55eed 100644 --- a/modules/client/back/methods/client/specs/lastActiveTickets.spec.js +++ b/modules/client/back/methods/client/specs/lastActiveTickets.spec.js @@ -1,18 +1,28 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Client last active tickets', () => { it('should receive an array of last active tickets of Bruce Wayne', async() => { - const ticketId = 22; - const clientId = 109; - const warehouseId = 5; - const result = await app.models.Client.lastActiveTickets(clientId, ticketId, warehouseId); + const tx = await models.Client.beginTransaction({}); - const length = result.length; - const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + try { + const options = {transaction: tx}; + const ticketId = 22; + const clientId = 1109; - const properties = Object.keys(anyResult); + const result = await models.Client.lastActiveTickets(clientId, ticketId, options); - expect(properties.length).toEqual(9); - expect(result.length).toEqual(3); + const length = result.length; + const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + + const properties = Object.keys(anyResult); + + expect(properties.length).toEqual(9); + expect(result.length).toEqual(3); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/client/specs/listWorkers.spec.js b/modules/client/back/methods/client/specs/listWorkers.spec.js deleted file mode 100644 index 271347969f..0000000000 --- a/modules/client/back/methods/client/specs/listWorkers.spec.js +++ /dev/null @@ -1,14 +0,0 @@ -const app = require('vn-loopback/server/server'); - -describe('Client listWorkers', () => { - it('should call the listWorkers()', done => { - app.models.Client.listWorkers() - .then(result => { - let amountOfEmployees = Object.keys(result).length; - - expect(amountOfEmployees).toEqual(54); - done(); - }) - .catch(done.fail); - }); -}); diff --git a/modules/client/back/methods/client/specs/sendSms.spec.js b/modules/client/back/methods/client/specs/sendSms.spec.js index d27188d53b..121d427cee 100644 --- a/modules/client/back/methods/client/specs/sendSms.spec.js +++ b/modules/client/back/methods/client/specs/sendSms.spec.js @@ -1,29 +1,29 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; const soap = require('soap'); describe('client sendSms()', () => { - let createdLog; - - afterAll(async done => { - await app.models.ClientLog.destroyById(createdLog.id); - - done(); - }); - it('should now send a message and log it', async() => { spyOn(soap, 'createClientAsync').and.returnValue('a so fake client'); - let ctx = {req: {accessToken: {userId: 9}}}; - let id = 101; - let destination = 222222222; - let message = 'this is the message created in a test'; + const tx = await models.Client.beginTransaction({}); - let sms = await app.models.Client.sendSms(ctx, id, destination, message); + try { + const options = {transaction: tx}; + const ctx = {req: {accessToken: {userId: 9}}}; + const id = 1101; + const destination = 222222222; + const message = 'this is the message created in a test'; - logId = sms.logId; + const sms = await models.Client.sendSms(ctx, id, destination, message, options); - createdLog = await app.models.ClientLog.findById(logId); - let json = JSON.parse(JSON.stringify(createdLog.newInstance)); + const createdLog = await models.ClientLog.findById(sms.logId, null, options); + const json = JSON.parse(JSON.stringify(createdLog.newInstance)); - expect(json.message).toEqual(message); + expect(json.message).toEqual(message); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/client/specs/summary.spec.js b/modules/client/back/methods/client/specs/summary.spec.js index 882abcab23..1eef350245 100644 --- a/modules/client/back/methods/client/specs/summary.spec.js +++ b/modules/client/back/methods/client/specs/summary.spec.js @@ -1,46 +1,130 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('client summary()', () => { it('should return a summary object containing data', async() => { - let result = await app.models.Client.summary(101); + const clientId = 1101; + const tx = await models.Client.beginTransaction({}); - expect(result.id).toEqual(101); - expect(result.name).toEqual('Bruce Wayne'); + try { + const options = {transaction: tx}; + + const result = await models.Client.summary(clientId, options); + + expect(result.id).toEqual(clientId); + expect(result.name).toEqual('Bruce Wayne'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return a summary object containing mana', async() => { - let result = await app.models.Client.summary(105); + const clientId = 1105; + const tx = await models.Client.beginTransaction({}); - expect(result.mana.mana).toEqual(0.34); + try { + const options = {transaction: tx}; + + const result = await models.Client.summary(clientId, options); + + expect(result.mana.mana).toEqual(0.34); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return a summary object containing debt', async() => { - let result = await app.models.Client.summary(101); + const clientId = 1101; + const tx = await models.Client.beginTransaction({}); - expect(result.debt.debt).toEqual(887.38); + try { + const options = {transaction: tx}; + + const result = await models.Client.summary(clientId, options); + + expect(result.debt.debt).toEqual(jasmine.any(Number)); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return a summary object containing averageInvoiced', async() => { - let result = await app.models.Client.summary(101); + const clientId = 1101; + const tx = await models.Client.beginTransaction({}); - expect(result.averageInvoiced.invoiced).toEqual(1500); + try { + const options = {transaction: tx}; + + const result = await models.Client.summary(clientId, options); + + expect(result.averageInvoiced.invoiced).toEqual(1500); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return a summary object containing totalGreuge', async() => { - let result = await app.models.Client.summary(101); + const clientId = 1101; + const tx = await models.Client.beginTransaction({}); - expect(result.totalGreuge).toEqual(203.71); + try { + const options = {transaction: tx}; + + const result = await models.Client.summary(clientId, options); + + expect(result.totalGreuge).toEqual(203.71); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return a summary object without containing active recoveries', async() => { - let result = await app.models.Client.summary(101); + const clientId = 1101; + const tx = await models.Client.beginTransaction({}); - expect(result.recovery).toEqual(null); + try { + const options = {transaction: tx}; + + const result = await models.Client.summary(clientId, options); + + expect(result.recovery).toEqual(null); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return a summary object containing active recoveries', async() => { - let result = await app.models.Client.summary(102); + const clientId = 1102; + const tx = await models.Client.beginTransaction({}); - expect(result.recovery.id).toEqual(3); + try { + const options = {transaction: tx}; + + const result = await models.Client.summary(clientId, options); + + expect(result.recovery.id).toEqual(3); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/client/specs/threeLastActive.spec.js b/modules/client/back/methods/client/specs/threeLastActive.spec.js deleted file mode 100644 index cd76a0b5b5..0000000000 --- a/modules/client/back/methods/client/specs/threeLastActive.spec.js +++ /dev/null @@ -1,12 +0,0 @@ -const app = require('vn-loopback/server/server'); - -describe('client lastActiveTickets()', () => { - it('should return the last three active tickets', async() => { - const clientId = 109; - const ticketId = 19; - - let result = await app.models.Client.lastActiveTickets(clientId, ticketId); - - expect(result.length).toEqual(3); - }); -}); diff --git a/modules/client/back/methods/client/specs/updateAddress.spec.js b/modules/client/back/methods/client/specs/updateAddress.spec.js index a30dcc96dd..efaa1b93c7 100644 --- a/modules/client/back/methods/client/specs/updateAddress.spec.js +++ b/modules/client/back/methods/client/specs/updateAddress.spec.js @@ -1,100 +1,116 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Address updateAddress', () => { - const clientId = 101; + const clientId = 1101; const addressId = 1; const provinceId = 5; const incotermsId = 'FAS'; const customAgentOneId = 1; it('should throw the non uee member error if no incoterms is defined', async() => { - let err; - const ctx = { - args: { - provinceFk: provinceId, - customsAgentFk: customAgentOneId - } - }; + const tx = await models.Client.beginTransaction({}); + + let error; try { - await app.models.Client.updateAddress(ctx, clientId, addressId); + const options = {transaction: tx}; + const ctx = { + args: { + provinceFk: provinceId, + customsAgentFk: customAgentOneId + } + }; + + await models.Client.updateAddress(ctx, clientId, addressId, options); + + await tx.rollback(); } catch (e) { - err = e; + await tx.rollback(); + error = e; } - expect(err).toBeDefined(); - expect(err.message).toEqual('Incoterms is required for a non UEE member'); + expect(error).toBeDefined(); + expect(error.message).toEqual('Incoterms is required for a non UEE member'); }); it('should throw a non uee member error if no customsAgent is defined', async() => { - let err; - const ctx = { - args: { - provinceFk: provinceId, - incotermsFk: incotermsId - } - }; + const tx = await models.Client.beginTransaction({}); + + let error; try { - await app.models.Client.updateAddress(ctx, clientId, addressId); + const options = {transaction: tx}; + const ctx = { + args: { + provinceFk: provinceId, + incotermsFk: incotermsId + } + }; + + await models.Client.updateAddress(ctx, clientId, addressId, options); + + await tx.rollback(); } catch (e) { - err = e; + await tx.rollback(); + error = e; } - expect(err).toBeDefined(); - expect(err.message).toEqual('Customs agent is required for a non UEE member'); + expect(error).toBeDefined(); + expect(error.message).toEqual('Customs agent is required for a non UEE member'); }); it('should update the adress from a non uee member with no error thrown', async() => { - const expectedResult = 'My edited address'; - const ctx = { - args: { - provinceFk: provinceId, - nickname: expectedResult, - incotermsFk: incotermsId, - customsAgentFk: customAgentOneId - } - }; + const tx = await models.Client.beginTransaction({}); - let oldAddress = await app.models.Address.findById(addressId); + try { + const options = {transaction: tx}; - await app.models.Client.updateAddress(ctx, clientId, addressId); + const expectedResult = 'My edited address'; + const ctx = { + args: { + provinceFk: provinceId, + nickname: expectedResult, + incotermsFk: incotermsId, + customsAgentFk: customAgentOneId + } + }; - let address = await app.models.Address.findById(addressId); + await models.Client.updateAddress(ctx, clientId, addressId, options); - expect(address.nickname).toEqual(expectedResult); + const address = await models.Address.findById(addressId, null, options); - // restores - await address.updateAttributes({ - nickname: oldAddress.nickname, - provinceFk: oldAddress.provinceFk, - customsAgentFk: null, - incotermsFk: null - }); + expect(address.nickname).toEqual(expectedResult); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should update the address', async() => { - const expectedResult = 'My second time edited address'; - const ctx = { - args: { - nickname: expectedResult - } - }; + const tx = await models.Client.beginTransaction({}); - oldAddress = await app.models.Address.findById(addressId); + try { + const options = {transaction: tx}; - await app.models.Client.updateAddress(ctx, clientId, addressId); + const expectedResult = 'My second time edited address'; + const ctx = { + args: { + nickname: expectedResult + } + }; - address = await app.models.Address.findById(addressId); + await models.Client.updateAddress(ctx, clientId, addressId, options); - expect(address.nickname).toEqual(expectedResult); + const address = await models.Address.findById(addressId, null, options); - // restores - await address.updateAttributes({ - nickname: oldAddress.nickname, - provinceFk: oldAddress.provinceFk, - customsAgentFk: null, - incotermsFk: null - }); + expect(address.nickname).toEqual(expectedResult); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/client/specs/updateFiscalData.spec.js b/modules/client/back/methods/client/specs/updateFiscalData.spec.js index 0b4425db69..75273a39ff 100644 --- a/modules/client/back/methods/client/specs/updateFiscalData.spec.js +++ b/modules/client/back/methods/client/specs/updateFiscalData.spec.js @@ -1,61 +1,77 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Client updateFiscalData', () => { - const clientId = 101; + const clientId = 1101; const employeeId = 1; const salesAssistantId = 21; const administrativeId = 5; - afterAll(async done => { - const ctx = {req: {accessToken: {userId: administrativeId}}}; - ctx.args = {postcode: 46460}; - - await app.models.Client.updateFiscalData(ctx, clientId); - - done(); - }); it('should return an error if the user is not salesAssistant and the isTaxDataChecked value is true', async() => { - const ctx = {req: {accessToken: {userId: employeeId}}}; - ctx.args = {}; + const tx = await models.Client.beginTransaction({}); let error; - await app.models.Client.updateFiscalData(ctx, clientId) - .catch(e => { - error = e; - }); + + try { + const options = {transaction: tx}; + const ctx = {req: {accessToken: {userId: employeeId}}}; + ctx.args = {}; + + await models.Client.updateFiscalData(ctx, clientId, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } expect(error.message).toEqual(`You can't make changes on a client with verified data`); }); it('should return an error if the salesAssistant did not fill the sage data before checking verified data', async() => { - const client = await app.models.Client.findById(clientId); - await client.updateAttribute('isTaxDataChecked', false); - - const ctx = {req: {accessToken: {userId: salesAssistantId}}}; - ctx.args = {isTaxDataChecked: true}; + const tx = await models.Client.beginTransaction({}); let error; - await app.models.Client.updateFiscalData(ctx, clientId) - .catch(e => { - error = e; - }); + + try { + const options = {transaction: tx}; + + const client = await models.Client.findById(clientId, options); + await client.updateAttribute('isTaxDataChecked', false, options); + + const ctx = {req: {accessToken: {userId: salesAssistantId}}}; + ctx.args = {isTaxDataChecked: true}; + + await models.Client.updateFiscalData(ctx, clientId, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } expect(error.message).toEqual('You need to fill sage information before you check verified data'); - - // Restores - await client.updateAttribute('isTaxDataChecked', true); }); - it('should update the client fiscal data and return the count if changes made', async() => { - const ctx = {req: {accessToken: {userId: administrativeId}}}; - ctx.args = {postcode: 46680}; + it('should update the client fiscal data', async() => { + const tx = await models.Client.beginTransaction({}); - const client = await app.models.Client.findById(clientId); + try { + const options = {transaction: tx}; + const ctx = {req: {accessToken: {userId: administrativeId}}}; + ctx.args = {postcode: 46680}; - expect(client.postcode).toEqual('46460'); + const client = await models.Client.findById(clientId, null, options); - const result = await app.models.Client.updateFiscalData(ctx, clientId); + expect(client.postcode).toEqual('46460'); - expect(result.postcode).toEqual('46680'); + const result = await models.Client.updateFiscalData(ctx, clientId, options); + + expect(result.postcode).toEqual('46680'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/client/specs/uploadFile.spec.js b/modules/client/back/methods/client/specs/uploadFile.spec.js index 15110731e0..7fee758921 100644 --- a/modules/client/back/methods/client/specs/uploadFile.spec.js +++ b/modules/client/back/methods/client/specs/uploadFile.spec.js @@ -1,19 +1,26 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Client uploadFile()', () => { it(`should return an error for a user without enough privileges`, async() => { - let clientId = 101; - let currentUserId = 102; - let paymentLawTypeId = 12; - let ctx = {req: {accessToken: {userId: currentUserId}}, args: {dmsTypeId: paymentLawTypeId}}; + const tx = await models.Client.beginTransaction({}); let error; - await app.models.Client.uploadFile(ctx, clientId).catch(e => { - error = e; - }).finally(() => { - expect(error.message).toEqual(`You don't have enough privileges`); - }); - expect(error).toBeDefined(); + try { + const options = {transaction: tx}; + const clientId = 1101; + const currentUserId = 1102; + const paymentLawTypeId = 12; + const ctx = {req: {accessToken: {userId: currentUserId}}, args: {dmsTypeId: paymentLawTypeId}}; + + await models.Client.uploadFile(ctx, clientId, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toEqual(`You don't have enough privileges`); }); }); diff --git a/modules/client/back/methods/client/summary.js b/modules/client/back/methods/client/summary.js index 009cd310e4..dccf7f39c3 100644 --- a/modules/client/back/methods/client/summary.js +++ b/modules/client/back/methods/client/summary.js @@ -19,21 +19,26 @@ module.exports = Self => { } }); - Self.summary = async clientFk => { - let models = Self.app.models; - let summaryObj = await getSummary(models.Client, clientFk); + Self.summary = async(clientFk, options) => { + const models = Self.app.models; + const myOptions = {}; - summaryObj.mana = await models.Client.getMana(clientFk); - summaryObj.debt = await models.Client.getDebt(clientFk); - summaryObj.averageInvoiced = await models.Client.getAverageInvoiced(clientFk); - summaryObj.totalGreuge = await models.Greuge.sumAmount(clientFk); - summaryObj.recovery = await getRecoveries(models.Recovery, clientFk); + if (typeof options == 'object') + Object.assign(myOptions, options); + + const summaryObj = await getSummary(models.Client, clientFk, myOptions); + + summaryObj.mana = await models.Client.getMana(clientFk, myOptions); + summaryObj.debt = await models.Client.getDebt(clientFk, myOptions); + summaryObj.averageInvoiced = await models.Client.getAverageInvoiced(clientFk, myOptions); + summaryObj.totalGreuge = await models.Greuge.sumAmount(clientFk, myOptions); + summaryObj.recovery = await getRecoveries(models.Recovery, clientFk, myOptions); return summaryObj; }; - async function getSummary(client, clientId) { - let filter = { + async function getSummary(clientModel, clientId, options) { + const filter = { include: [ { relation: 'account', @@ -115,17 +120,17 @@ module.exports = Self => { where: {id: clientId} }; - return await client.findOne(filter); + return clientModel.findOne(filter, options); } - async function getRecoveries(recovery, clientId) { - let filter = { + async function getRecoveries(recoveryModel, clientId, options) { + const filter = { where: { and: [{clientFk: clientId}, {or: [{finished: null}, {finished: {gt: Date.now()}}]}] }, limit: 1 }; - return await recovery.findOne(filter); + return recoveryModel.findOne(filter, options); } }; diff --git a/modules/client/back/methods/client/updateAddress.js b/modules/client/back/methods/client/updateAddress.js index 1ee6e5db88..d1a498fe74 100644 --- a/modules/client/back/methods/client/updateAddress.js +++ b/modules/client/back/methods/client/updateAddress.js @@ -3,71 +3,73 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = function(Self) { Self.remoteMethod('updateAddress', { description: 'Updates a client address updating default address', - accepts: [{ - arg: 'ctx', - type: 'object', - http: {source: 'context'} - }, - { - arg: 'clientId', - type: 'number', - description: 'The client id', - http: {source: 'path'} - }, - { - arg: 'addressId', - type: 'number', - description: 'The address id', - http: {source: 'path'} - }, - { - arg: 'nickname', - type: 'string' - }, - { - arg: 'city', - type: 'string' - }, - { - arg: 'street', - type: 'string' - }, - { - arg: 'phone', - type: 'any' - }, - { - arg: 'mobile', - type: 'any' - }, - { - arg: 'postalCode', - type: 'any' - }, - { - arg: 'provinceFk', - type: 'any' - }, - { - arg: 'agencyModeFk', - type: 'any' - }, - { - arg: 'incotermsFk', - type: 'any' - }, - { - arg: 'customsAgentFk', - type: 'any' - }, - { - arg: 'isActive', - type: 'boolean' - }, - { - arg: 'isEqualizated', - type: 'boolean' - }], + accepts: [ + { + arg: 'ctx', + type: 'object', + http: {source: 'context'} + }, + { + arg: 'clientId', + type: 'number', + description: 'The client id', + http: {source: 'path'} + }, + { + arg: 'addressId', + type: 'number', + description: 'The address id', + http: {source: 'path'} + }, + { + arg: 'nickname', + type: 'string' + }, + { + arg: 'city', + type: 'string' + }, + { + arg: 'street', + type: 'string' + }, + { + arg: 'phone', + type: 'any' + }, + { + arg: 'mobile', + type: 'any' + }, + { + arg: 'postalCode', + type: 'any' + }, + { + arg: 'provinceFk', + type: 'any' + }, + { + arg: 'agencyModeFk', + type: 'any' + }, + { + arg: 'incotermsFk', + type: 'any' + }, + { + arg: 'customsAgentFk', + type: 'any' + }, + { + arg: 'isActive', + type: 'boolean' + }, + { + arg: 'isEqualizated', + type: 'boolean' + } + ], returns: { root: true, type: 'object' @@ -78,44 +80,44 @@ module.exports = function(Self) { } }); - Self.updateAddress = async(ctx, clientId, addressId) => { + Self.updateAddress = async(ctx, clientId, addressId, options) => { const models = Self.app.models; const args = ctx.args; - const tx = await models.Address.beginTransaction({}); - try { - const options = {transaction: tx}; - const address = await models.Address.findOne({ - where: { - id: addressId, - clientFk: clientId - } - }); - const provinceId = args.provinceFk || address.provinceFk; - if (provinceId) { - const province = await models.Province.findById(provinceId, { - include: { - relation: 'country' - } - }, options); + const myOptions = {}; - const isUeeMember = province.country().isUeeMember; - const incotermsId = args.incotermsFk || address.incotermsFk; - if (!isUeeMember && !incotermsId) - throw new UserError(`Incoterms is required for a non UEE member`); + if (typeof options == 'object') + Object.assign(myOptions, options); - const customsAgentId = args.customsAgentFk || address.customsAgentFk; - if (!isUeeMember && !customsAgentId) - throw new UserError(`Customs agent is required for a non UEE member`); + const address = await models.Address.findOne({ + where: { + id: addressId, + clientFk: clientId } + }, myOptions); - delete args.ctx; // Remove unwanted properties - const updatedAddress = await address.updateAttributes(ctx.args, options); + const provinceId = args.provinceFk || address.provinceFk; + if (provinceId) { + const province = await models.Province.findById(provinceId, { + include: { + relation: 'country' + } + }, myOptions); - await tx.commit(); - return updatedAddress; - } catch (e) { - await tx.rollback(); - throw e; + const isUeeMember = province.country().isUeeMember; + const incotermsId = args.incotermsFk || address.incotermsFk; + + if (!isUeeMember && !incotermsId) + throw new UserError(`Incoterms is required for a non UEE member`); + + const customsAgentId = args.customsAgentFk || address.customsAgentFk; + if (!isUeeMember && !customsAgentId) + throw new UserError(`Customs agent is required for a non UEE member`); } + + delete args.ctx; // Remove unwanted properties + + const updatedAddress = await address.updateAttributes(ctx.args, myOptions); + + return updatedAddress; }; }; diff --git a/modules/client/back/methods/client/updateFiscalData.js b/modules/client/back/methods/client/updateFiscalData.js index a3d40a4d84..539d89d3a8 100644 --- a/modules/client/back/methods/client/updateFiscalData.js +++ b/modules/client/back/methods/client/updateFiscalData.js @@ -4,97 +4,99 @@ module.exports = Self => { Self.remoteMethod('updateFiscalData', { description: 'Updates fiscal data of a client', accessType: 'WRITE', - accepts: [{ - arg: 'ctx', - type: 'Object', - http: {source: 'context'} - }, - { - arg: 'id', - type: 'Number', - description: 'The client id', - http: {source: 'path'} - }, - { - arg: 'socialName', - type: 'string' - }, - { - arg: 'fi', - type: 'string' - }, - { - arg: 'street', - type: 'string' - }, - { - arg: 'postcode', - type: 'string' - }, - { - arg: 'city', - type: 'string' - }, - { - arg: 'countryFk', - type: 'number' - }, - { - arg: 'provinceFk', - type: 'number' - }, - { - arg: 'sageTaxTypeFk', - type: 'any' - }, - { - arg: 'sageTransactionTypeFk', - type: 'any' - }, - { - arg: 'transferorFk', - type: 'any' - }, - { - arg: 'hasToInvoiceByAddress', - type: 'boolean' - }, - { - arg: 'hasToInvoice', - type: 'boolean' - }, - { - arg: 'isActive', - type: 'boolean' - }, - { - arg: 'isFreezed', - type: 'boolean' - }, - { - arg: 'isVies', - type: 'boolean' - }, - { - arg: 'isToBeMailed', - type: 'boolean' - }, - { - arg: 'isEqualizated', - type: 'boolean' - }, - { - arg: 'isTaxDataVerified', - type: 'boolean' - }, - { - arg: 'isTaxDataChecked', - type: 'boolean' - }, - { - arg: 'despiteOfClient', - type: 'number' - }], + accepts: [ + { + arg: 'ctx', + type: 'object', + http: {source: 'context'} + }, + { + arg: 'id', + type: 'number', + description: 'The client id', + http: {source: 'path'} + }, + { + arg: 'socialName', + type: 'string' + }, + { + arg: 'fi', + type: 'string' + }, + { + arg: 'street', + type: 'string' + }, + { + arg: 'postcode', + type: 'string' + }, + { + arg: 'city', + type: 'string' + }, + { + arg: 'countryFk', + type: 'number' + }, + { + arg: 'provinceFk', + type: 'number' + }, + { + arg: 'sageTaxTypeFk', + type: 'any' + }, + { + arg: 'sageTransactionTypeFk', + type: 'any' + }, + { + arg: 'transferorFk', + type: 'any' + }, + { + arg: 'hasToInvoiceByAddress', + type: 'boolean' + }, + { + arg: 'hasToInvoice', + type: 'boolean' + }, + { + arg: 'isActive', + type: 'boolean' + }, + { + arg: 'isFreezed', + type: 'boolean' + }, + { + arg: 'isVies', + type: 'boolean' + }, + { + arg: 'isToBeMailed', + type: 'boolean' + }, + { + arg: 'isEqualizated', + type: 'boolean' + }, + { + arg: 'isTaxDataVerified', + type: 'boolean' + }, + { + arg: 'isTaxDataChecked', + type: 'boolean' + }, + { + arg: 'despiteOfClient', + type: 'number' + } + ], returns: { arg: 'res', type: 'string', @@ -106,46 +108,65 @@ module.exports = Self => { } }); - Self.updateFiscalData = async(ctx, clientId) => { + Self.updateFiscalData = async(ctx, clientId, options) => { + let tx; + const myOptions = {}; const models = Self.app.models; const args = ctx.args; const userId = ctx.req.accessToken.userId; - const isSalesAssistant = await models.Account.hasRole(userId, 'salesAssistant'); const $t = ctx.req.__; - const client = await models.Client.findById(clientId); + if (typeof options == 'object') + Object.assign(myOptions, options); - if (!isSalesAssistant && client.isTaxDataChecked) - throw new UserError(`You can't make changes on a client with verified data`); - - // Sage data validation - const taxDataChecked = args.isTaxDataChecked; - const sageTaxChecked = client.sageTaxTypeFk || args.sageTaxTypeFk; - const sageTransactionChecked = client.sageTransactionTypeFk || args.sageTransactionTypeFk; - const hasSageData = sageTaxChecked && sageTransactionChecked; - - if (taxDataChecked && !hasSageData) - throw new UserError(`You need to fill sage information before you check verified data`); - - if (args.despiteOfClient) { - const logRecord = { - originFk: clientId, - userFk: userId, - action: 'update', - changedModel: 'Client', - changedModelId: clientId, - description: $t(`Client checked as validated despite of duplication`, { - clientId: args.despiteOfClient - }) - }; - - await models.ClientLog.create(logRecord); + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; } - // Remove unwanted properties - delete args.ctx; - delete args.id; + try { + const isSalesAssistant = await models.Account.hasRole(userId, 'salesAssistant', myOptions); + const client = await models.Client.findById(clientId, null, myOptions); - return client.updateAttributes(args); + if (!isSalesAssistant && client.isTaxDataChecked) + throw new UserError(`You can't make changes on a client with verified data`); + + // Sage data validation + const taxDataChecked = args.isTaxDataChecked; + const sageTaxChecked = client.sageTaxTypeFk || args.sageTaxTypeFk; + const sageTransactionChecked = client.sageTransactionTypeFk || args.sageTransactionTypeFk; + const hasSageData = sageTaxChecked && sageTransactionChecked; + + if (taxDataChecked && !hasSageData) + throw new UserError(`You need to fill sage information before you check verified data`); + + if (args.despiteOfClient) { + const logRecord = { + originFk: clientId, + userFk: userId, + action: 'update', + changedModel: 'Client', + changedModelId: clientId, + description: $t(`Client checked as validated despite of duplication`, { + clientId: args.despiteOfClient + }) + }; + + await models.ClientLog.create(logRecord, myOptions); + } + + // Remove unwanted properties + delete args.ctx; + delete args.id; + + const updatedClient = await client.updateAttributes(args, myOptions); + + if (tx) await tx.commit(); + + return updatedClient; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } }; }; diff --git a/modules/client/back/methods/client/uploadFile.js b/modules/client/back/methods/client/uploadFile.js index 6ec96e3010..99ede27c67 100644 --- a/modules/client/back/methods/client/uploadFile.js +++ b/modules/client/back/methods/client/uploadFile.js @@ -2,42 +2,50 @@ module.exports = Self => { Self.remoteMethodCtx('uploadFile', { description: 'Upload and attach a file to a client', accessType: 'WRITE', - accepts: [{ - arg: 'id', - type: 'Number', - description: 'The client id', - http: {source: 'path'} - }, { - arg: 'warehouseId', - type: 'Number', - description: 'The warehouse id', - required: true - }, { - arg: 'companyId', - type: 'Number', - description: 'The company id', - required: true - }, { - arg: 'dmsTypeId', - type: 'Number', - description: 'The dms type id', - required: true - }, { - arg: 'reference', - type: 'String', - required: true - }, { - arg: 'description', - type: 'String', - required: true - }, { - arg: 'hasFile', - type: 'Boolean', - description: 'True if has an attached file', - required: true - }], + accepts: [ + { + arg: 'id', + type: 'number', + description: 'The client id', + http: {source: 'path'} + }, + { + arg: 'warehouseId', + type: 'number', + description: 'The warehouse id', + required: true + }, + { + arg: 'companyId', + type: 'number', + description: 'The company id', + required: true + }, + { + arg: 'dmsTypeId', + type: 'number', + description: 'The dms type id', + required: true + }, + { + arg: 'reference', + type: 'string', + required: true + }, + { + arg: 'description', + type: 'string', + required: true + }, + { + arg: 'hasFile', + type: 'boolean', + description: 'True if has an attached file', + required: true + } + ], returns: { - type: 'Object', + type: 'object', root: true }, http: { @@ -46,31 +54,39 @@ module.exports = Self => { } }); - Self.uploadFile = async(ctx, id) => { + Self.uploadFile = async(ctx, id, options) => { const models = Self.app.models; + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + const promises = []; - const tx = await Self.beginTransaction({}); try { - const options = {transaction: tx}; - - const uploadedFiles = await models.Dms.uploadFile(ctx, options); + const uploadedFiles = await models.Dms.uploadFile(ctx, myOptions); uploadedFiles.forEach(dms => { const newClientDms = models.ClientDms.create({ clientFk: id, dmsFk: dms.id - }, options); + }, myOptions); promises.push(newClientDms); }); const resolvedPromises = await Promise.all(promises); - await tx.commit(); + if (tx) await tx.commit(); return resolvedPromises; - } catch (err) { - await tx.rollback(); - throw err; + } catch (e) { + if (tx) await tx.rollback(); + throw e; } }; }; diff --git a/modules/client/back/methods/credit-classification/createWithInsurance.js b/modules/client/back/methods/credit-classification/createWithInsurance.js index bccfa61932..fb0a7222b8 100644 --- a/modules/client/back/methods/credit-classification/createWithInsurance.js +++ b/modules/client/back/methods/credit-classification/createWithInsurance.js @@ -1,17 +1,13 @@ module.exports = Self => { Self.remoteMethod('createWithInsurance', { description: 'Creates both classification and one insurance', - accepts: [{ - arg: 'data', - type: 'object', - http: {source: 'body'} - }, { - arg: 'context', - type: 'object', - http: function(ctx) { - return ctx; + accepts: [ + { + arg: 'data', + type: 'object', + http: {source: 'body'} } - }], + ], returns: { root: true, type: 'boolean' @@ -22,29 +18,36 @@ module.exports = Self => { } }); - Self.createWithInsurance = async(data, ctx) => { - const tx = await Self.beginTransaction({}); + Self.createWithInsurance = async(data, options) => { 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 { - let options = {transaction: tx}; - const newClassification = await Self.create({ client: data.clientFk, started: data.started - }, options); + }, myOptions); await models.CreditInsurance.create({ creditClassification: newClassification.id, credit: data.credit, grade: data.grade - }, options); + }, myOptions); - await tx.commit(); + if (tx) await tx.commit(); return newClassification; } catch (e) { - await tx.rollback(); + if (tx) await tx.rollback(); throw e; } }; diff --git a/modules/client/back/methods/credit-classification/createWithInsurance.spec.js b/modules/client/back/methods/credit-classification/createWithInsurance.spec.js index 596c9b140a..95ff5025ff 100644 --- a/modules/client/back/methods/credit-classification/createWithInsurance.spec.js +++ b/modules/client/back/methods/credit-classification/createWithInsurance.spec.js @@ -1,64 +1,44 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('Client createWithInsurance', () => { const activeCtx = { - accessToken: {userId: 101}, + accessToken: {userId: 19}, http: { req: { - headers: {origin: 'http://localhost'} + headers: {origin: 'http://localhost/'}, + __: () => {} } } }; - const ctx = {req: activeCtx}; - activeCtx.http.req.__ = value => { - return value; - }; - it('should verify the classifications and insurances are untainted', async() => { - let classifications = await app.models.CreditClassification.find(); - let insurances = await app.models.CreditInsurance.find(); - - expect(classifications.length).toEqual(5); - expect(insurances.length).toEqual(3); - }); - - it('should not create the insurance if couldnt create the classification', async() => { - let error; - let data = {clientFk: null, started: Date.now(), credit: 999, grade: 255}; + beforeAll(async() => { spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx + active: activeCtx, }); - await app.models.CreditClassification.createWithInsurance(data, ctx) - .catch(e => { - error = e; - }); - - expect(error.toString()).toBe('Error: ER_BAD_NULL_ERROR: Column \'client\' cannot be null'); - - let classifications = await app.models.CreditClassification.find(); - let insurances = await app.models.CreditInsurance.find(); - - expect(classifications.length).toEqual(5); - expect(insurances.length).toEqual(3); }); it('should create a new client credit classification with insurance', async() => { - let data = {clientFk: 101, started: Date.now(), credit: 999, grade: 255}; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - let result = await app.models.CreditClassification.createWithInsurance(data, ctx); + const tx = await models.Client.beginTransaction({}); - expect(result.client).toEqual(101); + try { + const options = {transaction: tx}; + const data = {clientFk: 1101, started: Date.now(), credit: 999, grade: 255}; - let classifications = await app.models.CreditClassification.find(); - let insurances = await app.models.CreditInsurance.find(); + const result = await models.CreditClassification.createWithInsurance(data, options); - expect(classifications.length).toEqual(6); - expect(insurances.length).toEqual(4); + expect(result.client).toEqual(1101); - // restore - await app.models.CreditClassification.destroyById(result.id); + const classifications = await models.CreditClassification.find(null, options); + const insurances = await models.CreditInsurance.find(null, options); + + expect(classifications.length).toEqual(6); + expect(insurances.length).toEqual(4); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/greuge/specs/sumAmount.spec.js b/modules/client/back/methods/greuge/specs/sumAmount.spec.js index fc84bca981..a4a7467421 100644 --- a/modules/client/back/methods/greuge/specs/sumAmount.spec.js +++ b/modules/client/back/methods/greuge/specs/sumAmount.spec.js @@ -1,14 +1,22 @@ -const totalGreuge = require('../sumAmount'); +const models = require('vn-loopback/server/server').models; describe('Greuge totalGreuge()', () => { it('should call the sumAmount method', async() => { - let clientFk = 1; - let self = jasmine.createSpyObj('self', ['remoteMethod', 'rawSql']); - self.rawSql.and.returnValue(Promise.resolve([{sumAmount: 6000}])); - totalGreuge(self); + const tx = await models.Client.beginTransaction({}); - let result = await self.sumAmount(clientFk); + try { + const options = {transaction: tx}; - expect(result).toBe(6000); + const clientId = 1101; + + const result = await models.Greuge.sumAmount(clientId, options); + + expect(result).toBe(203.71); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/greuge/sumAmount.js b/modules/client/back/methods/greuge/sumAmount.js index dcc780168a..198ef7251f 100644 --- a/modules/client/back/methods/greuge/sumAmount.js +++ b/modules/client/back/methods/greuge/sumAmount.js @@ -18,10 +18,15 @@ module.exports = Self => { } }); - Self.sumAmount = async clientFk => { - let query = `SELECT SUM(amount) AS sumAmount FROM vn.greuge WHERE clientFk = ?`; + Self.sumAmount = async(clientFk, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const query = `SELECT SUM(amount) AS sumAmount FROM vn.greuge WHERE clientFk = ?`; try { - let [response] = await Self.rawSql(query, [clientFk]); + const [response] = await Self.rawSql(query, [clientFk], myOptions); return response ? response.sumAmount : 0; } catch (e) { diff --git a/modules/client/back/methods/receipt/filter.js b/modules/client/back/methods/receipt/filter.js index b32249d4be..e29ccf8f28 100644 --- a/modules/client/back/methods/receipt/filter.js +++ b/modules/client/back/methods/receipt/filter.js @@ -7,23 +7,25 @@ module.exports = Self => { accepts: [ { arg: 'filter', - type: 'Object', + type: 'object', description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', http: {source: 'query'} - }, { + }, + { arg: 'clientId', - type: 'Number', + type: 'number', description: 'The client id', required: true, - }, { + }, + { arg: 'companyId', - type: 'Number', + type: 'number', description: 'The company id', required: true, } ], returns: { - type: ['Object'], + type: ['object'], root: true }, http: { @@ -32,51 +34,56 @@ module.exports = Self => { } }); - Self.filter = async(filter, clientId, companyId) => { - let stmt = new ParameterizedSQL( + Self.filter = async(filter, clientId, companyId, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const stmt = new ParameterizedSQL( `SELECT * FROM ( - SELECT - r.id, - r.isConciliate, - r.payed, - r.workerFk, - c.code company, - r.created, - r.invoiceFk description, - NULL debit, - r.amountPaid credit, - r.bankFk, - u.name userName, - r.clientFk, - FALSE hasPdf, - FALSE isInvoice - FROM vn.receipt r - LEFT JOIN vn.worker w ON w.id = r.workerFk - LEFT JOIN account.user u ON u.id = w.userFk - JOIN vn.company c ON c.id = r.companyFk - WHERE r.clientFk = ? AND r.companyFk = ? - UNION ALL - SELECT - i.id, - TRUE, - i.issued, - NULL, - c.code, - i.created, - i.ref, - i.amount, - NULL, - NULL, - NULL, - i.clientFk, - i.hasPdf, - TRUE isInvoice - FROM vn.invoiceOut i - JOIN vn.company c ON c.id = i.companyFk - WHERE i.clientFk = ? AND i.companyFk = ? - ORDER BY payed DESC, created DESC - ) t - ORDER BY payed DESC, created DESC`, [ + SELECT + r.id, + r.isConciliate, + r.payed, + r.workerFk, + c.code company, + r.created, + r.invoiceFk description, + NULL debit, + r.amountPaid credit, + r.bankFk, + u.name userName, + r.clientFk, + FALSE hasPdf, + FALSE isInvoice + FROM vn.receipt r + LEFT JOIN vn.worker w ON w.id = r.workerFk + LEFT JOIN account.user u ON u.id = w.userFk + JOIN vn.company c ON c.id = r.companyFk + WHERE r.clientFk = ? AND r.companyFk = ? + UNION ALL + SELECT + i.id, + TRUE, + i.issued, + NULL, + c.code, + i.created, + i.ref, + i.amount, + NULL, + NULL, + NULL, + i.clientFk, + i.hasPdf, + TRUE isInvoice + FROM vn.invoiceOut i + JOIN vn.company c ON c.id = i.companyFk + WHERE i.clientFk = ? AND i.companyFk = ? + ORDER BY payed DESC, created DESC + ) t ORDER BY payed DESC, created DESC`, + [ clientId, companyId, clientId, @@ -85,6 +92,7 @@ module.exports = Self => { ); stmt.merge(Self.makeLimit(filter)); - return await Self.rawStmt(stmt); + + return Self.rawStmt(stmt, myOptions); }; }; diff --git a/modules/client/back/methods/receipt/specs/filter.spec.js b/modules/client/back/methods/receipt/specs/filter.spec.js index 2af3b3127e..c28961d0cf 100644 --- a/modules/client/back/methods/receipt/specs/filter.spec.js +++ b/modules/client/back/methods/receipt/specs/filter.spec.js @@ -1,12 +1,23 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('receipt filter()', () => { it('should return the receipts', async() => { - const filter = {limit: 20}; - const clientId = 101; - const companyId = 442; - let result = await app.models.Receipt.filter(filter, clientId, companyId); + const tx = await models.Client.beginTransaction({}); - expect(result.length).toBeGreaterThan(0); + try { + const options = {transaction: tx}; + const filter = {limit: 20}; + const clientId = 1101; + const companyId = 442; + + const result = await models.Receipt.filter(filter, clientId, companyId, options); + + expect(result.length).toBeGreaterThan(0); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/recovery/hasActiveRecovery.js b/modules/client/back/methods/recovery/hasActiveRecovery.js index 81a8a5f402..a0d0064eb2 100644 --- a/modules/client/back/methods/recovery/hasActiveRecovery.js +++ b/modules/client/back/methods/recovery/hasActiveRecovery.js @@ -21,14 +21,20 @@ module.exports = Self => { } }); - Self.hasActiveRecovery = async id => { - let result = await Self.rawSql( - `SELECT count(*) AS hasActiveRecovery - FROM vn.recovery - WHERE clientFk = ? - AND IFNULL(finished,CURDATE()) >= CURDATE();`, - [id] - ); - return result[0].hasActiveRecovery != 0; + Self.hasActiveRecovery = async(id, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const query = ` + SELECT count(*) AS hasActiveRecovery + FROM vn.recovery + WHERE clientFk = ? + AND IFNULL(finished,CURDATE()) >= CURDATE(); + `; + const [result] = await Self.rawSql(query, [id], myOptions); + + return result.hasActiveRecovery != 0; }; }; diff --git a/modules/client/back/methods/recovery/hasActiveRecovery.spec.js b/modules/client/back/methods/recovery/hasActiveRecovery.spec.js index 218d10df50..8ff4d66cc8 100644 --- a/modules/client/back/methods/recovery/hasActiveRecovery.spec.js +++ b/modules/client/back/methods/recovery/hasActiveRecovery.spec.js @@ -1,15 +1,37 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('client hasActiveRecovery', () => { it(`should return false if the client doesn't owes`, async() => { - let hasActiveRecovery = await app.models.Recovery.hasActiveRecovery(101); + const tx = await models.Client.beginTransaction({}); - expect(hasActiveRecovery).toBeFalsy(); + try { + const options = {transaction: tx}; + + const hasActiveRecovery = await models.Recovery.hasActiveRecovery(1101, options); + + expect(hasActiveRecovery).toBeFalsy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return true if the client owes', async() => { - let hasActiveRecovery = await app.models.Recovery.hasActiveRecovery(102); + const tx = await models.Client.beginTransaction({}); - expect(hasActiveRecovery).toBeTruthy(); + try { + const options = {transaction: tx}; + + const hasActiveRecovery = await models.Recovery.hasActiveRecovery(1102, options); + + expect(hasActiveRecovery).toBeTruthy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/sms/send.js b/modules/client/back/methods/sms/send.js index 153036e058..c5cb6ace2a 100644 --- a/modules/client/back/methods/sms/send.js +++ b/modules/client/back/methods/sms/send.js @@ -6,22 +6,24 @@ module.exports = Self => { Self.remoteMethod('send', { description: 'Sends SMS to a destination phone', accessType: 'WRITE', - accepts: [{ - arg: 'destinationFk', - type: 'Integer' - }, - { - arg: 'destination', - type: 'String', - required: true, - }, - { - arg: 'message', - type: 'String', - required: true, - }], + accepts: [ + { + arg: 'destinationFk', + type: 'integer' + }, + { + arg: 'destination', + type: 'string', + required: true, + }, + { + arg: 'message', + type: 'string', + required: true, + } + ], returns: { - type: 'Object', + type: 'object', root: true }, http: { @@ -82,6 +84,7 @@ module.exports = Self => { }; const sms = await Self.create(newSms); + if (statusCode != 200) throw new UserError(`We weren't able to send this SMS`); diff --git a/modules/client/back/methods/sms/send.spec.js b/modules/client/back/methods/sms/send.spec.js index 2c65eab244..c39e2ad6ec 100644 --- a/modules/client/back/methods/sms/send.spec.js +++ b/modules/client/back/methods/sms/send.spec.js @@ -6,7 +6,7 @@ describe('sms send()', () => { const code = 200; spyOn(soap, 'createClientAsync').and.returnValue('a so fake client'); let ctx = {req: {accessToken: {userId: 1}}}; - let result = await app.models.Sms.send(ctx, 105, 'destination', 'My SMS Body'); + let result = await app.models.Sms.send(ctx, 1105, 'destination', 'My SMS Body'); expect(result.statusCode).toEqual(code); expect(result.status).toContain('Fake response'); diff --git a/modules/client/back/model-config.json b/modules/client/back/model-config.json index 1f18f4963e..38f5c94272 100644 --- a/modules/client/back/model-config.json +++ b/modules/client/back/model-config.json @@ -8,6 +8,9 @@ "BankEntity": { "dataSource": "vn" }, + "BusinessType": { + "dataSource": "vn" + }, "Client": { "dataSource": "vn" }, diff --git a/modules/client/back/models/business-type.json b/modules/client/back/models/business-type.json new file mode 100644 index 0000000000..e8399ed687 --- /dev/null +++ b/modules/client/back/models/business-type.json @@ -0,0 +1,24 @@ +{ + "name": "BusinessType", + "base": "VnModel", + "options": { + "mysql": { + "table": "businessType" + } + }, + "properties": { + "code": { + "type": "string", + "id": true + }, + "description": { + "type": "string" + } + }, + "acls": [{ + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }] +} \ No newline at end of file diff --git a/modules/client/back/models/client.js b/modules/client/back/models/client.js index 842565c3f1..6519cb979d 100644 --- a/modules/client/back/models/client.js +++ b/modules/client/back/models/client.js @@ -10,7 +10,6 @@ module.exports = Self => { // Methods require('../methods/client/getCard')(Self); require('../methods/client/createWithUser')(Self); - require('../methods/client/listWorkers')(Self); require('../methods/client/hasCustomerRole')(Self); require('../methods/client/canCreateTicket')(Self); require('../methods/client/isValidClient')(Self); @@ -181,10 +180,10 @@ module.exports = Self => { } Self.observe('before save', async function(ctx) { - let changes = ctx.data || ctx.instance; - let orgData = ctx.currentInstance; - let finalState = getFinalState(ctx); - let payMethodWithIban = 4; + const changes = ctx.data || ctx.instance; + const orgData = ctx.currentInstance; + const finalState = getFinalState(ctx); + const payMethodWithIban = 4; // Validate socialName format const hasChanges = orgData && changes; @@ -205,26 +204,22 @@ module.exports = Self => { changes.payMethodFk = 5; // Credit card } - let payMethodFk = changes.payMethodFk || (orgData && orgData.payMethodFk); - let dueDay = changes.dueDay || (orgData && orgData.dueDay); + const payMethodFk = changes.payMethodFk || (orgData && orgData.payMethodFk); + const dueDay = changes.dueDay || (orgData && orgData.dueDay); if (payMethodFk == payMethodWithIban && dueDay == 0) changes.dueDay = 5; if (isMultiple(ctx)) return; - if (changes.credit !== undefined) { - await validateCreditChange(ctx, finalState); - let filter = {fields: ['id'], where: {userFk: ctx.options.accessToken.userId}}; - let worker = await Self.app.models.Worker.findOne(filter); - - let newCredit = { - amount: changes.credit, - clientFk: finalState.id, - workerFk: worker ? worker.id : null - }; - await Self.app.models.ClientCredit.create(newCredit); + if (!ctx.isNewInstance) { + const isTaxDataCheckedChanged = !orgData.isTaxDataChecked && changes.isTaxDataChecked; + if (isTaxDataCheckedChanged && !orgData.businessTypeFk) + throw new UserError(`Can't verify data unless the client has a business type`); } + // Credit changes + if (changes.credit !== undefined) + await Self.changeCredit(ctx, finalState, changes); }); Self.observe('after save', async ctx => { @@ -327,42 +322,54 @@ module.exports = Self => { await models.Chat.send(httpCtx, `@${currentWorker.user}`, message); }; - async function validateCreditChange(ctx, finalState) { - let models = Self.app.models; - let userId = ctx.options.accessToken.userId; + // Credit change validations + Self.changeCredit = async function changeCredit(ctx, finalState, changes) { + const models = Self.app.models; + const userId = ctx.options.accessToken.userId; - let currentUserIsManager = await models.Account.hasRole(userId, 'manager'); - if (currentUserIsManager) - return; + const isManager = await models.Account.hasRole(userId, 'manager', ctx.options); + if (!isManager) { + const lastCredit = await models.ClientCredit.findOne({ + where: { + clientFk: finalState.id + }, + order: 'id DESC' + }, ctx.options); - let filter = { - fields: ['roleFk'], - where: { - maxAmount: {gt: ctx.data.credit} - } - }; + const lastAmount = lastCredit && lastCredit.amount; + const lastWorkerId = lastCredit && lastCredit.workerFk; + const lastWorkerIsManager = await models.Account.hasRole(lastWorkerId, 'manager', ctx.options); - let limits = await models.ClientCreditLimit.find(filter); + if (lastAmount == 0 && lastWorkerIsManager) + throw new UserError(`You can't change the credit set to zero from a manager`); - if (limits.length == 0) - throw new UserError('Credit limits not found'); + const creditLimits = await models.ClientCreditLimit.find({ + fields: ['roleFk'], + where: { + maxAmount: {gte: changes.credit} + } + }, ctx.options); - // Si el usuario no tiene alguno de los roles no continua + const requiredRoles = []; + for (limit of creditLimits) + requiredRoles.push(limit.roleFk); - let requiredRoles = []; - for (limit of limits) - requiredRoles.push(limit.roleFk); + const userRequiredRoles = await models.RoleMapping.count({ + roleId: {inq: requiredRoles}, + principalType: 'USER', + principalId: userId + }, ctx.options); - let where = { - roleId: {inq: requiredRoles}, - principalType: 'USER', - principalId: userId - }; - let count = await models.RoleMapping.count(where); + if (userRequiredRoles <= 0) + throw new UserError(`You don't have enough privileges to set this credit amount`); + } - if (count <= 0) - throw new UserError('The role cannot set this credit amount'); - } + await models.ClientCredit.create({ + amount: changes.credit, + clientFk: finalState.id, + workerFk: userId + }, ctx.options); + }; const app = require('vn-loopback/server/server'); app.on('started', function() { diff --git a/modules/client/back/models/client.json b/modules/client/back/models/client.json index b4682579af..1cf539439c 100644 --- a/modules/client/back/models/client.json +++ b/modules/client/back/models/client.json @@ -168,6 +168,11 @@ "model": "ClientType", "foreignKey": "clientTypeFk" }, + "businessType": { + "type": "belongsTo", + "model": "BusinessType", + "foreignKey": "businessTypeFk" + }, "addresses": { "type": "hasMany", "model": "Address", diff --git a/modules/client/back/models/pay-method.json b/modules/client/back/models/pay-method.json index 152544c01a..a025bee477 100644 --- a/modules/client/back/models/pay-method.json +++ b/modules/client/back/models/pay-method.json @@ -12,6 +12,9 @@ "id": true, "description": "Identifier" }, + "code": { + "type": "string" + }, "name": { "type": "string", "required": true diff --git a/modules/client/back/models/sage-tax-type.json b/modules/client/back/models/sage-tax-type.json index 858627c054..b60ef20cd5 100644 --- a/modules/client/back/models/sage-tax-type.json +++ b/modules/client/back/models/sage-tax-type.json @@ -20,6 +20,12 @@ "mysql": { "columnName": "Iva" } + }, + "rate": { + "type": "number", + "mysql": { + "columnName": "PorcentajeIva" + } } }, "acls": [ diff --git a/modules/client/back/models/sample.json b/modules/client/back/models/sample.json index 725bfb9c76..cfb127ab2d 100644 --- a/modules/client/back/models/sample.json +++ b/modules/client/back/models/sample.json @@ -9,23 +9,26 @@ "properties": { "id": { "id": true, - "type": "Number", + "type": "number", "description": "Identifier" }, "code": { - "type": "String" + "type": "string" }, "description": { - "type": "String" + "type": "string" }, "isVisible": { - "type": "Boolean" + "type": "boolean" }, "hasCompany": { - "type": "Boolean" + "type": "boolean" }, "hasPreview": { - "type": "Boolean" + "type": "boolean" + }, + "datepickerEnabled": { + "type": "boolean" } }, "scopes": { diff --git a/modules/client/back/models/specs/address.spec.js b/modules/client/back/models/specs/address.spec.js index 685acc80d0..3271c7d8f0 100644 --- a/modules/client/back/models/specs/address.spec.js +++ b/modules/client/back/models/specs/address.spec.js @@ -2,7 +2,7 @@ const app = require('vn-loopback/server/server'); describe('loopback model address', () => { let createdAddressId; - const clientId = 101; + const clientId = 1101; afterAll(async done => { let client = await app.models.Client.findById(clientId); diff --git a/modules/client/back/models/specs/client.spec.js b/modules/client/back/models/specs/client.spec.js index a9d479516c..d1a6d77cb9 100644 --- a/modules/client/back/models/specs/client.spec.js +++ b/modules/client/back/models/specs/client.spec.js @@ -1,4 +1,4 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('Client Model', () => { @@ -14,10 +14,10 @@ describe('Client Model', () => { } }; const ctx = {req: activeCtx}; - const chatModel = app.models.Chat; - const client = {id: 101, name: 'Bruce Banner'}; - const previousWorkerId = 106; // DavidCharlesHaller - const currentWorkerId = 107; // HankPym + const chatModel = models.Chat; + const instance = {id: 1101, name: 'Bruce Banner'}; + const previousWorkerId = 1106; // DavidCharlesHaller + const currentWorkerId = 1107; // HankPym beforeEach(() => { spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ @@ -29,7 +29,7 @@ describe('Client Model', () => { it('should call to the Chat send() method for both workers', async() => { spyOn(chatModel, 'send').and.callThrough(); - await app.models.Client.notifyAssignment(client, previousWorkerId, currentWorkerId); + await models.Client.notifyAssignment(instance, previousWorkerId, currentWorkerId); expect(chatModel.send).toHaveBeenCalledWith(ctx, '@DavidCharlesHaller', `Client assignment has changed`); expect(chatModel.send).toHaveBeenCalledWith(ctx, '@HankPym', `Client assignment has changed`); @@ -38,7 +38,7 @@ describe('Client Model', () => { it('should call to the Chat send() method for the previous worker', async() => { spyOn(chatModel, 'send').and.callThrough(); - await app.models.Client.notifyAssignment(client, null, currentWorkerId); + await models.Client.notifyAssignment(instance, null, currentWorkerId); expect(chatModel.send).toHaveBeenCalledWith(ctx, '@HankPym', `Client assignment has changed`); }); @@ -46,9 +46,69 @@ describe('Client Model', () => { it('should call to the Chat send() method for the current worker', async() => { spyOn(chatModel, 'send').and.callThrough(); - await app.models.Client.notifyAssignment(client, previousWorkerId, null); + await models.Client.notifyAssignment(instance, previousWorkerId, null); expect(chatModel.send).toHaveBeenCalledWith(ctx, '@DavidCharlesHaller', `Client assignment has changed`); }); }); + + describe('changeCredit()', () => { + it('should fail to change the credit as a salesAssistant set to zero by a manager', async() => { + const tx = await models.Client.beginTransaction({}); + + let error; + + try { + const options = {transaction: tx}; + const context = {options}; + + // Set credit to zero by a manager + const financialBoss = await models.Account.findOne({ + where: {name: 'financialBoss'} + }, options); + context.options.accessToken = {userId: financialBoss.id}; + + await models.Client.changeCredit(context, instance, {credit: 0}); + + const salesAssistant = await models.Account.findOne({ + where: {name: 'salesAssistant'} + }, options); + context.options.accessToken = {userId: salesAssistant.id}; + + await models.Client.changeCredit(context, instance, {credit: 300}); + + await tx.rollback(); + } catch (e) { + error = e; + await tx.rollback(); + } + + expect(error.message).toEqual(`You can't change the credit set to zero from a manager`); + }); + + it('should fail to change to a high credit amount as a salesAssistant', async() => { + const tx = await models.Client.beginTransaction({}); + + let error; + + try { + const options = {transaction: tx}; + const context = {options}; + + const salesAssistant = await models.Account.findOne({ + where: {name: 'salesAssistant'} + }, options); + context.options.accessToken = {userId: salesAssistant.id}; + + await models.Client.changeCredit(context, instance, {credit: 99999}); + + await tx.rollback(); + } catch (e) { + error = e; + await tx.rollback(); + } + + expect(error.message).toEqual(`You don't have enough privileges to set this credit amount`); + }); + }); }); diff --git a/modules/client/front/address/create/index.spec.js b/modules/client/front/address/create/index.spec.js index b12bc183b1..1be4766f5b 100644 --- a/modules/client/front/address/create/index.spec.js +++ b/modules/client/front/address/create/index.spec.js @@ -26,7 +26,7 @@ describe('Client', () => { } }; }; - controller.client = {id: 101, defaultAddressFk: 121}; + controller.client = {id: 1101, defaultAddressFk: 121}; })); it('should define and set address property', () => { diff --git a/modules/client/front/address/index/index.spec.js b/modules/client/front/address/index/index.spec.js index c7b4985c82..2a1f0d19ed 100644 --- a/modules/client/front/address/index/index.spec.js +++ b/modules/client/front/address/index/index.spec.js @@ -17,7 +17,7 @@ describe('Client', () => { $scope = $rootScope.$new(); const $element = angular.element(''); controller = $componentController('vnClientAddressIndex', {$element, $scope}); - controller.client = {id: 101, defaultAddressFk: 121}; + controller.client = {id: 1101, defaultAddressFk: 121}; controller.$.model = crudModel; })); diff --git a/modules/client/front/balance/create/index.html b/modules/client/front/balance/create/index.html index 89ec3b049e..f9bf89b049 100644 --- a/modules/client/front/balance/create/index.html +++ b/modules/client/front/balance/create/index.html @@ -20,9 +20,8 @@ label="Company" show-field="code" value-field="id" - ng-model="$ctrl.receipt.companyFk" - required="true" - rule> + ng-model="$ctrl.companyFk" + required="true"> @@ -34,7 +33,7 @@ fields="['accountingTypeFk']" include="{relation: 'accountingType'}" ng-model="$ctrl.bankFk" - search-function="{or: [{id: $search}, {bank: {like: '%'+ $search +'%'}}]}" + search-function="$ctrl.bankSearchFunc($search)" selection="$ctrl.bankSelection" order="id" required="true"> @@ -61,7 +60,8 @@ + label="Delivered amount" + step="0.01"> + + + + diff --git a/modules/client/front/balance/create/index.js b/modules/client/front/balance/create/index.js index 22426a2693..e78a9c1b29 100644 --- a/modules/client/front/balance/create/index.js +++ b/modules/client/front/balance/create/index.js @@ -2,9 +2,10 @@ import ngModule from '../../module'; import Dialog from 'core/components/dialog'; class Controller extends Dialog { - constructor($element, $, $transclude) { + constructor($element, $, $transclude, vnReport) { super($element, $, $transclude); + this.vnReport = vnReport; this.receipt = { payed: new Date() }; @@ -31,6 +32,12 @@ class Controller extends Dialog { return this.receipt.clientFk; } + get companyFk() { + if (!this.receipt.companyFk) + this.receipt.companyFk = this.vnConfig.companyFk; + return this.receipt.companyFk; + } + set companyFk(value) { this.receipt.companyFk = value; this.getAmountPaid(); @@ -62,6 +69,22 @@ class Controller extends Dialog { this.amountToReturn = value - this.receipt.amountPaid; } + get amountToReturn() { + return this._amountToReturn; + } + + set amountToReturn(value) { + if (!value) return; + + value = value.toFixed(2); + + if (Number.isInteger(value)) + value = parseInt(value); + else value = parseFloat(value); + + this._amountToReturn = value; + } + get deliveredAmount() { return this._deliveredAmount; } @@ -98,12 +121,32 @@ class Controller extends Dialog { if (response !== 'accept') return super.responseHandler(response); + let receiptId; return this.$http.post(`Clients/${this.clientFk}/createReceipt`, this.receipt) - .then(() => super.responseHandler(response)) - .then(() => this.vnApp.showSuccess(this.$t('Data saved!'))); + .then(res => { + receiptId = res.data.id; + super.responseHandler(response); + }) + .then(() => this.vnApp.showSuccess(this.$t('Data saved!'))) + .then(() => { + if (this.viewReceipt) { + this.vnReport.show('receipt', { + receiptId: receiptId, + companyId: this.companyFk + }); + } + }); + } + + bankSearchFunc($search) { + return /^\d+$/.test($search) + ? {id: $search} + : {bank: {like: '%' + $search + '%'}}; } } +Controller.$inject = ['$element', '$scope', '$transclude', 'vnReport']; + ngModule.vnComponent('vnClientBalanceCreate', { slotTemplate: require('./index.html'), controller: Controller, diff --git a/modules/client/front/balance/create/index.spec.js b/modules/client/front/balance/create/index.spec.js index 90015be19b..bd0607a797 100644 --- a/modules/client/front/balance/create/index.spec.js +++ b/modules/client/front/balance/create/index.spec.js @@ -20,7 +20,7 @@ describe('Client', () => { }; controller = $componentController('vnClientBalanceCreate', {$element, $scope, $transclude}); controller.receipt = { - clientFk: 101, + clientFk: 1101, companyFk: 442 }; })); @@ -40,13 +40,21 @@ describe('Client', () => { }); }); + describe('amountToReturn() setter', () => { + it('should set the amount to return with a maximum of two decimals', () => { + controller.amountToReturn = 200.1451789; + + expect(controller.amountToReturn).toEqual(200.15); + }); + }); + describe('getAmountPaid()', () => { it('should make an http GET query and then set the receipt amountPaid property', () => { - controller.$params = {id: 101}; + controller.$params = {id: 1101}; const receipt = controller.receipt; const filter = { where: { - clientFk: 101, + clientFk: 1101, companyFk: 442 } }; @@ -62,14 +70,34 @@ describe('Client', () => { describe('responseHandler()', () => { it('should make an http POST query and then call to the parent responseHandler() method', () => { jest.spyOn(controller.vnApp, 'showSuccess'); + jest.spyOn(controller.vnReport, 'show'); - controller.$params = {id: 101}; + controller.$params = {id: 1101}; - $httpBackend.expect('POST', `Clients/101/createReceipt`).respond({id: 1}); + $httpBackend.expect('POST', `Clients/1101/createReceipt`).respond({id: 1}); controller.responseHandler('accept'); $httpBackend.flush(); expect(controller.vnApp.showSuccess).toHaveBeenCalled(); + expect(controller.vnReport.show).not.toHaveBeenCalled(); + }); + + it('should make an http POST query and then call to the report show() method', () => { + jest.spyOn(controller.vnApp, 'showSuccess'); + jest.spyOn(controller.vnReport, 'show'); + window.open = jest.fn(); + + controller.$params = {id: 1101}; + controller.viewReceipt = true; + + $httpBackend.expect('POST', `Clients/1101/createReceipt`).respond({id: 1}); + controller.responseHandler('accept'); + $httpBackend.flush(); + + const expectedParams = {receiptId: 1, companyId: 442}; + + expect(controller.vnApp.showSuccess).toHaveBeenCalled(); + expect(controller.vnReport.show).toHaveBeenCalledWith('receipt', expectedParams); }); }); @@ -90,5 +118,21 @@ describe('Client', () => { expect(controller.receipt.compensationAccount).toEqual('4000000003'); }); }); + + describe('bankSearchFunc()', () => { + it('should return the filter by id property for an input of a number', () => { + const bankId = 1; + const result = controller.bankSearchFunc(bankId); + + expect(result).toEqual({id: bankId}); + }); + + it('should return the filter by bank property for an input of an string', () => { + const bankName = 'Bank of America'; + const result = controller.bankSearchFunc(bankName); + + expect(result).toEqual({bank: {like: '%' + bankName + '%'}}); + }); + }); }); }); diff --git a/modules/client/front/balance/create/locale/es.yml b/modules/client/front/balance/create/locale/es.yml new file mode 100644 index 0000000000..266e4365cd --- /dev/null +++ b/modules/client/front/balance/create/locale/es.yml @@ -0,0 +1 @@ +View receipt: Ver recibo \ No newline at end of file diff --git a/modules/client/front/balance/index/index.html b/modules/client/front/balance/index/index.html index 596838c0c2..3c61d8543d 100644 --- a/modules/client/front/balance/index/index.html +++ b/modules/client/front/balance/index/index.html @@ -47,7 +47,7 @@ Date - Creation date + Creation date Employee Reference Bank @@ -65,7 +65,7 @@ {{::balance.payed | date:'dd/MM/yyyy'}} - + {{::balance.created | date:'dd/MM/yyyy HH:mm'}} diff --git a/modules/client/front/balance/index/index.spec.js b/modules/client/front/balance/index/index.spec.js index bdbea38460..e130ac655e 100644 --- a/modules/client/front/balance/index/index.spec.js +++ b/modules/client/front/balance/index/index.spec.js @@ -17,7 +17,7 @@ describe('Client', () => { applyFilter: () => {}, data: [{ - clientFk: 101, + clientFk: 1101, companyFk: 442, amount: 713.24, company: { @@ -31,14 +31,14 @@ describe('Client', () => { describe('getData()', () => { it('should apply the filters on he models and get the client balance', () => { controller._companyId = 442; - controller.$params.id = 101; + controller.$params.id = 1101; jest.spyOn(controller, 'getBalances').mockReturnThis(); jest.spyOn(controller.$.model, 'applyFilter').mockReturnValue(Promise.resolve()); jest.spyOn(controller.$.riskModel, 'applyFilter').mockReturnValue(Promise.resolve()); controller.getData().then(() => { - expect(controller.$.model.applyFilter).toHaveBeenCalledWith(null, {'clientId': 101, 'companyId': 442}); - expect(controller.$.riskModel.applyFilter).toHaveBeenCalledWith({'where': {'clientFk': 101, 'companyFk': 442}}); + expect(controller.$.model.applyFilter).toHaveBeenCalledWith(null, {'clientId': 1101, 'companyId': 442}); + expect(controller.$.riskModel.applyFilter).toHaveBeenCalledWith({'where': {'clientFk': 1101, 'companyFk': 442}}); expect(controller.getBalances).toHaveBeenCalledWith(); }); }); diff --git a/modules/client/front/basic-data/index.html b/modules/client/front/basic-data/index.html index 4a705c3842..a76b448f26 100644 --- a/modules/client/front/basic-data/index.html +++ b/modules/client/front/basic-data/index.html @@ -20,6 +20,14 @@ rule vn-focus> + + - sin espacios, ejemplo: user@dominio.com, user2@dominio.com siendo el primer correo electrónico el principal Contact: Contacto -Undo changes: Deshacer cambios \ No newline at end of file +Undo changes: Deshacer cambios +Business type: Tipo de negocio \ No newline at end of file diff --git a/modules/client/front/billing-data/index.html b/modules/client/front/billing-data/index.html index b9c20ec24c..ff2e2f157b 100644 --- a/modules/client/front/billing-data/index.html +++ b/modules/client/front/billing-data/index.html @@ -66,7 +66,7 @@ @@ -108,53 +108,8 @@ - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + + + \ No newline at end of file diff --git a/modules/client/front/billing-data/index.js b/modules/client/front/billing-data/index.js index 2dda347b9d..7056fa566e 100644 --- a/modules/client/front/billing-data/index.js +++ b/modules/client/front/billing-data/index.js @@ -37,17 +37,8 @@ export default class Controller extends Section { return payMethod || iban || dueDay; } - onAddEntityClick(event) { - event.preventDefault(); - this.newBankEntity = { - countryFk: Number.parseInt(this.client.countryFk) - }; - this.$.bankEntityDialog.show(); - } - - onBankEntityAccept() { - return this.$http.post(`BankEntities`, this.newBankEntity) - .then(res => this.client.bankEntityFk = res.data.id); + onAccept(data) { + this.client.bankEntityFk = data.id; } get ibanCountry() { diff --git a/modules/client/front/billing-data/index.spec.js b/modules/client/front/billing-data/index.spec.js index dd44bd0fa7..2e9e8ba97a 100644 --- a/modules/client/front/billing-data/index.spec.js +++ b/modules/client/front/billing-data/index.spec.js @@ -17,8 +17,8 @@ describe('Client', () => { $scope.watcher = {}; jest.spyOn(vnApp, 'showError'); controller = $componentController('vnClientBillingData', {$element, $scope}); - controller.client = {id: 101, name: 'Client name', payMethodFk: 4}; - $scope.watcher.orgData = {id: 101, name: 'Client name', payMethodFk: 4}; + controller.client = {id: 1101, name: 'Client name', payMethodFk: 4}; + $scope.watcher.orgData = {id: 1101, name: 'Client name', payMethodFk: 4}; })); describe('hasPaymethodChanges()', () => { @@ -35,20 +35,12 @@ describe('Client', () => { }); }); - describe('onBankEntityAccept()', () => { - it('should request to create a new bank entity', () => { - let newBankEntity = { - name: 'My new bank entity', - bic: 'ES123', - countryFk: 1, - id: 999 - }; - controller.newBankEntity = newBankEntity; - $httpBackend.expectPOST('BankEntities', newBankEntity).respond({id: 999}); - controller.onBankEntityAccept(); - $httpBackend.flush(); + describe('onAccept()', () => { + it('should assign the response id to the client bankEntityFk', () => { + const expectedResponse = {id: 999}; + controller.onAccept(expectedResponse); - expect(controller.client.bankEntityFk).toEqual(newBankEntity.id); + expect(controller.client.bankEntityFk).toEqual(expectedResponse.id); }); }); diff --git a/modules/client/front/billing-data/locale/es.yml b/modules/client/front/billing-data/locale/es.yml index a7ecbbdae8..0052ee4039 100644 --- a/modules/client/front/billing-data/locale/es.yml +++ b/modules/client/front/billing-data/locale/es.yml @@ -14,5 +14,4 @@ Received core VNL: Recibido core VNL Received B2B VNL: Recibido B2B VNL Save: Guardar New bank entity: Nueva entidad bancaria -Name can't be empty: El nombre no puede quedar vacío -Entity Code: Código \ No newline at end of file +Name can't be empty: El nombre no puede quedar vacío \ No newline at end of file diff --git a/modules/client/front/consumption/index.spec.js b/modules/client/front/consumption/index.spec.js index 9fe92fee19..16b764b56b 100644 --- a/modules/client/front/consumption/index.spec.js +++ b/modules/client/front/consumption/index.spec.js @@ -18,7 +18,7 @@ describe('Client', () => { controller = $componentController('vnClientConsumption', {$element, $scope}); controller.$.model = crudModel; controller.client = { - id: 101 + id: 1101 }; })); @@ -35,7 +35,7 @@ describe('Client', () => { controller.showReport(); const expectedParams = { - recipientId: 101, + recipientId: 1101, from: now, to: now }; @@ -54,7 +54,7 @@ describe('Client', () => { to: now }; const expectedParams = { - recipientId: 101, + recipientId: 1101, from: now, to: now }; diff --git a/modules/client/front/credit-insurance/create/index.spec.js b/modules/client/front/credit-insurance/create/index.spec.js index 83cec62f86..36a91ceca9 100644 --- a/modules/client/front/credit-insurance/create/index.spec.js +++ b/modules/client/front/credit-insurance/create/index.spec.js @@ -16,7 +16,7 @@ describe('Client', () => { }; const $element = angular.element(''); controller = $componentController('vnClientCreditInsuranceCreate', {$element, $scope}); - controller.client = {id: 101}; + controller.client = {id: 1101}; controller.card = { reload: () => {} }; @@ -35,7 +35,7 @@ describe('Client', () => { started: started, credit: 300, grade: 1, - clientFk: 101 + clientFk: 1101 }; $httpBackend.whenPOST(`creditClassifications/createWithInsurance`, newData).respond(200, true); diff --git a/modules/client/front/credit-insurance/index/index.spec.js b/modules/client/front/credit-insurance/index/index.spec.js index 678301f289..8629db684b 100644 --- a/modules/client/front/credit-insurance/index/index.spec.js +++ b/modules/client/front/credit-insurance/index/index.spec.js @@ -13,7 +13,7 @@ describe('Client', () => { $scope = $rootScope.$new(); const $element = angular.element(''); controller = $componentController('vnClientCreditInsuranceIndex', {$element, $scope}); - controller.client = {id: 101}; + controller.client = {id: 1101}; })); describe('_getClassifications()', () => { @@ -81,7 +81,7 @@ describe('Client', () => { controller.returnDialog(); $httpBackend.flush(); - expect(controller._getClassifications).toHaveBeenCalledWith(101); + expect(controller._getClassifications).toHaveBeenCalledWith(1101); }); }); }); diff --git a/modules/client/front/credit/create/index.spec.js b/modules/client/front/credit/create/index.spec.js index 2fda0af659..f8deb69117 100644 --- a/modules/client/front/credit/create/index.spec.js +++ b/modules/client/front/credit/create/index.spec.js @@ -28,7 +28,7 @@ describe('Client', () => { }; client = {credit: 0}; $state = _$state_; - $state.params.id = 101; + $state.params.id = 1101; $httpBackend = _$httpBackend_; const $element = angular.element(''); controller = $componentController('vnClientCreditCreate', {$element, $scope}); @@ -36,16 +36,16 @@ describe('Client', () => { describe('onSubmit()', () => { it('should perform a query to check (GET) if the client has an active recovery', () => { - $httpBackend.whenGET(`Recoveries/101/hasActiveRecovery`).respond(true); - $httpBackend.expectGET(`Recoveries/101/hasActiveRecovery`); + $httpBackend.whenGET(`Recoveries/1101/hasActiveRecovery`).respond(true); + $httpBackend.expectGET(`Recoveries/1101/hasActiveRecovery`); controller.onSubmit(); $httpBackend.flush(); }); it('should call show() method when the client have a recovery', () => { jest.spyOn(controller.$.confirmation, 'show'); - $httpBackend.whenGET(`Recoveries/101/hasActiveRecovery`).respond(true); - $httpBackend.expectGET(`Recoveries/101/hasActiveRecovery`); + $httpBackend.whenGET(`Recoveries/1101/hasActiveRecovery`).respond(true); + $httpBackend.expectGET(`Recoveries/1101/hasActiveRecovery`); controller.onSubmit(); $httpBackend.flush(); @@ -54,8 +54,8 @@ describe('Client', () => { it('should call addCredit() method when the client doesnt have a recovery', () => { jest.spyOn(controller, 'addCredit'); - $httpBackend.whenGET(`Recoveries/101/hasActiveRecovery`).respond(false); - $httpBackend.expectGET(`Recoveries/101/hasActiveRecovery`); + $httpBackend.whenGET(`Recoveries/1101/hasActiveRecovery`).respond(false); + $httpBackend.expectGET(`Recoveries/1101/hasActiveRecovery`); controller.onSubmit(); $httpBackend.flush(); diff --git a/modules/client/front/credit/index/index.html b/modules/client/front/credit/index/index.html index 8e072a8869..989a0129f3 100644 --- a/modules/client/front/credit/index/index.html +++ b/modules/client/front/credit/index/index.html @@ -22,7 +22,7 @@ - {{::credit.created | date:'dd/MM/yyyy HH:mm'}} + {{::credit.created | date:'dd/MM/yyyy HH:mm'}}
diff --git a/modules/client/front/dms/create/index.spec.js b/modules/client/front/dms/create/index.spec.js index 5fa1a38352..fe302f7d27 100644 --- a/modules/client/front/dms/create/index.spec.js +++ b/modules/client/front/dms/create/index.spec.js @@ -15,7 +15,7 @@ describe('Client', () => { $httpParamSerializer = _$httpParamSerializer_; const $element = angular.element(''); controller = $componentController('vnClientDmsCreate', {$element, $scope}); - controller._client = {id: 101, name: 'Bruce wayne'}; + controller._client = {id: 1101, name: 'Bruce wayne'}; })); describe('client() setter', () => { @@ -44,7 +44,7 @@ describe('Client', () => { $httpBackend.flush(); expect(controller.dms).toBeDefined(); - expect(controller.dms.reference).toEqual(101); + expect(controller.dms.reference).toEqual(1101); expect(controller.dms.dmsTypeId).toEqual(12); }); }); diff --git a/modules/client/front/dms/edit/index.spec.js b/modules/client/front/dms/edit/index.spec.js index d063db57d6..155b1aba3b 100644 --- a/modules/client/front/dms/edit/index.spec.js +++ b/modules/client/front/dms/edit/index.spec.js @@ -36,7 +36,7 @@ describe('Client', () => { it('should perform a GET query and define the dms property on controller', () => { const dmsId = 1; const expectedResponse = { - reference: 101, + reference: 1101, warehouseFk: 1, companyFk: 442, dmsTypeFk: 12, @@ -50,7 +50,7 @@ describe('Client', () => { $httpBackend.flush(); expect(controller.dms).toBeDefined(); - expect(controller.dms.reference).toEqual(101); + expect(controller.dms.reference).toEqual(1101); expect(controller.dms.dmsTypeId).toEqual(12); }); }); diff --git a/modules/client/front/dms/index/index.html b/modules/client/front/dms/index/index.html index bface56482..7098fcbbd8 100644 --- a/modules/client/front/dms/index/index.html +++ b/modules/client/front/dms/index/index.html @@ -22,8 +22,8 @@ Description Original File - Employee - Created + Employee + Created @@ -70,7 +70,7 @@ ng-click="workerDescriptor.show($event, document.dms.workerFk)"> {{::document.dms.worker.user.name | dashIfEmpty}} - + {{::document.dms.created | date:'dd/MM/yyyy HH:mm'}} diff --git a/modules/client/front/fiscal-data/index.spec.js b/modules/client/front/fiscal-data/index.spec.js index 17e7309147..609ba51217 100644 --- a/modules/client/front/fiscal-data/index.spec.js +++ b/modules/client/front/fiscal-data/index.spec.js @@ -14,12 +14,12 @@ describe('Client', () => { $httpBackend = _$httpBackend_; $scope = $rootScope.$new(); $scope.watcher = watcher; - $scope.watcher.orgData = {id: 101, isEqualizated: false, isTaxDataChecked: false}; + $scope.watcher.orgData = {id: 1101, isEqualizated: false, isTaxDataChecked: false}; $element = angular.element(''); controller = $componentController('vnClientFiscalData', {$element, $scope}); controller.card = {reload: () => {}}; controller.client = { - id: 101, + id: 1101, email: 'batman@gothamcity.com', phone: '1111111111', isEqualizated: false, @@ -95,14 +95,14 @@ describe('Client', () => { ] } }; - const expectedClient = {id: 102}; + const expectedClient = {id: 1102}; const filter = encodeURIComponent(JSON.stringify(filterObj)); $httpBackend.expect('GET', `Clients/findOne?filter=${filter}`).respond(expectedClient); controller.checkExistingClient(); $httpBackend.flush(); expect(controller.$.confirmDuplicatedClient.show).toHaveBeenCalledWith(); - expect(controller.client.despiteOfClient).toEqual(102); + expect(controller.client.despiteOfClient).toEqual(1102); }); }); diff --git a/modules/client/front/greuge/index/index.html b/modules/client/front/greuge/index/index.html index 4fd10192f7..b48fe94669 100644 --- a/modules/client/front/greuge/index/index.html +++ b/modules/client/front/greuge/index/index.html @@ -36,7 +36,7 @@ - {{::greuge.shipped | date:'dd/MM/yyyy HH:mm' }} + {{::greuge.shipped | date:'dd/MM/yyyy HH:mm' }} {{::greuge.description}} diff --git a/modules/client/front/index/index.spec.js b/modules/client/front/index/index.spec.js index 4fc2c4f8c3..e37dccde41 100644 --- a/modules/client/front/index/index.spec.js +++ b/modules/client/front/index/index.spec.js @@ -16,7 +16,7 @@ describe('Client index', () => { describe('filterTickets()', () => { it('should navigate to the ticket index using params as filter', () => { - const client = {id: 101}; + const client = {id: 1101}; const event = new MouseEvent('click', {cancelable: true}); jest.spyOn($state, 'go'); diff --git a/modules/client/front/mandate/index.html b/modules/client/front/mandate/index.html index e6a9b97fe1..e2f2cd27b4 100644 --- a/modules/client/front/mandate/index.html +++ b/modules/client/front/mandate/index.html @@ -18,8 +18,8 @@ Id Company Type - Register date - End date + Register date + End date @@ -27,8 +27,8 @@ {{::mandate.id}} {{::mandate.company.code}} {{::mandate.mandateType.name}} - {{::mandate.created | date:'dd/MM/yyyy HH:mm' | dashIfEmpty}} - {{::mandate.finished | date:'dd/MM/yyyy HH:mm' | dashIfEmpty}} + {{::mandate.created | date:'dd/MM/yyyy HH:mm' | dashIfEmpty}} + {{::mandate.finished | date:'dd/MM/yyyy HH:mm' | dashIfEmpty}} diff --git a/modules/client/front/postcode/city/index.spec.js b/modules/client/front/postcode/city/index.spec.js index c6cd8732fd..18f93fe236 100644 --- a/modules/client/front/postcode/city/index.spec.js +++ b/modules/client/front/postcode/city/index.spec.js @@ -13,7 +13,7 @@ describe('Client', () => { $scope = $rootScope.$new(); const $element = angular.element(''); controller = $componentController('vnGeoCity', {$element, $scope}); - controller.client = {id: 101}; + controller.client = {id: 1101}; })); describe('onAccept()', () => { diff --git a/modules/client/front/postcode/index.spec.js b/modules/client/front/postcode/index.spec.js index 607866f44c..4978523248 100644 --- a/modules/client/front/postcode/index.spec.js +++ b/modules/client/front/postcode/index.spec.js @@ -13,7 +13,7 @@ describe('Client', () => { $scope = $rootScope.$new(); const $element = angular.element(''); controller = $componentController('vnGeoPostcode', {$element, $scope}); - controller.client = {id: 101}; + controller.client = {id: 1101}; })); describe('onAccept()', () => { diff --git a/modules/client/front/postcode/province/index.html b/modules/client/front/postcode/province/index.html index 03836901cb..e05cdf6440 100644 --- a/modules/client/front/postcode/province/index.html +++ b/modules/client/front/postcode/province/index.html @@ -12,11 +12,11 @@ label="Name"> + label="Autonomy"> diff --git a/modules/client/front/postcode/province/index.js b/modules/client/front/postcode/province/index.js index 6a0193d940..5da81aa52a 100644 --- a/modules/client/front/postcode/province/index.js +++ b/modules/client/front/postcode/province/index.js @@ -13,8 +13,8 @@ class Controller extends Component { try { if (!this.province.name) throw new Error(`The province name can't be empty`); - if (!this.province.countryFk) - throw new Error(`The country can't be empty`); + if (!this.province.autonomyFk) + throw new Error(`The autonomy can't be empty`); this.$http.patch(`provinces`, this.province).then(res => { this.vnApp.showMessage(this.$t('The province has been created')); diff --git a/modules/client/front/postcode/province/index.spec.js b/modules/client/front/postcode/province/index.spec.js index c28ecb489e..f73a3c284a 100644 --- a/modules/client/front/postcode/province/index.spec.js +++ b/modules/client/front/postcode/province/index.spec.js @@ -13,13 +13,13 @@ describe('Client', () => { $scope = $rootScope.$new(); const $element = angular.element(''); controller = $componentController('vnGeoProvince', {$element, $scope}); - controller.client = {id: 101}; + controller.client = {id: 1101}; })); describe('onAccept()', () => { it('should perform a POST query and show a success snackbar', () => { - let params = {name: 'New Jersey', countryFk: 1}; - controller.province = {name: 'New Jersey', countryFk: 1}; + const params = {name: 'New Jersey', autonomyFk: 1}; + controller.province = {name: 'New Jersey', autonomyFk: 1}; jest.spyOn(controller.vnApp, 'showMessage'); $httpBackend.expect('PATCH', `provinces`, params).respond(200, params); diff --git a/modules/client/front/sample/create/index.html b/modules/client/front/sample/create/index.html index e6733a6567..2d0f3d29ce 100644 --- a/modules/client/front/sample/create/index.html +++ b/modules/client/front/sample/create/index.html @@ -25,38 +25,48 @@
- - - - - - - - + label="Sample" + required="true"> + + + + + + + + + ng-if="sampleType.selection.hasCompany" + required="true"> + + diff --git a/modules/client/front/sample/create/index.js b/modules/client/front/sample/create/index.js index 0eaeddc20b..19fe1fecf6 100644 --- a/modules/client/front/sample/create/index.js +++ b/modules/client/front/sample/create/index.js @@ -80,6 +80,12 @@ class Controller extends Section { if (sampleType.hasCompany) params.companyId = this.clientSample.companyFk; + if (sampleType.datepickerEnabled && !this.clientSample.from) + return this.vnApp.showError(this.$t('Choose a date')); + + if (sampleType.datepickerEnabled) + params.from = this.clientSample.from; + let query = `email/${sampleType.code}`; if (isPreview) query = `email/${sampleType.code}/preview`; diff --git a/modules/client/front/sample/create/index.spec.js b/modules/client/front/sample/create/index.spec.js index 37d322b5fd..781025fd22 100644 --- a/modules/client/front/sample/create/index.spec.js +++ b/modules/client/front/sample/create/index.spec.js @@ -35,7 +35,7 @@ describe('Client', () => { show: () => {} }; $state = _$state_; - $state.params.id = 101; + $state.params.id = 1101; $httpBackend = _$httpBackend_; $httpParamSerializer = _$httpParamSerializer_; $element = angular.element(''); @@ -68,7 +68,7 @@ describe('Client', () => { code: 'MyReport' }; controller.clientSample = { - recipientId: 101 + recipientId: 1101 }; controller.send(false, () => {}); @@ -81,7 +81,7 @@ describe('Client', () => { controller.$.sampleType.selection = null; controller.clientSample = { - recipientId: 101, + recipientId: 1101, recipient: 'client@email.com' }; @@ -98,7 +98,7 @@ describe('Client', () => { code: 'MyReport' }; controller.clientSample = { - recipientId: 101, + recipientId: 1101, recipient: 'client@email.com' }; @@ -113,11 +113,11 @@ describe('Client', () => { code: 'MyReport' }; controller.clientSample = { - recipientId: 101, + recipientId: 1101, recipient: 'client@email.com' }; const expectedParams = { - recipientId: 101, + recipientId: 1101, recipient: 'client@email.com' }; const serializedParams = $httpParamSerializer(expectedParams); @@ -133,12 +133,12 @@ describe('Client', () => { code: 'MyReport' }; controller.clientSample = { - recipientId: 101, + recipientId: 1101, recipient: 'client@email.com', companyFk: 442 }; const expectedParams = { - recipientId: 101, + recipientId: 1101, recipient: 'client@email.com', companyId: 442 }; diff --git a/modules/client/front/sample/create/locale/es.yml b/modules/client/front/sample/create/locale/es.yml index a534e05d49..b72d456d8a 100644 --- a/modules/client/front/sample/create/locale/es.yml +++ b/modules/client/front/sample/create/locale/es.yml @@ -1,5 +1,6 @@ Choose a sample: Selecciona una plantilla Choose a company: Selecciona una empresa +Choose a date: Selecciona una fecha Email cannot be blank: Debes introducir un email Recipient: Destinatario Its only used when sample is sent: Se utiliza únicamente cuando se envía la plantilla diff --git a/modules/client/front/sample/index/index.html b/modules/client/front/sample/index/index.html index 7bb503fa2c..5909e12831 100644 --- a/modules/client/front/sample/index/index.html +++ b/modules/client/front/sample/index/index.html @@ -23,8 +23,8 @@ - {{::sample.created | date:'dd/MM/yyyy HH:mm' }} - {{::sample.created | date:'dd/MM/yyyy HH:mm' }} + {{::sample.type.description}} diff --git a/modules/client/front/sms/index.spec.js b/modules/client/front/sms/index.spec.js index 3462bf6814..793c80d6eb 100644 --- a/modules/client/front/sms/index.spec.js +++ b/modules/client/front/sms/index.spec.js @@ -13,8 +13,8 @@ describe('Client', () => { let $scope = $rootScope.$new(); $element = angular.element(''); controller = $componentController('vnClientSms', {$element, $scope}); - controller.client = {id: 101}; - controller.$params = {id: 101}; + controller.client = {id: 1101}; + controller.$params = {id: 1101}; controller.$.message = { input: { value: 'My SMS' @@ -24,11 +24,11 @@ describe('Client', () => { describe('onResponse()', () => { it('should perform a POST query and show a success snackbar', () => { - let params = {destinationFk: 101, destination: 111111111, message: 'My SMS'}; - controller.sms = {destinationFk: 101, destination: 111111111, message: 'My SMS'}; + let params = {destinationFk: 1101, destination: 111111111, message: 'My SMS'}; + controller.sms = {destinationFk: 1101, destination: 111111111, message: 'My SMS'}; jest.spyOn(controller.vnApp, 'showMessage'); - $httpBackend.expect('POST', `Clients/101/sendSms`, params).respond(200, params); + $httpBackend.expect('POST', `Clients/1101/sendSms`, params).respond(200, params); controller.onResponse(); $httpBackend.flush(); @@ -37,7 +37,7 @@ describe('Client', () => { }); it('should call onResponse without the destination and show an error snackbar', () => { - controller.sms = {destinationFk: 101, message: 'My SMS'}; + controller.sms = {destinationFk: 1101, message: 'My SMS'}; jest.spyOn(controller.vnApp, 'showError'); @@ -47,7 +47,7 @@ describe('Client', () => { }); it('should call onResponse without the message and show an error snackbar', () => { - controller.sms = {destinationFk: 101, destination: 222222222}; + controller.sms = {destinationFk: 1101, destination: 222222222}; jest.spyOn(controller.vnApp, 'showError'); diff --git a/modules/client/front/summary/index.html b/modules/client/front/summary/index.html index 6ff742c36b..3c5a8d3e5a 100644 --- a/modules/client/front/summary/index.html +++ b/modules/client/front/summary/index.html @@ -1,8 +1,7 @@ Route Packages Date - State - Total + State + Total @@ -349,7 +348,7 @@ - + {{::(ticket.totalWithVat ? ticket.totalWithVat : 0) | currency: 'EUR': 2}} diff --git a/modules/client/front/summary/index.js b/modules/client/front/summary/index.js index b1f0faf130..1f22612d27 100644 --- a/modules/client/front/summary/index.js +++ b/modules/client/front/summary/index.js @@ -32,10 +32,20 @@ class Controller extends Summary { ] }; } - $onChanges() { - if (!this.client) - return; + get client() { + return this._client; + } + + set client(value) { + this._client = value; + if (value) { + this.loadData(); + this.loadTickets(); + } + } + + loadData() { this.$http.get(`Clients/${this.client.id}/summary`).then(res => { if (res && res.data) { this.summary = res.data; @@ -48,6 +58,10 @@ class Controller extends Summary { }); } + loadTickets() { + this.$.$applyAsync(() => this.$.ticketsModel.refresh()); + } + get isEmployee() { return this.aclService.hasAny(['employee']); } diff --git a/modules/client/front/summary/index.spec.js b/modules/client/front/summary/index.spec.js index 397bb42400..0261cef451 100644 --- a/modules/client/front/summary/index.spec.js +++ b/modules/client/front/summary/index.spec.js @@ -1,4 +1,5 @@ import './index'; +import crudModel from 'core/mocks/crud-model'; describe('Client', () => { describe('Component vnClientSummary', () => { @@ -13,17 +14,30 @@ describe('Client', () => { $httpBackend = _$httpBackend_; const $element = angular.element(''); controller = $componentController('vnClientSummary', {$element}); - controller.client = {id: 101}; + controller._client = {id: 1101}; + controller.$.ticketsModel = crudModel; })); - describe('$onChanges()', () => { + describe('client() setter', () => { + it('should call to the loadData() and loadTickets() methods', () => { + controller.loadData = jest.fn(); + controller.loadTickets = jest.fn(); + + controller.client = {id: 1102}; + + expect(controller.loadData).toHaveBeenCalledWith(); + expect(controller.loadTickets).toHaveBeenCalledWith(); + }); + }); + + describe('loadData()', () => { it('should perform a GET query and then define the summary property', () => { let res = {name: 'Superman', classifications: []}; jest.spyOn(controller, 'sumRisk').mockReturnThis(); - $httpBackend.expect('GET', `Clients/101/summary`).respond(200, res); + $httpBackend.expect('GET', `Clients/1101/summary`).respond(200, res); - controller.$onChanges(); + controller.loadData(); $httpBackend.flush(); expect(controller.summary).toBeDefined(); @@ -31,6 +45,17 @@ describe('Client', () => { }); }); + describe('loadTickets()', () => { + it('should call to the model refresh() method', () => { + jest.spyOn(controller.$.ticketsModel, 'refresh'); + + controller.loadTickets(); + controller.$.$apply(); + + expect(controller.$.ticketsModel.refresh).toHaveBeenCalledWith(); + }); + }); + describe('sumRisk()', () => { it('should sum property amount of an array', () => { controller.summary = { @@ -113,7 +138,7 @@ describe('Client', () => { controller.$.summary = {show: () => {}}; jest.spyOn(controller.$.summary, 'show'); - const ticket = {id: 1, clientFk: 101}; + const ticket = {id: 1, clientFk: 1101}; const event = new MouseEvent('click', { view: $window, diff --git a/modules/client/front/web-access/index.html b/modules/client/front/web-access/index.html index 07a2615dd6..6104979948 100644 --- a/modules/client/front/web-access/index.html +++ b/modules/client/front/web-access/index.html @@ -9,6 +9,8 @@ {{::transaction.id}} - {{::transaction.created | date:'dd/MM/yyyy HH:mm'}} + {{::transaction.created | date:'dd/MM/yyyy HH:mm'}} {{::transaction.amount | currency: 'EUR':2}} { const model = models[modelName]; try { - let promises = []; + const promises = []; const targets = lines.map(line => { return line[identifier]; @@ -78,7 +78,7 @@ module.exports = Self => { for (let target of targets) promises.push(model.upsertWithWhere({id: target}, value, myOptions)); - const result = await Promise.all(promises, myOptions); + const result = await Promise.all(promises); if (tx) await tx.commit(); diff --git a/modules/entry/back/methods/entry/getEntry.js b/modules/entry/back/methods/entry/getEntry.js index c14ca800a5..30078c5f93 100644 --- a/modules/entry/back/methods/entry/getEntry.js +++ b/modules/entry/back/methods/entry/getEntry.js @@ -38,7 +38,7 @@ module.exports = Self => { { relation: 'travel', scope: { - fields: ['id', 'name', 'shipped', 'landed', 'agencyFk', 'warehouseOutFk', 'warehouseInFk'], + fields: ['id', 'name', 'shipped', 'landed', 'agencyFk', 'warehouseOutFk', 'warehouseInFk', 'isReceived', 'isDelivered'], include: [ { relation: 'agency', diff --git a/modules/entry/back/methods/entry/importBuys.js b/modules/entry/back/methods/entry/importBuys.js index 325fe4d22d..3ed8ac1c7d 100644 --- a/modules/entry/back/methods/entry/importBuys.js +++ b/modules/entry/back/methods/entry/importBuys.js @@ -11,11 +11,6 @@ module.exports = Self => { description: 'The entry id', http: {source: 'path'} }, - { - arg: 'options', - type: 'object', - description: 'Callback options', - }, { arg: 'ref', type: 'string', @@ -28,11 +23,11 @@ module.exports = Self => { }, { arg: 'buys', - type: ['Object'], + type: ['object'], description: 'The buys', }], returns: { - type: ['Object'], + type: ['object'], root: true }, http: { @@ -41,23 +36,27 @@ module.exports = Self => { } }); - Self.importBuys = async(ctx, id, options = {}) => { + Self.importBuys = async(ctx, id, options) => { const conn = Self.dataSource.connector; const args = ctx.args; const models = Self.app.models; let tx; + const myOptions = {}; - if (!options.transaction) { + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { tx = await Self.beginTransaction({}); - options.transaction = tx; + myOptions.transaction = tx; } try { - const entry = await models.Entry.findById(id, null, options); + const entry = await models.Entry.findById(id, null, myOptions); await entry.updateAttributes({ observation: args.observation, ref: args.ref - }, options); + }, myOptions); const buys = []; for (let buy of args.buys) { @@ -71,9 +70,16 @@ module.exports = Self => { buyingValue: buy.buyingValue, packageFk: buy.packageFk }); + + await models.ItemMatchProperties.upsert({ + itemFk: buy.itemFk, + name: buy.description, + producer: buy.companyName, + size: buy.size + }, myOptions); } - const createdBuys = await models.Buy.create(buys, options); + const createdBuys = await models.Buy.create(buys, myOptions); const buyIds = createdBuys.map(buy => buy.id); const stmts = []; @@ -90,7 +96,7 @@ module.exports = Self => { stmts.push('CALL buy_recalcPrices()'); const sql = ParameterizedSQL.join(stmts, ';'); - await conn.executeStmt(sql, options); + await conn.executeStmt(sql, myOptions); if (tx) await tx.commit(); } catch (e) { if (tx) await tx.rollback(); diff --git a/modules/entry/back/methods/entry/importBuysPreview.js b/modules/entry/back/methods/entry/importBuysPreview.js index 9ba2b58ed8..790d33364c 100644 --- a/modules/entry/back/methods/entry/importBuysPreview.js +++ b/modules/entry/back/methods/entry/importBuysPreview.js @@ -37,7 +37,21 @@ module.exports = Self => { where: {volume: {gte: buy.volume}}, order: 'volume ASC' }, myOptions); - buy.packageFk = packaging.id; + + if (packaging) + buy.packageFk = packaging.id; + + const reference = await models.ItemMatchProperties.findOne({ + fields: ['itemFk'], + where: { + name: buy.description, + producer: buy.companyName, + size: buy.size + } + }, myOptions); + + if (reference) + buy.itemFk = reference.itemFk; } return buys; diff --git a/modules/entry/back/methods/entry/latestBuysFilter.js b/modules/entry/back/methods/entry/latestBuysFilter.js index d59e34e643..cbf9e3b6a4 100644 --- a/modules/entry/back/methods/entry/latestBuysFilter.js +++ b/modules/entry/back/methods/entry/latestBuysFilter.js @@ -115,7 +115,6 @@ module.exports = Self => { const stmts = []; let stmt; - stmts.push('CALL cache.last_buy_refresh(FALSE)'); stmts.push('CALL cache.visible_refresh(@calc_id, FALSE, 1)'); stmt = new ParameterizedSQL(` diff --git a/modules/entry/back/model-config.json b/modules/entry/back/model-config.json index eddef9c410..ad5a9063ec 100644 --- a/modules/entry/back/model-config.json +++ b/modules/entry/back/model-config.json @@ -5,6 +5,9 @@ "Buy": { "dataSource": "vn" }, + "ItemMatchProperties": { + "dataSource": "vn" + }, "EntryLog": { "dataSource": "vn" }, diff --git a/modules/entry/back/models/buy-import-reference.json b/modules/entry/back/models/buy-import-reference.json new file mode 100644 index 0000000000..ab64dad73e --- /dev/null +++ b/modules/entry/back/models/buy-import-reference.json @@ -0,0 +1,32 @@ +{ + "name": "ItemMatchProperties", + "base": "VnModel", + "options": { + "mysql": { + "table": "itemMatchProperties" + } + }, + "properties": { + "itemFk": { + "type": "number", + "id": true, + "description": "Identifier" + }, + "name": { + "type": "string" + }, + "producer": { + "type": "string" + }, + "size": { + "type": "string" + } + }, + "relations": { + "item": { + "type": "belongsTo", + "model": "Item", + "foreignKey": "itemFk" + } + } +} \ No newline at end of file diff --git a/modules/entry/front/buy/import/index.html b/modules/entry/front/buy/import/index.html index 74b6c708ad..ada92fcc32 100644 --- a/modules/entry/front/buy/import/index.html +++ b/modules/entry/front/buy/import/index.html @@ -9,20 +9,6 @@ class="vn-ma-md">
- - - - - - - - + + + + + + + + @@ -51,7 +51,6 @@ - @@ -60,7 +59,7 @@ {{::id}} - {{::name}} + + + + - - + -
Grouping Buying value BoxVolume
{{::buy.description | dashIfEmpty}} {{::buy.size | dashIfEmpty}} - - {{::buy.packing | dashIfEmpty}} - - - - {{::buy.grouping | dashIfEmpty}} - - + {{::buy.packing | dashIfEmpty}}{{::buy.grouping | dashIfEmpty}} {{::buy.buyingValue | currency: 'EUR':2}} {{::buy.volume | number}}
@@ -110,7 +107,95 @@ label="Cancel" ui-sref="entry.card.buy.index"> -
+ + + + + + + + + + + + + + + + + + + + + + + + + + ID + Item + Size + Producer + Color + + + + + + + {{::item.id}} + + + {{::item.name}} + {{::item.size}} + {{::item.producer.name}} + {{::item.ink.name}} + + + + + + + + \ No newline at end of file diff --git a/modules/entry/front/buy/import/index.js b/modules/entry/front/buy/import/index.js index b5ff92a893..2f13b27460 100644 --- a/modules/entry/front/buy/import/index.js +++ b/modules/entry/front/buy/import/index.js @@ -29,6 +29,7 @@ class Controller extends Section { this.$.$applyAsync(() => { this.import.observation = invoice.tx_awb; + const companyName = invoice.tx_company; const boxes = invoice.boxes; const buys = []; for (let box of boxes) { @@ -37,11 +38,12 @@ class Controller extends Section { const packing = product.nu_stems_bunch * product.nu_bunches; buys.push({ description: product.nm_product, + companyName: companyName, size: product.nu_length, packing: packing, grouping: product.nu_stems_bunch, buyingValue: parseFloat(product.mny_rate_stem), - volume: boxVolume + volume: boxVolume, }); } } @@ -86,6 +88,59 @@ class Controller extends Section { ? {id: $search} : {name: {like: '%' + $search + '%'}}; } + + showFilterDialog(buy) { + this.activeBuy = buy; + this.itemFilterParams = {}; + this.itemFilter = { + include: [ + { + relation: 'producer', + scope: { + fields: ['name'] + } + }, + { + relation: 'ink', + scope: { + fields: ['name'] + } + } + ] + }; + + this.$.filterDialog.show(); + } + + selectItem(id) { + this.activeBuy['itemFk'] = id; + this.$.filterDialog.hide(); + } + + filter() { + const filter = this.itemFilter; + const params = this.itemFilterParams; + const where = {}; + + for (let key in params) { + const value = params[key]; + if (!value) continue; + + switch (key) { + case 'name': + where[key] = {like: `%${value}%`}; + break; + case 'producerFk': + case 'typeFk': + case 'size': + case 'ink': + where[key] = value; + } + } + + filter.where = where; + this.$.itemsModel.applyFilter(filter); + } } Controller.$inject = ['$element', '$scope']; diff --git a/modules/entry/front/buy/import/style.scss b/modules/entry/front/buy/import/style.scss index dba0696164..8426d41699 100644 --- a/modules/entry/front/buy/import/style.scss +++ b/modules/entry/front/buy/import/style.scss @@ -2,4 +2,10 @@ vn-entry-buy-import { .vn-table > tbody td:nth-child(1) { width: 250px } +} + +.itemFilter { + vn-table.scrollable { + height: 500px + } } \ No newline at end of file diff --git a/modules/entry/front/buy/index/index.html b/modules/entry/front/buy/index/index.html index 5a8c10ecd4..1e1a7ecd26 100644 --- a/modules/entry/front/buy/index/index.html +++ b/modules/entry/front/buy/index/index.html @@ -64,7 +64,7 @@ { $httpBackend = _$httpBackend_; let $element = $compile(' { diff --git a/modules/entry/front/buy/index/locale/es.yml b/modules/entry/front/buy/index/locale/es.yml index bd10b39aaa..0a1ecf5b11 100644 --- a/modules/entry/front/buy/index/locale/es.yml +++ b/modules/entry/front/buy/index/locale/es.yml @@ -1,2 +1,3 @@ Buys: Compras -Delete buy(s): Eliminar compra(s) \ No newline at end of file +Delete buy(s): Eliminar compra(s) +Add buy: Añadir compra \ No newline at end of file diff --git a/modules/entry/front/buy/locale/es.yml b/modules/entry/front/buy/locale/es.yml index c775877581..55828a3c6a 100644 --- a/modules/entry/front/buy/locale/es.yml +++ b/modules/entry/front/buy/locale/es.yml @@ -3,4 +3,6 @@ Observation: Observación Box: Embalaje Import buys: Importar compras Some of the imported buys doesn't have an item: Algunas de las compras importadas no tienen un artículo -JSON files only: Solo ficheros JSON \ No newline at end of file +JSON files only: Solo ficheros JSON +Filter item: Filtrar artículo +Filter...: Filtrar... \ No newline at end of file diff --git a/modules/entry/front/summary/index.html b/modules/entry/front/summary/index.html index 3f91ddc26c..60467ae888 100644 --- a/modules/entry/front/summary/index.html +++ b/modules/entry/front/summary/index.html @@ -34,12 +34,8 @@ - - - {{$ctrl.entryData.travel.agency.name}} - + @@ -47,12 +43,22 @@ + + + + @@ -174,7 +180,4 @@ vn-id="item-descriptor" warehouse-fk="$ctrl.vnConfig.warehouseFk"> - - diff --git a/modules/invoiceIn/back/methods/invoice-in/clone.js b/modules/invoiceIn/back/methods/invoice-in/clone.js new file mode 100644 index 0000000000..18df53a95f --- /dev/null +++ b/modules/invoiceIn/back/methods/invoice-in/clone.js @@ -0,0 +1,105 @@ +module.exports = Self => { + Self.remoteMethodCtx('clone', { + description: 'Clone the invoiceIn and as many invoiceInTax and invoiceInDueDay referencing it', + accessType: 'WRITE', + accepts: { + arg: 'id', + type: 'number', + required: true, + description: 'The invoiceIn id', + http: {source: 'path'} + }, + returns: { + type: 'object', + root: true + }, + http: { + path: '/:id/clone', + verb: 'POST' + } + }); + + Self.clone = async(ctx, id, options) => { + const models = Self.app.models; + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const sourceInvoiceIn = await Self.findById(id, { + fields: [ + 'id', + 'serial', + 'supplierRef', + 'supplierFk', + 'issued', + 'currencyFk', + 'companyFk', + 'isVatDeductible', + 'withholdingSageFk', + 'deductibleExpenseFk', + ] + }, myOptions); + const sourceInvoiceInTax = await models.InvoiceInTax.find({where: {invoiceInFk: id}}, myOptions); + const sourceInvoiceInDueDay = await models.InvoiceInDueDay.find({where: {invoiceInFk: id}}, myOptions); + + const issued = new Date(sourceInvoiceIn.issued); + issued.setMonth(issued.getMonth() + 1); + const clonedRef = sourceInvoiceIn.supplierRef + '(2)'; + + const clone = await models.InvoiceIn.create({ + serial: sourceInvoiceIn.serial, + supplierRef: clonedRef, + supplierFk: sourceInvoiceIn.supplierFk, + issued: issued, + currencyFk: sourceInvoiceIn.currencyFk, + companyFk: sourceInvoiceIn.companyFk, + isVatDeductible: sourceInvoiceIn.isVatDeductible, + withholdingSageFk: sourceInvoiceIn.withholdingSageFk, + deductibleExpenseFk: sourceInvoiceIn.deductibleExpenseFk, + }, myOptions); + + const promises = []; + + for (let tax of sourceInvoiceInTax) { + promises.push(models.InvoiceInTax.create({ + invoiceInFk: clone.id, + taxableBase: tax.taxableBase, + expenseFk: tax.expenseFk, + foreignValue: tax.foreignValue, + taxTypeSageFk: tax.taxTypeSageFk, + transactionTypeSageFk: tax.transactionTypeSageFk + }, myOptions)); + } + + for (let dueDay of sourceInvoiceInDueDay) { + const dueDated = dueDay.dueDated; + dueDated.setMonth(dueDated.getMonth() + 1); + + promises.push(models.InvoiceInDueDay.create({ + invoiceInFk: clone.id, + dueDated: dueDated, + bankFk: dueDay.bankFk, + amount: dueDay.amount, + foreignValue: dueDated.foreignValue, + }, myOptions)); + } + + await Promise.all(promises); + + if (tx) await tx.commit(); + + return clone; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/invoiceIn/back/methods/invoice-in/filter.js b/modules/invoiceIn/back/methods/invoice-in/filter.js index 3b9330eb93..e2e759fb8b 100644 --- a/modules/invoiceIn/back/methods/invoice-in/filter.js +++ b/modules/invoiceIn/back/methods/invoice-in/filter.js @@ -54,7 +54,8 @@ module.exports = Self => { arg: 'from', type: 'date', description: `The from date filter` - }, { + }, + { arg: 'to', type: 'date', description: `The to date filter` @@ -90,16 +91,21 @@ module.exports = Self => { } }); - Self.filter = async(ctx, filter) => { + Self.filter = async(ctx, filter, options) => { const conn = Self.dataSource.connector; const args = ctx.args; + let myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + if (args && args.to) { const dateTo = args.to; dateTo.setHours(23, 59, 0, 0); } - let where = buildFilter(ctx.args, (param, value) => { + const where = buildFilter(ctx.args, (param, value) => { switch (param) { case 'search': return /^\d+$/.test(value) @@ -127,10 +133,9 @@ module.exports = Self => { filter = mergeFilters(filter, {where}); - let stmts = []; - let stmt; + const stmts = []; - stmt = new ParameterizedSQL( + const stmt = new ParameterizedSQL( `SELECT ii.id, ii.serialNumber, @@ -169,10 +174,11 @@ module.exports = Self => { stmt.merge(conn.makePagination(filter)); - let itemsIndex = stmts.push(stmt) - 1; + const itemsIndex = stmts.push(stmt) - 1; + + const sql = ParameterizedSQL.join(stmts, ';'); + const result = await conn.executeStmt(sql, myOptions); - let sql = ParameterizedSQL.join(stmts, ';'); - let result = await conn.executeStmt(sql); return itemsIndex === 0 ? result : result[itemsIndex]; }; }; diff --git a/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js b/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js new file mode 100644 index 0000000000..e0f191962e --- /dev/null +++ b/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js @@ -0,0 +1,36 @@ +const models = require('vn-loopback/server/server').models; + +describe('invoiceIn clone()', () => { + it('should return the cloned invoiceIn and also clone invoiceInDueDays and invoiceInTaxes if there are any referencing the invoiceIn', async() => { + const userId = 1; + const ctx = { + req: { + + accessToken: {userId: userId}, + headers: {origin: 'http://localhost:5000'}, + } + }; + + const tx = await models.InvoiceIn.beginTransaction({}); + const options = {transaction: tx}; + + try { + const clone = await models.InvoiceIn.clone(ctx, 1, options); + + expect(clone.supplierRef).toEqual('1234(2)'); + + const invoiceInTaxes = await models.InvoiceInTax.find({where: {invoiceInFk: clone.id}}, options); + + expect(invoiceInTaxes.length).toEqual(2); + + const invoiceInDueDays = await models.InvoiceInDueDay.find({where: {invoiceInFk: clone.id}}, options); + + expect(invoiceInDueDays.length).toEqual(2); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); +}); 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 13b54527b8..401b8dab07 100644 --- a/modules/invoiceIn/back/methods/invoice-in/specs/filter.spec.js +++ b/modules/invoiceIn/back/methods/invoice-in/specs/filter.spec.js @@ -1,111 +1,191 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('InvoiceIn filter()', () => { it('should return the invoice in matching supplier name', async() => { - let ctx = { - args: { - search: 'Plants SL', - } - }; + const tx = await models.InvoiceIn.beginTransaction({}); + const options = {transaction: tx}; - let result = await app.models.InvoiceIn.filter(ctx); + try { + const ctx = { + args: { + search: 'Plants SL', + } + }; - expect(result.length).toEqual(5); - expect(result[0].supplierName).toEqual('Plants SL'); + const result = await models.InvoiceIn.filter(ctx, {}, options); + + expect(result.length).toEqual(5); + expect(result[0].supplierName).toEqual('Plants SL'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the invoice in matching supplier reference', async() => { - let ctx = { - args: { - supplierRef: '1241', - } - }; + const tx = await models.InvoiceIn.beginTransaction({}); + const options = {transaction: tx}; - let result = await app.models.InvoiceIn.filter(ctx); + try { + const ctx = { + args: { + supplierRef: '1241', + } + }; - expect(result.length).toEqual(1); - expect(result[0].supplierRef).toEqual('1241'); + const result = await models.InvoiceIn.filter(ctx, {}, options); + + expect(result.length).toEqual(1); + expect(result[0].supplierRef).toEqual('1241'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the invoice in matching the serial number', async() => { - let ctx = { - args: { - serialNumber: '1002', - } - }; + const tx = await models.InvoiceIn.beginTransaction({}); + const options = {transaction: tx}; - let result = await app.models.InvoiceIn.filter(ctx); + try { + const ctx = { + args: { + serialNumber: '1002', + } + }; - expect(result.length).toEqual(1); - expect(result[0].serialNumber).toEqual(1002); + const result = await models.InvoiceIn.filter(ctx, {}, options); + + expect(result.length).toEqual(1); + expect(result[0].serialNumber).toEqual(1002); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the invoice in matching the account', async() => { - let ctx = { - args: { - account: '4000020002', - } - }; + const tx = await models.InvoiceIn.beginTransaction({}); + const options = {transaction: tx}; - let result = await app.models.InvoiceIn.filter(ctx); + try { + const ctx = { + args: { + account: '4000020002', + } + }; - expect(result.length).toEqual(5); - expect(result[0].account).toEqual('4000020002'); + const result = await models.InvoiceIn.filter(ctx, {}, options); + + expect(result.length).toEqual(5); + expect(result[0].account).toEqual('4000020002'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the invoice in matching the awb code', async() => { - let ctx = { - args: { - awbCode: '07546491432', - } - }; + const tx = await models.InvoiceIn.beginTransaction({}); + const options = {transaction: tx}; - let result = await app.models.InvoiceIn.filter(ctx); - const firstRow = result[0]; + try { + const ctx = { + args: { + awbCode: '07546500856', + } + }; - expect(result.length).toEqual(1); - expect(firstRow.id).toEqual(7); - expect(firstRow.awbCode).toEqual('07546491432'); + const result = await models.InvoiceIn.filter(ctx, {}, options); + const firstRow = result[0]; + + expect(result.length).toEqual(1); + expect(firstRow.id).toEqual(10); + expect(firstRow.awbCode).toEqual('07546500856'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the invoice in matching the amount', async() => { - let ctx = { - args: { - amount: '64.23', - } - }; + const tx = await models.InvoiceIn.beginTransaction({}); + const options = {transaction: tx}; - let result = await app.models.InvoiceIn.filter(ctx); + try { + const ctx = { + args: { + amount: '64.23', + } + }; - expect(result.length).toEqual(1); - expect(result[0].amount).toEqual(64.23); + const result = await models.InvoiceIn.filter(ctx, {}, options); + + expect(result.length).toEqual(1); + expect(result[0].amount).toEqual(64.23); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the invoice in matching "from" and "to"', async() => { - const from = new Date(); - const to = new Date(); - from.setHours(0, 0, 0, 0); - to.setHours(23, 59, 59, 999); - to.setDate(to.getDate() + 1); - const ctx = { - args: {from, to} - }; + const tx = await models.InvoiceIn.beginTransaction({}); + const options = {transaction: tx}; - const result = await app.models.InvoiceIn.filter(ctx); + try { + const from = new Date(); + const to = new Date(); + from.setHours(0, 0, 0, 0); + to.setHours(23, 59, 59, 999); + to.setDate(to.getDate() + 1); + const ctx = { + args: {from, to} + }; - expect(result.length).toEqual(6); + const result = await models.InvoiceIn.filter(ctx, {}, options); + + expect(result.length).toEqual(6); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the booked invoice in', async() => { - let ctx = { - args: { - isBooked: true, - } - }; + const tx = await models.InvoiceIn.beginTransaction({}); + const options = {transaction: tx}; - let result = await app.models.InvoiceIn.filter(ctx); + try { + const ctx = { + args: { + isBooked: true, + } + }; - expect(result.length).toEqual(6); - expect(result[0].isBooked).toBeTruthy(); + const result = await models.InvoiceIn.filter(ctx, {}, options); + + expect(result.length).toEqual(6); + expect(result[0].isBooked).toBeTruthy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/invoiceIn/back/methods/invoice-in/specs/summary.spec.js b/modules/invoiceIn/back/methods/invoice-in/specs/summary.spec.js index ff7a39ef57..656b97d6d1 100644 --- a/modules/invoiceIn/back/methods/invoice-in/specs/summary.spec.js +++ b/modules/invoiceIn/back/methods/invoice-in/specs/summary.spec.js @@ -1,9 +1,20 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('invoiceIn summary()', () => { it('should return a summary object containing data from one invoiceIn', async() => { - const summary = await app.models.InvoiceIn.summary(1); + const tx = await models.InvoiceIn.beginTransaction({}); + const options = {transaction: tx}; - expect(summary.supplierRef).toEqual('1234'); + try { + const summary = await models.InvoiceIn.summary(1, options); + + expect(summary.supplierRef).toEqual('1234'); + expect(summary.totals.totalTaxableBase).toEqual(352.24); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/invoiceIn/back/methods/invoice-in/summary.js b/modules/invoiceIn/back/methods/invoice-in/summary.js index 196a9d0764..f09be4add1 100644 --- a/modules/invoiceIn/back/methods/invoice-in/summary.js +++ b/modules/invoiceIn/back/methods/invoice-in/summary.js @@ -19,7 +19,12 @@ module.exports = Self => { } }); - Self.summary = async id => { + Self.summary = async(id, options) => { + let myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + const filter = { include: [ { @@ -40,6 +45,31 @@ module.exports = Self => { fields: ['withholding'] } }, + { + relation: 'invoiceInTax', + scope: { + fields: [ + 'id', + 'invoiceInFk', + 'taxableBase', + 'expenseFk', + 'taxTypeSageFk', + 'transactionTypeSageFk', + 'foreignValue'], + include: [{ + relation: 'transactionTypeSage', + scope: { + fields: ['transaction'] + } + }, + { + relation: 'taxTypeSage', + scope: { + fields: ['vat'] + } + }] + } + }, { relation: 'expenseDeductible', scope: { @@ -49,12 +79,31 @@ module.exports = Self => { { relation: 'currency', scope: { - fields: ['id', 'name'] + fields: ['id', 'code'] + } } ] }; - return Self.app.models.InvoiceIn.findById(id, filter); + let summaryObj = await Self.app.models.InvoiceIn.findById(id, filter, myOptions); + + summaryObj.totals = await getTotals(id); + return summaryObj; }; + + async function getTotals(invoiceInFk) { + return (await Self.rawSql(` + SELECT iit.*, + SUM(iidd.amount) totalDueDay + FROM vn.invoiceIn ii + LEFT JOIN (SELECT SUM(iit.taxableBase) totalTaxableBase, + SUM(iit.taxableBase * (1 + (ti.PorcentajeIva / 100))) totalVat + FROM vn.invoiceInTax iit + LEFT JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk + WHERE iit.invoiceInFk = ?) iit ON TRUE + LEFT JOIN vn.invoiceInDueDay iidd ON iidd.invoiceInFk = ii.id + WHERE + ii.id = ?`, [invoiceInFk, invoiceInFk]))[0]; + } }; diff --git a/modules/invoiceIn/back/model-config.json b/modules/invoiceIn/back/model-config.json index 467d6f7f93..f0745f53b2 100644 --- a/modules/invoiceIn/back/model-config.json +++ b/modules/invoiceIn/back/model-config.json @@ -2,6 +2,9 @@ "InvoiceIn": { "dataSource": "vn" }, + "InvoiceInTax": { + "dataSource": "vn" + }, "InvoiceInDueDay": { "dataSource": "vn" }, diff --git a/modules/invoiceIn/back/models/invoice-in-due-day.json b/modules/invoiceIn/back/models/invoice-in-due-day.json index 6c27dcd6c4..5a66ecd8b0 100644 --- a/modules/invoiceIn/back/models/invoice-in-due-day.json +++ b/modules/invoiceIn/back/models/invoice-in-due-day.json @@ -24,6 +24,9 @@ "amount": { "type": "number" }, + "foreignValue": { + "type": "number" + }, "created": { "type": "date" } diff --git a/modules/invoiceIn/back/models/invoice-in-tax.json b/modules/invoiceIn/back/models/invoice-in-tax.json new file mode 100644 index 0000000000..7890201616 --- /dev/null +++ b/modules/invoiceIn/back/models/invoice-in-tax.json @@ -0,0 +1,58 @@ +{ + "name": "InvoiceInTax", + "base": "Loggable", + "log": { + "model": "InvoiceInLog", + "relation": "invoiceIn" + }, + "options": { + "mysql": { + "table": "invoiceInTax" + } + }, + "properties": { + "id": { + "id": true, + "type": "number", + "description": "Identifier" + }, + "taxableBase": { + "type": "number" + }, + "foreignValue": { + "type": "number" + }, + "expenseFk": { + "type": "number", + "mysql": { + "columnName": "expenceFk" + } + }, + "created": { + "type": "date" + } + + }, + "relations": { + "invoiceIn": { + "type": "belongsTo", + "model": "InvoiceIn", + "foreignKey": "invoiceInFk" + }, + "expense": { + "type": "belongsTo", + "model": "Expense", + "foreignKey": "expenseFk" + }, + "taxTypeSage": { + "type": "belongsTo", + "model": "SageTaxType", + "foreignKey": "taxTypeSageFk" + }, + "transactionTypeSage": { + "type": "belongsTo", + "model": "SageTransactionType", + "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 7c5b163586..7754890cad 100644 --- a/modules/invoiceIn/back/models/invoice-in.js +++ b/modules/invoiceIn/back/models/invoice-in.js @@ -1,4 +1,5 @@ module.exports = Self => { require('../methods/invoice-in/filter')(Self); require('../methods/invoice-in/summary')(Self); + require('../methods/invoice-in/clone')(Self); }; diff --git a/modules/invoiceIn/back/models/invoice-in.json b/modules/invoiceIn/back/models/invoice-in.json index 468972523f..feb2d9aec0 100644 --- a/modules/invoiceIn/back/models/invoice-in.json +++ b/modules/invoiceIn/back/models/invoice-in.json @@ -12,7 +12,7 @@ "properties": { "id": { "id": true, - "type": "Number", + "type": "number", "description": "Identifier" }, "serialNumber": { @@ -36,6 +36,9 @@ "booked": { "type": "date" }, + "isVatDeductible": { + "type": "boolean" + }, "operated": { "type": "date" }, @@ -61,6 +64,11 @@ "model": "InvoiceInDueDay", "foreignKey": "invoiceInFk" }, + "invoiceInTax": { + "type": "hasMany", + "model": "InvoiceInTax", + "foreignKey": "invoiceInFk" + }, "sageWithholding": { "type": "belongsTo", "model": "SageWithholding", diff --git a/modules/invoiceIn/front/basic-data/index.html b/modules/invoiceIn/front/basic-data/index.html index 037b0657a1..be89e502c2 100644 --- a/modules/invoiceIn/front/basic-data/index.html +++ b/modules/invoiceIn/front/basic-data/index.html @@ -78,7 +78,7 @@ label="Currency" ng-model="$ctrl.invoiceIn.currencyFk" url="Currencies" - show-field="name" + show-field="code" value-field="id" rule> diff --git a/modules/invoiceIn/front/card/index.js b/modules/invoiceIn/front/card/index.js index c669e5f7f8..582c2abb8c 100644 --- a/modules/invoiceIn/front/card/index.js +++ b/modules/invoiceIn/front/card/index.js @@ -13,6 +13,9 @@ class Controller extends ModuleCard { }, { relation: 'company' + }, + { + relation: 'currency' } ]}; diff --git a/modules/invoiceIn/front/descriptor/index.html b/modules/invoiceIn/front/descriptor/index.html index 42a9469136..6829a0daf4 100644 --- a/modules/invoiceIn/front/descriptor/index.html +++ b/modules/invoiceIn/front/descriptor/index.html @@ -8,6 +8,13 @@ translate> Delete Invoice + + Clone Invoice +
@@ -42,8 +49,16 @@
- - + + + diff --git a/modules/invoiceIn/front/descriptor/index.js b/modules/invoiceIn/front/descriptor/index.js index be507e0d4c..a767f4b5c5 100644 --- a/modules/invoiceIn/front/descriptor/index.js +++ b/modules/invoiceIn/front/descriptor/index.js @@ -30,6 +30,12 @@ class Controller extends Descriptor { .then(() => this.vnApp.showSuccess(this.$t('InvoiceIn deleted'))); } + cloneInvoiceIn() { + return this.$http.post(`InvoiceIns/${this.id}/clone`) + .then(res => this.$state.go('invoiceIn.card.summary', {id: res.data.id})) + .then(() => this.vnApp.showSuccess(this.$t('InvoiceIn cloned'))); + } + loadData() { const filter = { include: [ diff --git a/modules/invoiceIn/front/index.js b/modules/invoiceIn/front/index.js index f82228f0ad..033c4ad69c 100644 --- a/modules/invoiceIn/front/index.js +++ b/modules/invoiceIn/front/index.js @@ -8,5 +8,6 @@ import './descriptor'; import './descriptor-popover'; import './summary'; import './basic-data'; +import './tax'; import './create'; import './log'; diff --git a/modules/invoiceIn/front/locale/es.yml b/modules/invoiceIn/front/locale/es.yml index ac432aba8b..f837c834b0 100644 --- a/modules/invoiceIn/front/locale/es.yml +++ b/modules/invoiceIn/front/locale/es.yml @@ -1,5 +1,13 @@ InvoiceIn: Facturas recibidas Search invoices in by reference: Buscar facturas recibidas por referencia Entries list: Listado de entradas +InvoiceIn deleted: Factura eliminada +Remove tax: Quitar iva +Add tax: Añadir iva +Sage tax: Sage iva +Sage transaction: Sage transaccion +Foreign value: Divisa +Due day: Vencimiento Invoice list: Listado de facturas recibidas -InvoiceIn deleted: Factura eliminada \ No newline at end of file +InvoiceIn cloned: Factura clonada + diff --git a/modules/invoiceIn/front/routes.json b/modules/invoiceIn/front/routes.json index d09d8fda09..599e6cb2de 100644 --- a/modules/invoiceIn/front/routes.json +++ b/modules/invoiceIn/front/routes.json @@ -19,6 +19,10 @@ "state": "invoiceIn.card.basicData", "icon": "settings" }, + { + "state": "invoiceIn.card.tax", + "icon": "icon-lines" + }, { "state": "invoiceIn.card.log", "icon": "history" @@ -81,6 +85,16 @@ "administrative" ] }, + { + "url": "/tax", + "state": "invoiceIn.card.tax", + "component": "vn-invoice-in-tax", + "description": "Tax", + "params": { + "invoice-in": "$ctrl.invoiceIn" + }, + "acl": ["administrative"] + }, { "url": "/log", "state": "invoiceIn.card.log", diff --git a/modules/invoiceIn/front/summary/index.html b/modules/invoiceIn/front/summary/index.html index 189a8585de..a4b7b06eee 100644 --- a/modules/invoiceIn/front/summary/index.html +++ b/modules/invoiceIn/front/summary/index.html @@ -18,7 +18,7 @@ - + @@ -45,8 +45,51 @@
+ + Taxable base {{$ctrl.summary.totals.totalTaxableBase | currency: 'EUR':2 | dashIfEmpty}} +

Total {{$ctrl.summary.totals.totalVat | currency: 'EUR':2 | dashIfEmpty}}

+ Due day + {{$ctrl.summary.totals.totalDueDay | currency: 'EUR':2 | dashIfEmpty}} + +
+ + +

+ + Vat + +

+ + + + Expense + Taxable base + Sage vat + Sage transaction + Rate + Foreign value + + + + + {{::tax.expenseFk}} + {{::tax.taxableBase | currency: 'EUR':2}} + {{::tax.taxTypeSage.vat}} + {{::tax.transactionTypeSage.transaction}} + {{::tax.taxRate | percentage}} + {{::tax.foreignValue | currency: 'USD':2}} + + + +
this.summary = res.data); } + + get amountsNotMatch() { + if (!this.summary) return false; + + const total = this.summary.totals; + return total.totalDueDay != total.totalTaxableBase && total.totalDueDay != total.totalVat; + } } ngModule.vnComponent('vnInvoiceInSummary', { diff --git a/modules/invoiceIn/front/summary/index.spec.js b/modules/invoiceIn/front/summary/index.spec.js index 56bfe9f4a4..76f48ac7e3 100644 --- a/modules/invoiceIn/front/summary/index.spec.js +++ b/modules/invoiceIn/front/summary/index.spec.js @@ -25,5 +25,33 @@ describe('InvoiceIn', () => { expect(controller.summary).toEqual('the data you are looking for'); }); }); + + describe('amountsNotMatch getter()', () => { + it('should get false when taxamount match with due day amount', () => { + controller.summary = + { + totals: { + totalDueDay: 'amount match', + totalTaxableBase: 'amount match', + totalVat: 'no care' + } + }; + + expect(controller.amountsNotMatch).toBeFalsy(); + }); + + it('should get true when taxamount does not match with due day amount', () => { + controller.summary = + { + totals: { + totalDueDay: 'amount does not match', + totalTaxableBase: 'neither match', + totalVat: 'no care' + } + }; + + expect(controller.amountsNotMatch).toBeTruthy(); + }); + }); }); }); diff --git a/modules/invoiceIn/front/summary/locale/es.yml b/modules/invoiceIn/front/summary/locale/es.yml index 6f7cefddb7..fbfa5f1403 100644 --- a/modules/invoiceIn/front/summary/locale/es.yml +++ b/modules/invoiceIn/front/summary/locale/es.yml @@ -7,4 +7,5 @@ Booked date: Fecha contable Accounted date: Fecha contable Doc number: Numero documento Sage withholding: Retención sage -Undeductible VAT: Iva no deducible \ No newline at end of file +Undeductible VAT: Iva no deducible +Do not match: No coinciden \ No newline at end of file diff --git a/modules/invoiceIn/front/summary/style.scss b/modules/invoiceIn/front/summary/style.scss index f7ddb2cb77..d1d1918318 100644 --- a/modules/invoiceIn/front/summary/style.scss +++ b/modules/invoiceIn/front/summary/style.scss @@ -1,5 +1,13 @@ -@import "variables"; +@import "./variables"; vn-invoice-in-summary .summary { - width: $width-lg; + max-width: $width-xl; + + .taxes { + border: $border-thin-light; + text-align: right; + padding: 8px; + font-size: 1.2rem; + margin: 3px; + } } \ No newline at end of file diff --git a/modules/invoiceIn/front/tax/index.html b/modules/invoiceIn/front/tax/index.html new file mode 100644 index 0000000000..c495d44d2f --- /dev/null +++ b/modules/invoiceIn/front/tax/index.html @@ -0,0 +1,99 @@ + + + + + + +
+ + + + {{id}}: {{name}} + + + + + {{id}}: {{vat}} + + + {{id}}: {{transaction}} + + + + + + + + + + + + + + + + + + + +
\ No newline at end of file diff --git a/modules/invoiceIn/front/tax/index.js b/modules/invoiceIn/front/tax/index.js new file mode 100644 index 0000000000..53cfc55980 --- /dev/null +++ b/modules/invoiceIn/front/tax/index.js @@ -0,0 +1,40 @@ +import ngModule from '../module'; +import Section from 'salix/components/section'; + +class Controller extends Section { + taxRate(invoiceInTax, taxRateSelection) { + const taxTypeSage = taxRateSelection && taxRateSelection.rate; + const taxableBase = invoiceInTax && invoiceInTax.taxableBase; + + if (taxTypeSage && taxableBase) + return (taxTypeSage / 100) * taxableBase; + + return 0; + } + + add() { + this.$.model.insert({ + invoiceIn: this.$params.id + }); + } + + onSubmit() { + this.$.watcher.check(); + this.$.model.save().then(() => { + this.$.watcher.notifySaved(); + this.$.watcher.updateOriginalData(); + this.card.reload(); + }); + } +} + +ngModule.vnComponent('vnInvoiceInTax', { + template: require('./index.html'), + controller: Controller, + require: { + card: '^vnInvoiceInCard' + }, + bindings: { + invoiceIn: '<' + } +}); diff --git a/modules/invoiceIn/front/tax/index.spec.js b/modules/invoiceIn/front/tax/index.spec.js new file mode 100644 index 0000000000..20d5d40d86 --- /dev/null +++ b/modules/invoiceIn/front/tax/index.spec.js @@ -0,0 +1,59 @@ +import './index.js'; +import watcher from 'core/mocks/watcher'; +import crudModel from 'core/mocks/crud-model'; + +describe('InvoiceIn', () => { + describe('Component tax', () => { + let controller; + let $scope; + let vnApp; + + beforeEach(ngModule('invoiceIn')); + + beforeEach(inject(($componentController, $rootScope, _vnApp_) => { + vnApp = _vnApp_; + jest.spyOn(vnApp, 'showError'); + $scope = $rootScope.$new(); + $scope.model = crudModel; + $scope.watcher = watcher; + + const $element = angular.element(''); + controller = $componentController('vnInvoiceInTax', {$element, $scope}); + controller.invoiceIn = {id: 1}; + })); + + describe('taxRate()', () => { + it('should set tax rate with the Sage tax type value', () => { + const taxRateSelection = { + rate: 21 + }; + const invoiceInTax = { + taxableBase: 200 + }; + + const taxRate = controller.taxRate(invoiceInTax, taxRateSelection); + + expect(taxRate).toEqual(42); + }); + }); + + describe('onSubmit()', () => { + it('should make HTTP POST request to save tax values', () => { + controller.card = {reload: () => {}}; + jest.spyOn($scope.watcher, 'check'); + jest.spyOn($scope.watcher, 'notifySaved'); + jest.spyOn($scope.watcher, 'updateOriginalData'); + jest.spyOn(controller.card, 'reload'); + jest.spyOn($scope.model, 'save'); + + controller.onSubmit(); + + expect($scope.model.save).toHaveBeenCalledWith(); + expect($scope.watcher.updateOriginalData).toHaveBeenCalledWith(); + expect($scope.watcher.check).toHaveBeenCalledWith(); + expect($scope.watcher.notifySaved).toHaveBeenCalledWith(); + expect(controller.card.reload).toHaveBeenCalledWith(); + }); + }); + }); +}); diff --git a/modules/invoiceOut/back/methods/invoiceOut/book.js b/modules/invoiceOut/back/methods/invoiceOut/book.js index af495c1f0a..0371d4f746 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/book.js +++ b/modules/invoiceOut/back/methods/invoiceOut/book.js @@ -20,21 +20,45 @@ module.exports = Self => { } }); - Self.book = async ref => { + Self.book = async(ref, options) => { const models = Self.app.models; - const ticketAddress = await models.Ticket.findOne({ - where: {invoiceOut: ref} - }); - const invoiceCompany = await models.InvoiceOut.findOne({ - where: {ref: ref} - }); - let query = 'SELECT vn.addressTaxArea(?, ?) AS code'; - const [taxArea] = await Self.rawSql(query, [ - ticketAddress.address, - invoiceCompany.company - ]); + let tx; + let myOptions = {}; - query = 'CALL vn.invoiceOutAgain(?, ?)'; - return Self.rawSql(query, [ref, taxArea.code]); + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const ticketAddress = await models.Ticket.findOne({ + where: {invoiceOut: ref} + }, myOptions); + + const invoiceCompany = await models.InvoiceOut.findOne({ + where: {ref: ref} + }, myOptions); + + let query = 'SELECT vn.addressTaxArea(?, ?) AS code'; + + const [taxArea] = await Self.rawSql(query, [ + ticketAddress.address, + invoiceCompany.company + ], myOptions); + + query = 'CALL vn.invoiceOutAgain(?, ?)'; + + const result = Self.rawSql(query, [ref, taxArea.code], myOptions); + + if (tx) await tx.commit(); + + return result; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } }; }; diff --git a/modules/invoiceOut/back/methods/invoiceOut/createManualInvoice.js b/modules/invoiceOut/back/methods/invoiceOut/createManualInvoice.js new file mode 100644 index 0000000000..297afa8e88 --- /dev/null +++ b/modules/invoiceOut/back/methods/invoiceOut/createManualInvoice.js @@ -0,0 +1,184 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('createManualInvoice', { + description: 'Make a manual invoice', + accessType: 'WRITE', + accepts: [ + { + arg: 'clientFk', + type: 'any', + description: 'The invoiceable client id' + }, + { + arg: 'ticketFk', + type: 'any', + description: 'The invoiceable ticket id' + }, + { + arg: 'maxShipped', + type: 'date', + description: 'The maximum shipped date' + }, + { + arg: 'serial', + type: 'string', + description: 'The invoice serial' + }, + { + arg: 'taxArea', + type: 'string', + description: 'The invoice tax area' + }, + { + arg: 'reference', + type: 'string', + description: 'The invoice reference' + } + ], + returns: { + type: 'object', + root: true + }, + http: { + path: '/createManualInvoice', + verb: 'POST' + } + }); + + Self.createManualInvoice = async(ctx, options) => { + const models = Self.app.models; + const args = ctx.args; + + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + const ticketId = args.ticketFk; + let clientId = args.clientFk; + let maxShipped = args.maxShipped; + let companyId; + let newInvoice; + let query; + try { + if (ticketId) { + const ticket = await models.Ticket.findById(ticketId, null, myOptions); + const company = await models.Company.findById(ticket.companyFk, null, myOptions); + + clientId = ticket.clientFk; + maxShipped = ticket.shipped; + companyId = ticket.companyFk; + + // Validates invoiced ticket + 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`); + + // Validates ticket nagative base + const hasNegativeBase = await getNegativeBase(ticketId, 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: clientId, + shipped: {lte: maxShipped} + } + }, myOptions); + companyId = company.companyFk; + } + + // Validate invoiceable client + const isClientInvoiceable = await isInvoiceable(clientId, myOptions); + if (!isClientInvoiceable) + throw new UserError(`This client is not invoiceable`); + + // Can't invoice tickets into future + const tomorrow = new Date(); + tomorrow.setDate(tomorrow.getDate() + 1); + + if (maxShipped >= tomorrow) + throw new UserError(`Can't invoice to future`); + + const maxInvoiceDate = await getMaxIssued(args.serial, companyId, myOptions); + if (new Date() < maxInvoiceDate) + throw new UserError(`Can't invoice to past`); + + if (ticketId) { + query = `CALL invoiceOut_newFromTicket(?, ?, ?, ?, @newInvoiceId)`; + await Self.rawSql(query, [ + ticketId, + args.serial, + args.taxArea, + args.reference + ], myOptions); + } else { + query = `CALL invoiceOut_newFromClient(?, ?, ?, ?, ?, ?, @newInvoiceId)`; + await Self.rawSql(query, [ + clientId, + args.serial, + maxShipped, + companyId, + args.taxArea, + args.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) + await Self.createPdf(ctx, newInvoice.id); + + return newInvoice; + }; + + async function isInvoiceable(clientId, options) { + const models = Self.app.models; + const query = `SELECT (hasToInvoice AND isTaxDataChecked) AS invoiceable + FROM client + WHERE id = ?`; + const [result] = await models.InvoiceOut.rawSql(query, [clientId], options); + + return result.invoiceable; + } + + async function getNegativeBase(ticketId, options) { + const models = Self.app.models; + const query = 'SELECT vn.hasSomeNegativeBase(?) AS base'; + const [result] = await models.InvoiceOut.rawSql(query, [ticketId], options); + + return result.base; + } + + async function getMaxIssued(serial, companyId, 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 || new Date(); + + return maxInvoiceDate; + } +}; diff --git a/modules/invoiceOut/back/methods/invoiceOut/createPdf.js b/modules/invoiceOut/back/methods/invoiceOut/createPdf.js index 9bf4e93a3d..a787e48a1a 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/createPdf.js +++ b/modules/invoiceOut/back/methods/invoiceOut/createPdf.js @@ -1,3 +1,4 @@ +const UserError = require('vn-loopback/util/user-error'); const fs = require('fs-extra'); const got = require('got'); const path = require('path'); @@ -34,22 +35,22 @@ module.exports = Self => { throw new UserError(`Action not allowed on the test environment`); let tx; - let newOptions = {}; + let myOptions = {}; if (typeof options == 'object') - Object.assign(newOptions, options); + Object.assign(myOptions, options); - if (!newOptions.transaction) { + if (!myOptions.transaction) { tx = await Self.beginTransaction({}); - newOptions.transaction = tx; + myOptions.transaction = tx; } let fileSrc; try { - const invoiceOut = await Self.findById(id, null, newOptions); + const invoiceOut = await Self.findById(id, null, myOptions); await invoiceOut.updateAttributes({ hasPdf: true - }, newOptions); + }, myOptions); const response = got.stream(`${origin}/api/report/invoice`, { query: { @@ -58,24 +59,33 @@ module.exports = Self => { } }); - const invoiceYear = invoiceOut.created.getFullYear().toString(); - const container = await models.InvoiceContainer.container(invoiceYear); + const created = invoiceOut.created; + const year = created.getFullYear().toString(); + const month = created.getMonth().toString(); + const day = created.getDate().toString(); + + const container = await models.InvoiceContainer.container(year); const rootPath = container.client.root; const fileName = `${invoiceOut.ref}.pdf`; - fileSrc = path.join(rootPath, invoiceYear, fileName); + const src = path.join(rootPath, year, month, day); + fileSrc = path.join(src, fileName); + + await fs.mkdir(src, {recursive: true}); + + if (tx) await tx.commit(); const writeStream = fs.createWriteStream(fileSrc); writeStream.on('open', () => { response.pipe(writeStream); }); - writeStream.on('finish', async function() { - writeStream.end(); + return new Promise(resolve => { + writeStream.on('finish', () => { + writeStream.end(); + + resolve(invoiceOut); + }); }); - - if (tx) await tx.commit(); - - return invoiceOut; } catch (e) { if (tx) await tx.rollback(); if (fs.existsSync(fileSrc)) diff --git a/modules/invoiceOut/back/methods/invoiceOut/delete.js b/modules/invoiceOut/back/methods/invoiceOut/delete.js index 127786ded4..d8b9d309b4 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/delete.js +++ b/modules/invoiceOut/back/methods/invoiceOut/delete.js @@ -20,25 +20,38 @@ module.exports = Self => { } }); - Self.delete = async id => { - const transaction = await Self.beginTransaction({}); - try { - let options = {transaction: transaction}; + Self.delete = async(id, options) => { + let tx; + const myOptions = {}; - let invoiceOut = await Self.findById(id); - let tickets = await Self.app.models.Ticket.find({where: {refFk: invoiceOut.ref}}); + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const invoiceOut = await Self.findById(id, {}, myOptions); + const tickets = await Self.app.models.Ticket.find({ + where: {refFk: invoiceOut.ref} + }, myOptions); const promises = []; - tickets.forEach(ticket => { - promises.push(ticket.updateAttribute('refFk', null, options)); - }); + + for (let ticket of tickets) + promises.push(ticket.updateAttribute('refFk', null, myOptions)); await Promise.all(promises); - await invoiceOut.destroy(options); - await transaction.commit(); + + await invoiceOut.destroy(myOptions); + + if (tx) await tx.commit(); + return tickets; } catch (e) { - await transaction.rollback(); + if (tx) await tx.rollback(); throw e; } }; diff --git a/modules/invoiceOut/back/methods/invoiceOut/download.js b/modules/invoiceOut/back/methods/invoiceOut/download.js index 3c9924fc37..9836479823 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/download.js +++ b/modules/invoiceOut/back/methods/invoiceOut/download.js @@ -1,4 +1,5 @@ const fs = require('fs-extra'); +const path = require('path'); module.exports = Self => { Self.remoteMethod('download', { @@ -33,24 +34,31 @@ module.exports = Self => { } }); - Self.download = async function(id) { - let file; - let env = process.env.NODE_ENV; - let [invoice] = await Self.rawSql(`SELECT invoiceOut_getPath(?) path`, [id]); + Self.download = async function(id, options) { + const models = Self.app.models; + const myOptions = {}; - if (env && env != 'development') { - file = { - path: `/var/lib/salix/pdfs/${invoice.path}`, - contentType: 'application/pdf', - name: `${id}.pdf` - }; - } else { - file = { - path: `${process.cwd()}/README.md`, - contentType: 'text/plain', - name: `README.md` - }; - } + if (typeof options == 'object') + Object.assign(myOptions, options); + + const invoiceOut = await models.InvoiceOut.findById(id, null, myOptions); + + const created = invoiceOut.created; + const year = created.getFullYear().toString(); + const month = created.getMonth().toString(); + const day = created.getDate().toString(); + + const container = await models.InvoiceContainer.container(year); + const rootPath = container.client.root; + const src = path.join(rootPath, year, month, day); + const fileName = `${invoiceOut.ref}.pdf`; + const fileSrc = path.join(src, fileName); + + const file = { + path: fileSrc, + contentType: 'application/pdf', + name: `${id}.pdf` + }; await fs.access(file.path); let stream = fs.createReadStream(file.path); diff --git a/modules/invoiceOut/back/methods/invoiceOut/filter.js b/modules/invoiceOut/back/methods/invoiceOut/filter.js index 58e8c52438..3496c92963 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/filter.js +++ b/modules/invoiceOut/back/methods/invoiceOut/filter.js @@ -10,73 +10,73 @@ module.exports = Self => { accepts: [ { arg: 'filter', - type: 'Object', + type: 'object', description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', http: {source: 'query'} }, { arg: 'search', - type: 'String', + type: 'string', description: 'Searchs the invoiceOut by id', http: {source: 'query'} }, { arg: 'clientFk', - type: 'Integer', + type: 'integer', description: 'The client id', http: {source: 'query'} }, { arg: 'fi', - type: 'String', + type: 'string', description: 'The client fiscal id', http: {source: 'query'} }, { arg: 'hasPdf', - type: 'Boolean', + type: 'boolean', description: 'Whether the the invoiceOut has PDF or not', http: {source: 'query'} }, { arg: 'amount', - type: 'Number', + type: 'number', description: 'The amount filter', http: {source: 'query'} }, { arg: 'min', - type: 'Number', + type: 'number', description: 'The minimun amount flter', http: {source: 'query'} }, { arg: 'max', - type: 'Number', + type: 'number', description: 'The maximun amount flter', http: {source: 'query'} }, { arg: 'issued', - type: 'Date', + type: 'date', description: 'The issued date filter', http: {source: 'query'} }, { arg: 'created', - type: 'Date', + type: 'date', description: 'The created date filter', http: {source: 'query'} }, { arg: 'dued', - type: 'Date', + type: 'date', description: 'The due date filter', http: {source: 'query'} } ], returns: { - type: ['Object'], + type: ['object'], root: true }, http: { @@ -85,10 +85,14 @@ module.exports = Self => { } }); - Self.filter = async(ctx, filter) => { - let conn = Self.dataSource.connector; + Self.filter = async(ctx, filter, options) => { + const conn = Self.dataSource.connector; + let myOptions = {}; - let where = buildFilter(ctx.args, (param, value) => { + if (typeof options == 'object') + Object.assign(myOptions, options); + + const where = buildFilter(ctx.args, (param, value) => { switch (param) { case 'search': return {'i.ref': {like: `%${value}%`}}; @@ -115,10 +119,9 @@ module.exports = Self => { filter = mergeFilters(filter, {where}); - let stmts = []; - let stmt; + const stmts = []; - stmt = new ParameterizedSQL( + const stmt = new ParameterizedSQL( `SELECT i.id, i.ref, @@ -136,10 +139,12 @@ module.exports = Self => { ); stmt.merge(conn.makeSuffix(filter)); - let itemsIndex = stmts.push(stmt) - 1; - let sql = ParameterizedSQL.join(stmts, ';'); - let result = await conn.executeStmt(sql); + const itemsIndex = stmts.push(stmt) - 1; + + const sql = ParameterizedSQL.join(stmts, ';'); + const result = await conn.executeStmt(sql, myOptions); + return itemsIndex === 0 ? result : result[itemsIndex]; }; }; diff --git a/modules/invoiceOut/back/methods/invoiceOut/globalInvoicing.js b/modules/invoiceOut/back/methods/invoiceOut/globalInvoicing.js new file mode 100644 index 0000000000..6b901872e5 --- /dev/null +++ b/modules/invoiceOut/back/methods/invoiceOut/globalInvoicing.js @@ -0,0 +1,263 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('globalInvoicing', { + description: 'Make a global invoice', + accessType: 'WRITE', + accepts: [ + { + arg: 'invoiceDate', + type: 'date', + description: 'The invoice date' + }, + { + arg: 'maxShipped', + type: 'date', + description: 'The maximum shipped date' + }, + { + arg: 'fromClientId', + type: 'number', + description: 'The minimum client id' + }, + { + arg: 'toClientId', + type: 'number', + description: 'The maximum client id' + }, + { + arg: 'companyFk', + type: 'number', + description: 'The company id to invoice' + } + ], + returns: { + type: 'object', + root: true + }, + http: { + path: '/globalInvoicing', + verb: 'POST' + } + }); + + Self.globalInvoicing = async(ctx, options) => { + const args = ctx.args; + + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + const invoicesIds = []; + const failedClients = []; + let query; + try { + query = ` + SELECT MAX(issued) issued + FROM vn.invoiceOut io + JOIN vn.time t ON t.dated = io.issued + WHERE io.serial = 'A' + AND t.year = YEAR(?) + AND io.companyFk = ?`; + const [maxIssued] = await Self.rawSql(query, [ + args.invoiceDate, + args.companyFk + ], myOptions); + + const maxSerialDate = maxIssued.issued || args.invoiceDate; + if (args.invoiceDate < maxSerialDate) + args.invoiceDate = maxSerialDate; + + if (args.invoiceDate < args.maxShipped) + args.maxShipped = args.invoiceDate; + + const minShipped = new Date(); + minShipped.setFullYear(minShipped.getFullYear() - 1); + + // Packaging liquidation + const vIsAllInvoiceable = false; + const clientsWithPackaging = await getClientsWithPackaging(ctx, myOptions); + for (let client of clientsWithPackaging) { + await Self.rawSql('CALL packageInvoicing(?, ?, ?, ?, @newTicket)', [ + client.id, + args.invoiceDate, + args.companyFk, + vIsAllInvoiceable + ], myOptions); + } + + const invoiceableClients = await getInvoiceableClients(ctx, myOptions); + + if (!invoiceableClients.length) return; + + for (let client of invoiceableClients) { + try { + if (client.hasToInvoiceByAddress) { + await Self.rawSql('CALL ticketToInvoiceByAddress(?, ?, ?, ?)', [ + minShipped, + args.maxShipped, + client.addressFk, + args.companyFk + ], myOptions); + } else { + await Self.rawSql('CALL invoiceFromClient(?, ?, ?)', [ + args.maxShipped, + client.id, + args.companyFk + ], myOptions); + } + + // Make invoice + const isSpanishCompany = await getIsSpanishCompany(args.companyFk, myOptions); + + // Validates ticket nagative base + const hasAnyNegativeBase = await getNegativeBase(myOptions); + if (hasAnyNegativeBase && isSpanishCompany) + continue; + + query = `SELECT invoiceSerial(?, ?, ?) AS serial`; + const [invoiceSerial] = await Self.rawSql(query, [ + client.id, + args.companyFk, + 'G' + ], myOptions); + const serialLetter = invoiceSerial.serial; + + query = `CALL invoiceOut_new(?, ?, NULL, @invoiceId)`; + await Self.rawSql(query, [ + serialLetter, + args.invoiceDate + ], myOptions); + + const [newInvoice] = await Self.rawSql(`SELECT @invoiceId id`, null, myOptions); + if (newInvoice.id) { + await Self.rawSql('CALL invoiceOutBooking(?)', [newInvoice.id], myOptions); + + invoicesIds.push(newInvoice.id); + } + } catch (e) { + failedClients.push({ + id: client.id, + stacktrace: e + }); + continue; + } + } + + if (failedClients.length > 0) + await notifyFailures(ctx, failedClients, myOptions); + + if (tx) await tx.commit(); + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + + // Print invoices PDF + for (let invoiceId of invoicesIds) + await Self.createPdf(ctx, invoiceId); + + return invoicesIds; + }; + + async function getNegativeBase(options) { + const models = Self.app.models; + const query = 'SELECT hasAnyNegativeBase() AS base'; + const [result] = await models.InvoiceOut.rawSql(query, null, options); + + return result && result.base; + } + + async function getIsSpanishCompany(companyId, options) { + const models = Self.app.models; + const query = `SELECT COUNT(*) AS total + FROM supplier s + JOIN country c ON c.id = s.countryFk + AND c.code = 'ES' + WHERE s.id = ?`; + const [supplierCompany] = await models.InvoiceOut.rawSql(query, [ + companyId + ], options); + + return supplierCompany && supplierCompany.total; + } + + async function getClientsWithPackaging(ctx, options) { + const models = Self.app.models; + const args = ctx.args; + const query = `SELECT DISTINCT clientFk AS id + FROM ticket t + JOIN ticketPackaging tp ON t.id = tp.ticketFk + WHERE t.shipped BETWEEN '2017-11-21' AND ? + AND t.clientFk BETWEEN ? AND ?`; + return models.InvoiceOut.rawSql(query, [ + args.maxShipped, + args.fromClientId, + args.toClientId + ], options); + } + + async function getInvoiceableClients(ctx, options) { + const models = Self.app.models; + const args = ctx.args; + const minShipped = new Date(); + minShipped.setFullYear(minShipped.getFullYear() - 1); + + const query = `SELECT + c.id, + SUM(IFNULL(s.quantity * s.price * (100-s.discount)/100, 0) + IFNULL(ts.quantity * ts.price,0)) AS sumAmount, + c.hasToInvoiceByAddress, + c.email, + c.isToBeMailed, + a.id addressFk + FROM ticket t + LEFT JOIN sale s ON s.ticketFk = t.id + LEFT JOIN ticketService ts ON ts.ticketFk = t.id + JOIN address a ON a.id = t.addressFk + JOIN client c ON c.id = t.clientFk + WHERE ISNULL(t.refFk) AND c.id BETWEEN ? AND ? + AND t.shipped BETWEEN ? AND util.dayEnd(?) + AND t.companyFk = ? AND c.hasToInvoice + AND c.isTaxDataChecked + GROUP BY c.id, IF(c.hasToInvoiceByAddress,a.id,TRUE) HAVING sumAmount > 0`; + + return models.InvoiceOut.rawSql(query, [ + args.fromClientId, + args.toClientId, + minShipped, + args.maxShipped, + args.companyFk + ], options); + } + + async function notifyFailures(ctx, failedClients, options) { + const models = Self.app.models; + const userId = ctx.req.accessToken.userId; + const $t = ctx.req.__; // $translate + + const worker = await models.EmailUser.findById(userId, null, options); + const subject = $t('Global invoicing failed'); + let body = $t(`Wasn't able to invoice the following clients`) + ':

'; + + for (client of failedClients) { + body += `ID: ${client.id} +
${client.stacktrace}

`; + } + + await Self.rawSql(` + INSERT INTO vn.mail (sender, replyTo, sent, subject, body) + VALUES (?, ?, FALSE, ?, ?)`, [ + worker.email, + worker.email, + subject, + body + ], options); + } +}; diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js index 0f0a7badec..ee72f22186 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js @@ -1,32 +1,28 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('invoiceOut book()', () => { const invoiceOutId = 5; - it('should check that invoice out booked is untainted', async() => { - const invoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); - - expect(invoiceOut.booked).toBeDefined(); - expect(invoiceOut.hasPdf).toBeTruthy(); - }); - it('should update the booked property', async() => { - const originalInvoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); - const bookedDate = originalInvoiceOut.booked; - const invoiceOutRef = originalInvoiceOut.ref; + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; - await app.models.InvoiceOut.book(invoiceOutRef); + try { + const originalInvoiceOut = await models.InvoiceOut.findById(invoiceOutId, {}, options); + const bookedDate = originalInvoiceOut.booked; + const invoiceOutRef = originalInvoiceOut.ref; - const updatedInvoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); + await models.InvoiceOut.book(invoiceOutRef, options); - expect(updatedInvoiceOut.booked).not.toEqual(bookedDate); - expect(updatedInvoiceOut.hasPdf).toBeFalsy(); + const updatedInvoiceOut = await models.InvoiceOut.findById(invoiceOutId, {}, options); - // restores - await updatedInvoiceOut.updateAttributes({ - booked: originalInvoiceOut.booked, - hasPdf: originalInvoiceOut.hasPdf, - amount: originalInvoiceOut.amount - }); + expect(updatedInvoiceOut.booked).not.toEqual(bookedDate); + expect(updatedInvoiceOut.hasPdf).toBeFalsy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/createManualInvoice.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/createManualInvoice.spec.js new file mode 100644 index 0000000000..f1c1bbab83 --- /dev/null +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/createManualInvoice.spec.js @@ -0,0 +1,145 @@ +const models = require('vn-loopback/server/server').models; +const LoopBackContext = require('loopback-context'); + +describe('InvoiceOut createManualInvoice()', () => { + const userId = 1; + const ticketId = 16; + const clientId = 1106; + const activeCtx = { + accessToken: {userId: userId}, + }; + const ctx = {req: activeCtx}; + + 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 { + ctx.args = { + ticketFk: ticketId, + serial: 'T', + taxArea: 'CEE' + }; + await models.InvoiceOut.createManualInvoice(ctx, options); + await models.InvoiceOut.createManualInvoice(ctx, options); + + await tx.rollback(); + } 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); + + ctx.args = { + ticketFk: ticketId, + serial: 'T', + taxArea: 'CEE' + }; + await models.InvoiceOut.createManualInvoice(ctx, options); + + await tx.rollback(); + } 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 { + ctx.args = { + clientFk: clientId, + serial: 'T', + taxArea: 'CEE' + }; + await models.InvoiceOut.createManualInvoice(ctx, options); + + 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))); + + 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); + + ctx.args = { + ticketFk: ticketId, + serial: 'T', + taxArea: 'CEE' + }; + await models.InvoiceOut.createManualInvoice(ctx, options); + + await tx.rollback(); + } 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))); + + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; + + try { + ctx.args = { + ticketFk: ticketId, + serial: 'T', + taxArea: 'CEE' + }; + const result = await models.InvoiceOut.createManualInvoice(ctx, options); + + expect(result.id).toEqual(jasmine.any(Number)); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); +}); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/createPdf.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/createPdf.spec.js index 3372411c1c..2f503d11c2 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/createPdf.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/createPdf.spec.js @@ -1,5 +1,6 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; const got = require('got'); +const fs = require('fs-extra'); describe('InvoiceOut createPdf()', () => { const userId = 1; @@ -18,9 +19,27 @@ describe('InvoiceOut createPdf()', () => { on: () => {}, }; spyOn(got, 'stream').and.returnValue(response); + spyOn(models.InvoiceContainer, 'container').and.returnValue({ + client: {root: '/path'} + }); + spyOn(fs, 'mkdir').and.returnValue(true); + spyOn(fs, 'createWriteStream').and.returnValue({ + on: (event, cb) => cb(), + end: () => {} + }); - let result = await app.models.InvoiceOut.createPdf(ctx, invoiceId); + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; - expect(result.hasPdf).toBe(true); + try { + const result = await models.InvoiceOut.createPdf(ctx, invoiceId, options); + + expect(result.hasPdf).toBe(true); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/delete.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/delete.spec.js index cea61eaf90..a662cb318f 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/delete.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/delete.spec.js @@ -1,38 +1,53 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('invoiceOut delete()', () => { const invoiceOutId = 2; - let originalInvoiceOut; - let originalTicket; - const userId = 106; + const userId = 1106; const activeCtx = { accessToken: {userId: userId}, }; it('should check that there is one ticket in the target invoiceOut', async() => { - const invoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); - const tickets = await app.models.Ticket.find({where: {refFk: invoiceOut.ref}}); + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; - expect(tickets.length).toEqual(1); - expect(tickets[0].id).toEqual(3); + try { + const invoiceOut = await models.InvoiceOut.findById(invoiceOutId, {}, options); + const tickets = await models.Ticket.find({where: {refFk: invoiceOut.ref}}, options); + + expect(tickets.length).toEqual(1); + expect(tickets[0].id).toEqual(3); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it(`should delete the target invoiceOut then check the ticket doesn't have a refFk anymore`, async() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - originalInvoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); - await app.models.InvoiceOut.delete(invoiceOutId); - originalTicket = await app.models.Ticket.findById(3); - const deletedInvoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; - expect(deletedInvoiceOut).toBeNull(); - expect(originalTicket.refFk).toBeNull(); + try { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); - // restores - const restoredInvoiceOut = await app.models.InvoiceOut.create(originalInvoiceOut); - await restoredInvoiceOut.updateAttribute('ref', originalInvoiceOut.ref); - await originalTicket.updateAttribute('refFk', restoredInvoiceOut.ref); + await models.InvoiceOut.delete(invoiceOutId, options); + + const originalTicket = await models.Ticket.findById(3, {}, options); + + const deletedInvoiceOut = await models.InvoiceOut.findById(invoiceOutId, {}, options); + + expect(deletedInvoiceOut).toBeNull(); + expect(originalTicket.refFk).toBeNull(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/download.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/download.spec.js index 09289896f8..c053adde16 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/download.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/download.spec.js @@ -1,10 +1,17 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; +const fs = require('fs-extra'); describe('InvoiceOut download()', () => { it('should return the downloaded fine name', async() => { - let result = await app.models.InvoiceOut.download(1); + spyOn(models.InvoiceContainer, 'container').and.returnValue({ + client: {root: '/path'} + }); + spyOn(fs, 'createReadStream').and.returnValue(new Promise(resolve => resolve('streamObject'))); + spyOn(fs, 'access').and.returnValue(true); - expect(result[1]).toEqual('text/plain'); - expect(result[2]).toEqual('filename="README.md"'); + const result = await models.InvoiceOut.download(1); + + expect(result[1]).toEqual('application/pdf'); + expect(result[2]).toEqual('filename="1.pdf"'); }); }); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/filter.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/filter.spec.js index 09f67eced1..2a530048e3 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/filter.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/filter.spec.js @@ -1,109 +1,120 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('InvoiceOut filter()', () => { let today = new Date(); today.setHours(2, 0, 0, 0); it('should return the invoice out matching ref', async() => { - let ctx = { - args: { - search: 'T4444444', - } - }; + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; - let result = await app.models.InvoiceOut.filter(ctx); + try { + const ctx = { + args: { + search: 'T4444444', + } + }; - expect(result.length).toEqual(1); - expect(result[0].ref).toEqual('T4444444'); + const result = await models.InvoiceOut.filter(ctx, {}, options); + + expect(result.length).toEqual(1); + expect(result[0].ref).toEqual('T4444444'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the invoice out matching clientFk', async() => { - let ctx = { - args: { - clientFk: 102, - } - }; + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; - let result = await app.models.InvoiceOut.filter(ctx); + try { + const ctx = { + args: { + clientFk: 1102, + } + }; - expect(result.length).toEqual(1); - expect(result[0].ref).toEqual('T2222222'); + const result = await models.InvoiceOut.filter(ctx, {}, options); + + expect(result.length).toEqual(1); + expect(result[0].ref).toEqual('T2222222'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the invoice out matching hasPdf', async() => { - let ctx = { - args: { - hasPdf: true, - } - }; + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; - let result = await app.models.InvoiceOut.filter(ctx); + try { + const ctx = { + args: { + hasPdf: true, + } + }; - expect(result.length).toEqual(5); + const result = await models.InvoiceOut.filter(ctx, {}, options); + + expect(result.length).toEqual(5); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the invoice out matching amount', async() => { - let ctx = { - args: { - amount: 121.36, - } - }; + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; - let result = await app.models.InvoiceOut.filter(ctx); + try { + const ctx = { + args: { + amount: 121.36, + } + }; - expect(result.length).toEqual(1); - expect(result[0].ref).toEqual('T2222222'); + const result = await models.InvoiceOut.filter(ctx, {}, options); + + expect(result.length).toEqual(1); + expect(result[0].ref).toEqual('T2222222'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the invoice out matching min and max', async() => { - let ctx = { - args: { - min: 0, - max: 100, - } - }; + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; - let result = await app.models.InvoiceOut.filter(ctx); + try { + let ctx = { + args: { + min: 0, + max: 100, + } + }; - expect(result.length).toEqual(3); - }); + let result = await models.InvoiceOut.filter(ctx, {}, options); - // #1428 cuadrar formato de horas - xit('should return the invoice out matching issued', async() => { - let ctx = { - args: { - issued: today, - } - }; + expect(result.length).toEqual(3); - let result = await app.models.InvoiceOut.filter(ctx); - - expect(result.length).toEqual(1); - }); - - // #1428 cuadrar formato de horas - xit('should return the invoice out matching created', async() => { - let ctx = { - args: { - created: today, - } - }; - - let result = await app.models.InvoiceOut.filter(ctx); - - expect(result.length).toEqual(5); - }); - - // #1428 cuadrar formato de horas - xit('should return the invoice out matching dued', async() => { - let ctx = { - args: { - dued: today - } - }; - - let result = await app.models.InvoiceOut.filter(ctx); - - expect(result.length).toEqual(1); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/getTickets.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/getTickets.spec.js index 0872ff85f2..67be3dface 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/getTickets.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/getTickets.spec.js @@ -1,10 +1,20 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('entry getTickets()', () => { const invoiceOutId = 4; it('should get the ticket of an invoiceOut', async() => { - const result = await app.models.InvoiceOut.getTickets(invoiceOutId); + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; - expect(result.length).toEqual(1); + try { + const result = await models.InvoiceOut.getTickets(invoiceOutId, {}, options); + + expect(result.length).toEqual(1); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/globalInvoicing.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/globalInvoicing.spec.js new file mode 100644 index 0000000000..e0ed6c91cf --- /dev/null +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/globalInvoicing.spec.js @@ -0,0 +1,40 @@ +const models = require('vn-loopback/server/server').models; + +describe('InvoiceOut globalInvoicing()', () => { + const userId = 1; + const companyFk = 442; + const clientId = 1101; + const invoicedTicketId = 8; + const invoiceSerial = 'A'; + const activeCtx = { + accessToken: {userId: userId}, + }; + const ctx = {req: activeCtx}; + + it('should make a global invoicing', async() => { + spyOn(models.InvoiceOut, 'createPdf').and.returnValue(new Promise(resolve => resolve(true))); + + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; + + try { + ctx.args = { + invoiceDate: new Date(), + maxShipped: new Date(), + fromClientId: clientId, + toClientId: clientId, + companyFk: companyFk + }; + const result = await models.InvoiceOut.globalInvoicing(ctx, options); + const ticket = await models.Ticket.findById(invoicedTicketId, null, options); + + expect(result.length).toBeGreaterThan(0); + expect(ticket.refFk).toContain(invoiceSerial); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); +}); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/summary.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/summary.spec.js index 1155977174..2db4077c35 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/summary.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/summary.spec.js @@ -1,25 +1,55 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('invoiceOut summary()', () => { it('should return a summary object containing data from one invoiceOut', async() => { - const result = await app.models.InvoiceOut.summary(1); + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; - expect(result.invoiceOut.id).toEqual(1); + try { + const result = await models.InvoiceOut.summary(1, options); + + expect(result.invoiceOut.id).toEqual(1); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it(`should return a summary object containing it's supplier country`, async() => { - const summary = await app.models.InvoiceOut.summary(1); - const supplier = summary.invoiceOut.supplier(); + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; - expect(summary.invoiceOut.ref).toEqual('T1111111'); - expect(supplier.id).toEqual(442); - expect(supplier.countryFk).toEqual(1); + try { + const summary = await models.InvoiceOut.summary(1, options); + const supplier = summary.invoiceOut.supplier(); + + expect(summary.invoiceOut.ref).toEqual('T1111111'); + expect(supplier.id).toEqual(442); + expect(supplier.countryFk).toEqual(1); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it(`should return a summary object containing idata from it's tax types`, async() => { - const summary = await app.models.InvoiceOut.summary(1); + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; - expect(summary.invoiceOut.ref).toEqual('T1111111'); - expect(summary.invoiceOut.taxesBreakdown.length).toEqual(2); + try { + const summary = await models.InvoiceOut.summary(1, options); + + expect(summary.invoiceOut.ref).toEqual('T1111111'); + expect(summary.invoiceOut.taxesBreakdown.length).toEqual(2); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/invoiceOut/back/methods/invoiceOut/summary.js b/modules/invoiceOut/back/methods/invoiceOut/summary.js index 0dd82fd0d8..5a87dd4a30 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/summary.js +++ b/modules/invoiceOut/back/methods/invoiceOut/summary.js @@ -19,8 +19,12 @@ module.exports = Self => { } }); - Self.summary = async id => { + Self.summary = async(id, options) => { let summary = {}; + let myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); const filter = { fields: [ @@ -58,14 +62,14 @@ module.exports = Self => { ] }; - summary.invoiceOut = await Self.app.models.InvoiceOut.findOne(filter); + summary.invoiceOut = await Self.app.models.InvoiceOut.findOne(filter, myOptions); const invoiceOutTaxes = await Self.rawSql(` SELECT iot.* , pgc.*, IF(pe.equFk IS NULL, taxableBase, 0) AS Base, pgc.rate / 100 as vatPercent FROM vn.invoiceOutTax iot JOIN vn.pgc ON pgc.code = iot.pgcFk LEFT JOIN vn.pgcEqu pe ON pe.equFk = pgc.code - WHERE invoiceOutFk = ?`, [summary.invoiceOut.id]); + WHERE invoiceOutFk = ?`, [summary.invoiceOut.id], myOptions); summary.invoiceOut.taxesBreakdown = invoiceOutTaxes; diff --git a/modules/invoiceOut/back/model-config.json b/modules/invoiceOut/back/model-config.json index e144ce80e5..d52f794775 100644 --- a/modules/invoiceOut/back/model-config.json +++ b/modules/invoiceOut/back/model-config.json @@ -2,7 +2,25 @@ "InvoiceOut": { "dataSource": "vn" }, + "InvoiceOutSerial": { + "dataSource": "vn" + }, "InvoiceContainer": { "dataSource": "invoiceStorage" + }, + "TaxArea": { + "dataSource": "vn" + }, + "TaxClass": { + "dataSource": "vn" + }, + "TaxClassCode": { + "dataSource": "vn" + }, + "TaxCode": { + "dataSource": "vn" + }, + "TaxType": { + "dataSource": "vn" } } diff --git a/modules/invoiceOut/back/models/invoice-out-serial.json b/modules/invoiceOut/back/models/invoice-out-serial.json new file mode 100644 index 0000000000..912269fd79 --- /dev/null +++ b/modules/invoiceOut/back/models/invoice-out-serial.json @@ -0,0 +1,38 @@ +{ + "name": "InvoiceOutSerial", + "base": "VnModel", + "options": { + "mysql": { + "table": "invoiceOutSerial" + } + }, + "properties": { + "code": { + "type": "string", + "id": true, + "description": "Identifier" + }, + "description": { + "type": "string" + }, + "isTaxed": { + "type": "boolean" + }, + "isCEE": { + "type": "boolean" + } + }, + "relations": { + "taxArea": { + "type": "belongsTo", + "model": "TaxArea", + "foreignKey": "taxAreaFk" + } + }, + "acls": [{ + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }] +} \ No newline at end of file diff --git a/modules/invoiceOut/back/models/invoiceOut.js b/modules/invoiceOut/back/models/invoice-out.js similarity index 76% rename from modules/invoiceOut/back/models/invoiceOut.js rename to modules/invoiceOut/back/models/invoice-out.js index 7c6503d8e9..3b2822ada1 100644 --- a/modules/invoiceOut/back/models/invoiceOut.js +++ b/modules/invoiceOut/back/models/invoice-out.js @@ -6,4 +6,6 @@ module.exports = Self => { require('../methods/invoiceOut/delete')(Self); require('../methods/invoiceOut/book')(Self); require('../methods/invoiceOut/createPdf')(Self); + require('../methods/invoiceOut/createManualInvoice')(Self); + require('../methods/invoiceOut/globalInvoicing')(Self); }; diff --git a/modules/invoiceOut/back/models/invoiceOut.json b/modules/invoiceOut/back/models/invoice-out.json similarity index 100% rename from modules/invoiceOut/back/models/invoiceOut.json rename to modules/invoiceOut/back/models/invoice-out.json diff --git a/modules/invoiceOut/back/models/tax-area.json b/modules/invoiceOut/back/models/tax-area.json new file mode 100644 index 0000000000..0aa00d194a --- /dev/null +++ b/modules/invoiceOut/back/models/tax-area.json @@ -0,0 +1,22 @@ +{ + "name": "TaxArea", + "base": "VnModel", + "options": { + "mysql": { + "table": "taxArea" + } + }, + "properties": { + "code": { + "type": "string", + "id": true, + "description": "Identifier" + } + }, + "acls": [{ + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }] +} \ No newline at end of file diff --git a/modules/item/back/models/tax-class-code.json b/modules/invoiceOut/back/models/tax-class-code.json similarity index 100% rename from modules/item/back/models/tax-class-code.json rename to modules/invoiceOut/back/models/tax-class-code.json diff --git a/modules/item/back/models/tax-class.json b/modules/invoiceOut/back/models/tax-class.json similarity index 100% rename from modules/item/back/models/tax-class.json rename to modules/invoiceOut/back/models/tax-class.json diff --git a/modules/item/back/models/tax-code.json b/modules/invoiceOut/back/models/tax-code.json similarity index 100% rename from modules/item/back/models/tax-code.json rename to modules/invoiceOut/back/models/tax-code.json diff --git a/modules/item/back/models/tax-type.json b/modules/invoiceOut/back/models/tax-type.json similarity index 100% rename from modules/item/back/models/tax-type.json rename to modules/invoiceOut/back/models/tax-type.json diff --git a/modules/invoiceOut/front/card/index.js b/modules/invoiceOut/front/card/index.js index f718f22aeb..093fcdf669 100644 --- a/modules/invoiceOut/front/card/index.js +++ b/modules/invoiceOut/front/card/index.js @@ -21,7 +21,7 @@ class Controller extends ModuleCard { }, { relation: 'client', scope: { - fields: ['id', 'socialName', 'name'] + fields: ['id', 'socialName', 'name', 'email'] } } ] diff --git a/modules/invoiceOut/front/descriptor/index.html b/modules/invoiceOut/front/descriptor/index.html index b4c76d8085..7e8d6b8d9e 100644 --- a/modules/invoiceOut/front/descriptor/index.html +++ b/modules/invoiceOut/front/descriptor/index.html @@ -9,6 +9,12 @@ translate> Show invoice PDF + + Send invoice PDF + + + + + \ No newline at end of file diff --git a/modules/invoiceOut/front/descriptor/index.js b/modules/invoiceOut/front/descriptor/index.js index 3e859478d0..e6305db93b 100644 --- a/modules/invoiceOut/front/descriptor/index.js +++ b/modules/invoiceOut/front/descriptor/index.js @@ -59,6 +59,14 @@ class Controller extends Descriptor { return this.getData(`InvoiceOuts/${this.id}`, {filter}) .then(res => this.entity = res.data); } + + sendInvoice() { + return this.vnEmail.send('invoice', { + recipientId: this.invoiceOut.client.id, + recipient: this.invoiceOut.client.email, + invoiceId: this.id + }); + } } ngModule.vnComponent('vnInvoiceOutDescriptor', { diff --git a/modules/invoiceOut/front/descriptor/locale/es.yml b/modules/invoiceOut/front/descriptor/locale/es.yml index dd67660ee4..ec9cd33100 100644 --- a/modules/invoiceOut/front/descriptor/locale/es.yml +++ b/modules/invoiceOut/front/descriptor/locale/es.yml @@ -3,9 +3,12 @@ Volume: Volumen Client card: Ficha del cliente Invoice ticket list: Listado de tickets de la factura Show invoice PDF: Ver factura en PDF +Send invoice PDF: Enviar factura en PDF Delete Invoice: Eliminar factura +Clone Invoice: Clonar factura InvoiceOut deleted: Factura eliminada Are you sure you want to delete this invoice?: Estas seguro de eliminar esta factura? +Are you sure you want to clone this invoice?: Estas seguro de clonar esta factura? Book invoice: Asentar factura InvoiceOut booked: Factura asentada Are you sure you want to book this invoice?: Estas seguro de querer asentar esta factura? diff --git a/modules/invoiceOut/front/index.js b/modules/invoiceOut/front/index.js index 9843e188b5..3bb6d54d2a 100644 --- a/modules/invoiceOut/front/index.js +++ b/modules/invoiceOut/front/index.js @@ -7,3 +7,5 @@ import './summary'; import './card'; import './descriptor'; import './descriptor-popover'; +import './index/manual'; +import './index/global-invoicing'; diff --git a/modules/invoiceOut/front/index/global-invoicing/index.html b/modules/invoiceOut/front/index/global-invoicing/index.html new file mode 100644 index 0000000000..9fd412d0eb --- /dev/null +++ b/modules/invoiceOut/front/index/global-invoicing/index.html @@ -0,0 +1,70 @@ + + Create global invoice + + + + + + +
+ + + Invoicing in progress... + +
+ + + + + + + + + {{::id}} - {{::name}} + + + {{::id}} - {{::name}} + + + + + + +
+ + + + \ No newline at end of file diff --git a/modules/invoiceOut/front/index/global-invoicing/index.js b/modules/invoiceOut/front/index/global-invoicing/index.js new file mode 100644 index 0000000000..5e522f23d4 --- /dev/null +++ b/modules/invoiceOut/front/index/global-invoicing/index.js @@ -0,0 +1,81 @@ +import ngModule from '../../module'; +import Dialog from 'core/components/dialog'; +import './style.scss'; + +class Controller extends Dialog { + constructor($element, $, $transclude) { + super($element, $, $transclude); + + this.isInvoicing = false; + this.invoice = { + maxShipped: new Date() + }; + } + + $onInit() { + this.getMinClientId(); + this.getMaxClientId(); + } + + getMinClientId() { + this.getClientId('min') + .then(res => this.invoice.fromClientId = res.data.id); + } + + getMaxClientId() { + this.getClientId('max') + .then(res => this.invoice.toClientId = res.data.id); + } + + getClientId(func) { + const order = func == 'min' ? 'ASC' : 'DESC'; + const params = { + filter: { + order: 'id ' + order, + limit: 1 + } + }; + return this.$http.get('Clients/findOne', {params}); + } + + get companyFk() { + return this.invoice.companyFk; + } + + set companyFk(value) { + this.invoice.companyFk = value; + } + + responseHandler(response) { + try { + if (response !== 'accept') + return super.responseHandler(response); + + if (!this.invoice.invoiceDate || !this.invoice.maxShipped) + throw new Error('Invoice date and the max date should be filled'); + + if (!this.invoice.fromClientId || !this.invoice.toClientId) + throw new Error('Choose a valid clients range'); + + this.isInvoicing = true; + return this.$http.post(`InvoiceOuts/globalInvoicing`, this.invoice) + .then(() => super.responseHandler(response)) + .then(() => this.vnApp.showSuccess(this.$t('Data saved!'))) + .finally(() => this.isInvoicing = false); + } catch (e) { + this.vnApp.showError(this.$t(e.message)); + this.isInvoicing = false; + return false; + } + } +} + +Controller.$inject = ['$element', '$scope', '$transclude']; + +ngModule.vnComponent('vnInvoiceOutGlobalInvoicing', { + slotTemplate: require('./index.html'), + controller: Controller, + bindings: { + companyFk: ' { + describe('Component vnInvoiceOutGlobalInvoicing', () => { + let controller; + let $httpBackend; + let $httpParamSerializer; + + beforeEach(ngModule('invoiceOut')); + + beforeEach(inject(($componentController, $rootScope, _$httpBackend_, _$httpParamSerializer_) => { + $httpBackend = _$httpBackend_; + $httpParamSerializer = _$httpParamSerializer_; + let $scope = $rootScope.$new(); + const $element = angular.element(''); + const $transclude = { + $$boundTransclude: { + $$slots: [] + } + }; + controller = $componentController('vnInvoiceOutGlobalInvoicing', {$element, $scope, $transclude}); + })); + + describe('getMinClientId()', () => { + it('should set the invoice fromClientId property', () => { + const filter = { + order: 'id ASC', + limit: 1 + }; + + const serializedParams = $httpParamSerializer({filter}); + $httpBackend.expectGET(`Clients/findOne?${serializedParams}`).respond(200, {id: 1101}); + + controller.getMinClientId(); + $httpBackend.flush(); + + expect(controller.invoice.fromClientId).toEqual(1101); + }); + }); + + describe('getMaxClientId()', () => { + it('should set the invoice toClientId property', () => { + const filter = { + order: 'id DESC', + limit: 1 + }; + + const serializedParams = $httpParamSerializer({filter}); + $httpBackend.expectGET(`Clients/findOne?${serializedParams}`).respond(200, {id: 1112}); + + controller.getMaxClientId(); + $httpBackend.flush(); + + expect(controller.invoice.toClientId).toEqual(1112); + }); + }); + + describe('responseHandler()', () => { + it('should throw an error when invoiceDate or maxShipped properties are not filled in', () => { + jest.spyOn(controller.vnApp, 'showError'); + + controller.invoice = { + fromClientId: 1101, + toClientId: 1101 + }; + + controller.responseHandler('accept'); + + expect(controller.vnApp.showError).toHaveBeenCalledWith(`Invoice date and the max date should be filled`); + }); + + it('should throw an error when fromClientId or toClientId properties are not filled in', () => { + jest.spyOn(controller.vnApp, 'showError'); + + controller.invoice = { + invoiceDate: new Date(), + maxShipped: new Date() + }; + + controller.responseHandler('accept'); + + expect(controller.vnApp.showError).toHaveBeenCalledWith(`Choose a valid clients range`); + }); + + it('should make an http POST query and then call to the showSuccess() method', () => { + jest.spyOn(controller.vnApp, 'showSuccess'); + + controller.invoice = { + invoiceDate: new Date(), + maxShipped: new Date(), + fromClientId: 1101, + toClientId: 1101 + }; + + $httpBackend.expect('POST', `InvoiceOuts/globalInvoicing`).respond({id: 1}); + controller.responseHandler('accept'); + $httpBackend.flush(); + + expect(controller.vnApp.showSuccess).toHaveBeenCalled(); + }); + }); + }); +}); diff --git a/modules/invoiceOut/front/index/global-invoicing/locale/es.yml b/modules/invoiceOut/front/index/global-invoicing/locale/es.yml new file mode 100644 index 0000000000..51e165e2a7 --- /dev/null +++ b/modules/invoiceOut/front/index/global-invoicing/locale/es.yml @@ -0,0 +1,9 @@ +Create global invoice: Crear factura global +Some fields are required: Algunos campos son obligatorios +Max date: Fecha límite +Invoicing in progress...: Facturación en progreso... +Invoice date: Fecha de factura +From client: Desde el cliente +To client: Hasta el cliente +Invoice date and the max date should be filled: La fecha de factura y la fecha límite deben rellenarse +Choose a valid clients range: Selecciona un rango válido de clientes \ No newline at end of file diff --git a/modules/invoiceOut/front/index/global-invoicing/style.scss b/modules/invoiceOut/front/index/global-invoicing/style.scss new file mode 100644 index 0000000000..d0bd9e2149 --- /dev/null +++ b/modules/invoiceOut/front/index/global-invoicing/style.scss @@ -0,0 +1,17 @@ +@import "variables"; + +.vn-invoice-out-global-invoicing { + tpl-body { + width: 500px; + + .progress { + font-weight: bold; + text-align: center; + font-size: 1.5rem; + color: $color-primary; + vn-horizontal { + justify-content: center + } + } + } +} \ No newline at end of file diff --git a/modules/invoiceOut/front/index/index.html b/modules/invoiceOut/front/index/index.html index 8685990a4e..d970bd15ac 100644 --- a/modules/invoiceOut/front/index/index.html +++ b/modules/invoiceOut/front/index/index.html @@ -57,6 +57,31 @@ +
+ + + + + + + Manual invoicing + + + Global invoicing + + + +
@@ -65,3 +90,10 @@ + + + + \ No newline at end of file diff --git a/modules/invoiceOut/front/index/locale/es.yml b/modules/invoiceOut/front/index/locale/es.yml index eb22e17799..1460b90d8a 100644 --- a/modules/invoiceOut/front/index/locale/es.yml +++ b/modules/invoiceOut/front/index/locale/es.yml @@ -3,4 +3,6 @@ Issued: Fecha factura Due date: Fecha vencimiento Has PDF: PDF disponible Minimum: Minimo -Maximum: Máximo \ No newline at end of file +Maximum: Máximo +Global invoicing: Facturación global +Manual invoicing: Facturación manual diff --git a/modules/invoiceOut/front/index/manual/index.html b/modules/invoiceOut/front/index/manual/index.html new file mode 100644 index 0000000000..3148d3f948 --- /dev/null +++ b/modules/invoiceOut/front/index/manual/index.html @@ -0,0 +1,83 @@ + + Create manual invoice + + + + + + +
+ + + Invoicing in progress... + +
+ + + + {{::id}} - {{::nickname}} + + + Or + + + + + + + + + + + + + + + +
+ + + + \ No newline at end of file diff --git a/modules/invoiceOut/front/index/manual/index.js b/modules/invoiceOut/front/index/manual/index.js new file mode 100644 index 0000000000..ed50e37dac --- /dev/null +++ b/modules/invoiceOut/front/index/manual/index.js @@ -0,0 +1,51 @@ +import ngModule from '../../module'; +import Dialog from 'core/components/dialog'; +import './style.scss'; + +class Controller extends Dialog { + constructor($element, $, $transclude) { + super($element, $, $transclude); + + this.isInvoicing = false; + this.invoice = { + maxShipped: new Date() + }; + } + + responseHandler(response) { + try { + if (response !== 'accept') + return super.responseHandler(response); + + if (this.invoice.clientFk && !this.invoice.maxShipped) + throw new Error('Client and the max shipped should be filled'); + + if (!this.invoice.serial || !this.invoice.taxArea) + throw new Error('Some fields are required'); + + this.isInvoicing = true; + return this.$http.post(`InvoiceOuts/createManualInvoice`, this.invoice) + .then(res => { + this.$state.go('invoiceOut.card.summary', {id: res.data.id}); + super.responseHandler(response); + }) + .then(() => this.vnApp.showSuccess(this.$t('Data saved!'))) + .finally(() => this.isInvoicing = false); + } catch (e) { + this.vnApp.showError(this.$t(e.message)); + this.isInvoicing = false; + return false; + } + } +} + +Controller.$inject = ['$element', '$scope', '$transclude']; + +ngModule.vnComponent('vnInvoiceOutManual', { + slotTemplate: require('./index.html'), + controller: Controller, + bindings: { + ticketFk: ' { + describe('Component vnInvoiceOutManual', () => { + let controller; + let $httpBackend; + + beforeEach(ngModule('invoiceOut')); + + beforeEach(inject(($componentController, $rootScope, _$httpBackend_) => { + $httpBackend = _$httpBackend_; + let $scope = $rootScope.$new(); + const $element = angular.element(''); + const $transclude = { + $$boundTransclude: { + $$slots: [] + } + }; + controller = $componentController('vnInvoiceOutManual', {$element, $scope, $transclude}); + })); + + describe('responseHandler()', () => { + it('should throw an error when clientFk property is set and the maxShipped is not filled', () => { + jest.spyOn(controller.vnApp, 'showError'); + + controller.invoice = { + clientFk: 1101, + serial: 'T', + taxArea: 'B' + }; + + controller.responseHandler('accept'); + + expect(controller.vnApp.showError).toHaveBeenCalledWith(`Client and the max shipped should be filled`); + }); + + it('should throw an error when some required fields are not filled in', () => { + jest.spyOn(controller.vnApp, 'showError'); + + controller.invoice = { + ticketFk: 1101 + }; + + controller.responseHandler('accept'); + + expect(controller.vnApp.showError).toHaveBeenCalledWith(`Some fields are required`); + }); + + it('should make an http POST query and then call to the parent showSuccess() method', () => { + jest.spyOn(controller.vnApp, 'showSuccess'); + + controller.invoice = { + ticketFk: 1101, + serial: 'T', + taxArea: 'B' + }; + + $httpBackend.expect('POST', `InvoiceOuts/createManualInvoice`).respond({id: 1}); + controller.responseHandler('accept'); + $httpBackend.flush(); + + expect(controller.vnApp.showSuccess).toHaveBeenCalled(); + }); + }); + }); +}); diff --git a/modules/invoiceOut/front/index/manual/locale/es.yml b/modules/invoiceOut/front/index/manual/locale/es.yml new file mode 100644 index 0000000000..370e823d06 --- /dev/null +++ b/modules/invoiceOut/front/index/manual/locale/es.yml @@ -0,0 +1,6 @@ +Create manual invoice: Crear factura manual +Some fields are required: Algunos campos son obligatorios +Client and max shipped fields should be filled: Los campos de cliente y fecha límite deben rellenarse +Max date: Fecha límite +Serial: Serie +Invoicing in progress...: Facturación en progreso... \ No newline at end of file diff --git a/modules/invoiceOut/front/index/manual/style.scss b/modules/invoiceOut/front/index/manual/style.scss new file mode 100644 index 0000000000..18e6f35138 --- /dev/null +++ b/modules/invoiceOut/front/index/manual/style.scss @@ -0,0 +1,17 @@ +@import "variables"; + +.vn-invoice-out-manual { + tpl-body { + width: 500px; + + .progress { + font-weight: bold; + text-align: center; + font-size: 1.5rem; + color: $color-primary; + vn-horizontal { + justify-content: center + } + } + } +} \ No newline at end of file diff --git a/modules/invoiceOut/front/summary/index.html b/modules/invoiceOut/front/summary/index.html index 0406a39c52..6a117052e9 100644 --- a/modules/invoiceOut/front/summary/index.html +++ b/modules/invoiceOut/front/summary/index.html @@ -1,5 +1,6 @@ diff --git a/modules/invoiceOut/front/summary/index.js b/modules/invoiceOut/front/summary/index.js index 2446e986ab..131f9ba8fe 100644 --- a/modules/invoiceOut/front/summary/index.js +++ b/modules/invoiceOut/front/summary/index.js @@ -3,29 +3,25 @@ import Summary from 'salix/components/summary'; import './style.scss'; class Controller extends Summary { - set invoiceOut(value) { - this._invoiceOut = value; - if (value && value.id) { - this.getSummary(); - this.getTickets(); - } - } - get invoiceOut() { return this._invoiceOut; } - getSummary() { - return this.$http.get(`InvoiceOuts/${this.invoiceOut.id}/summary`) + set invoiceOut(value) { + this._invoiceOut = value; + if (value && value.id) { + this.loadData(); + this.loadTickets(); + } + } + + loadData() { + this.$http.get(`InvoiceOuts/${this.invoiceOut.id}/summary`) .then(res => this.summary = res.data); } - getTickets() { - this.$.$applyAsync(() => { - const query = `InvoiceOuts/${this.invoiceOut.id}/getTickets`; - this.$.ticketsModel.url = query; - this.$.ticketsModel.refresh(); - }); + loadTickets() { + this.$.$applyAsync(() => this.$.ticketsModel.refresh()); } } diff --git a/modules/invoiceOut/front/summary/index.spec.js b/modules/invoiceOut/front/summary/index.spec.js index be6ad0a181..44e3094ae5 100644 --- a/modules/invoiceOut/front/summary/index.spec.js +++ b/modules/invoiceOut/front/summary/index.spec.js @@ -18,26 +18,14 @@ describe('InvoiceOut', () => { controller.$.ticketsModel = crudModel; })); - describe('getSummary()', () => { + describe('loadData()', () => { it('should perform a query to set summary', () => { $httpBackend.expect('GET', `InvoiceOuts/1/summary`).respond(200, 'the data you are looking for'); - controller.getSummary(); + controller.loadData(); $httpBackend.flush(); expect(controller.summary).toEqual('the data you are looking for'); }); }); - - describe('getTickets()', () => { - it('should perform a and then call to the ticketModel refresh() method', () => { - jest.spyOn(controller.$.ticketsModel, 'refresh'); - - controller.getTickets(); - $scope.$apply(); - - expect(controller.$.ticketsModel.url).toEqual('InvoiceOuts/1/getTickets'); - expect(controller.$.ticketsModel.refresh).toHaveBeenCalledWith(); - }); - }); }); }); diff --git a/modules/item/back/methods/fixed-price/filter.js b/modules/item/back/methods/fixed-price/filter.js index 22cf2bf446..c15ae67f00 100644 --- a/modules/item/back/methods/fixed-price/filter.js +++ b/modules/item/back/methods/fixed-price/filter.js @@ -80,12 +80,12 @@ module.exports = Self => { }, { arg: 'mine', - type: 'Boolean', + type: 'boolean', description: `Search requests attended by the current user` } ], returns: { - type: ['Object'], + type: ['object'], root: true }, http: { @@ -94,9 +94,13 @@ module.exports = Self => { } }); - Self.filter = async(ctx, filter) => { + Self.filter = async(ctx, filter, options) => { const conn = Self.dataSource.connector; - let userId = ctx.req.accessToken.userId; + const userId = ctx.req.accessToken.userId; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); if (ctx.args.mine) ctx.args.buyerFk = userId; @@ -128,36 +132,35 @@ module.exports = Self => { filter = mergeFilters(filter, {where}); const stmts = []; - let stmt; - stmt = new ParameterizedSQL( - `SELECT fp.id, - fp.itemFk, - fp.warehouseFk, - fp.rate2, - fp.rate3, - fp.started, - fp.ended, - i.minPrice, - i.hasMinPrice, - i.name, - i.subName, - i.tag5, - i.value5, - i.tag6, - i.value6, - i.tag7, - i.value7, - i.tag8, - i.value8, - i.tag9, - i.value9, - i.tag10, - i.value10 - FROM priceFixed fp - JOIN item i ON i.id = fp.itemFk - JOIN itemType it ON it.id = i.typeFk` - ); + const stmt = new ParameterizedSQL(` + SELECT fp.id, + fp.itemFk, + fp.warehouseFk, + fp.rate2, + fp.rate3, + fp.started, + fp.ended, + i.minPrice, + i.hasMinPrice, + i.name, + i.subName, + i.tag5, + i.value5, + i.tag6, + i.value6, + i.tag7, + i.value7, + i.tag8, + i.value8, + i.tag9, + i.value9, + i.tag10, + i.value10 + FROM priceFixed fp + JOIN item i ON i.id = fp.itemFk + JOIN itemType it ON it.id = i.typeFk + `); if (ctx.args.tags) { let i = 1; @@ -186,7 +189,8 @@ module.exports = Self => { const fixedPriceIndex = stmts.push(stmt) - 1; const sql = ParameterizedSQL.join(stmts, ';'); - const result = await conn.executeStmt(sql); + const result = await conn.executeStmt(sql, myOptions); + return fixedPriceIndex === 0 ? result : result[fixedPriceIndex]; }; }; diff --git a/modules/item/back/methods/fixed-price/specs/filter.spec.js b/modules/item/back/methods/fixed-price/specs/filter.spec.js index ff259357fc..bdb28efd92 100644 --- a/modules/item/back/methods/fixed-price/specs/filter.spec.js +++ b/modules/item/back/methods/fixed-price/specs/filter.spec.js @@ -1,86 +1,136 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('fixed price filter()', () => { it('should return 1 result filtering by item ID', async() => { - const itemID = 3; - const ctx = { - req: {accessToken: {userId: 1}}, - args: { - search: itemID - } - }; - const result = await app.models.FixedPrice.filter(ctx); + const tx = await models.FixedPrice.beginTransaction({}); - expect(result.length).toEqual(1); - expect(result[0].id).toEqual(2); - expect(result[0].itemFk).toEqual(itemID); + try { + const options = {transaction: tx}; + const itemID = 3; + const ctx = { + req: {accessToken: {userId: 1}}, + args: { + search: itemID + } + }; + const result = await models.FixedPrice.filter(ctx, null, options); + + expect(result.length).toEqual(1); + expect(result[0].id).toEqual(2); + expect(result[0].itemFk).toEqual(itemID); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return 1 result filtering by item type code', async() => { - const itemCode = 'CRI'; - const ctx = { - req: {accessToken: {userId: 1}}, - args: { - search: itemCode - } - }; - const itemType = await app.models.ItemType.findOne({ - where: {code: itemCode}, - fields: ['id'] - }); - const items = await app.models.Item.find({ - where: {typeFk: itemType.id}, - fields: ['id'] - }); - const IDs = items.map(item => { - return item.id; - }); + const tx = await models.FixedPrice.beginTransaction({}); - const result = await app.models.FixedPrice.filter(ctx); - const firstResult = result[0]; + try { + const options = {transaction: tx}; + const itemCode = 'CRI'; + const ctx = { + req: {accessToken: {userId: 1}}, + args: { + search: itemCode + } + }; + const itemType = await models.ItemType.findOne({ + where: {code: itemCode}, + fields: ['id'] + }, options); + const items = await models.Item.find({ + where: {typeFk: itemType.id}, + fields: ['id'] + }, options); + const IDs = items.map(item => { + return item.id; + }); - expect(result.length).toEqual(1); - expect(firstResult.id).toEqual(2); - expect(IDs).toContain(firstResult.itemFk); + const result = await models.FixedPrice.filter(ctx, null, options); + const firstResult = result[0]; + + expect(result.length).toEqual(1); + expect(firstResult.id).toEqual(2); + expect(IDs).toContain(firstResult.itemFk); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return 2 results filtering by warehouse', async() => { - const warehouseID = 1; - const ctx = { - req: {accessToken: {userId: 1}}, - args: { - warehouseFk: warehouseID - } - }; - const result = await app.models.FixedPrice.filter(ctx); - const length = result.length; - const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + const tx = await models.FixedPrice.beginTransaction({}); - expect(result.length).toEqual(2); - expect(anyResult.warehouseFk).toEqual(warehouseID); + try { + const options = {transaction: tx}; + const warehouseID = 1; + const ctx = { + req: {accessToken: {userId: 1}}, + args: { + warehouseFk: warehouseID + } + }; + const result = await models.FixedPrice.filter(ctx, null, options); + const length = result.length; + const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + + expect(result.length).toEqual(2); + expect(anyResult.warehouseFk).toEqual(warehouseID); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return no results filtering by hasMinPrice', async() => { - const ctx = { - req: {accessToken: {userId: 1}}, - args: { - hasMinPrice: true - } - }; - const result = await app.models.FixedPrice.filter(ctx); + const tx = await models.FixedPrice.beginTransaction({}); - expect(result.length).toEqual(0); + try { + const options = {transaction: tx}; + const ctx = { + req: {accessToken: {userId: 1}}, + args: { + hasMinPrice: true + } + }; + const result = await models.FixedPrice.filter(ctx, null, options); + + expect(result.length).toEqual(0); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return no results filtering by typeFk', async() => { - const ctx = { - req: {accessToken: {userId: 1}}, - args: { - typeFk: 1 - } - }; - const result = await app.models.FixedPrice.filter(ctx); + const tx = await models.FixedPrice.beginTransaction({}); - expect(result.length).toEqual(1); + try { + const options = {transaction: tx}; + const ctx = { + req: {accessToken: {userId: 1}}, + args: { + typeFk: 1 + } + }; + const result = await models.FixedPrice.filter(ctx, null, options); + + expect(result.length).toEqual(1); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js b/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js index 63c2112935..68eacfbad4 100644 --- a/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js +++ b/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js @@ -1,62 +1,75 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('upsertFixedPrice()', () => { const now = new Date(); const fixedPriceId = 1; let originalFixedPrice; - let originalItem; beforeAll(async() => { - originalFixedPrice = await app.models.FixedPrice.findById(fixedPriceId); - originalItem = await app.models.Item.findById(originalFixedPrice.itemFk); - }); - - afterAll(async() => { - await originalFixedPrice.save(); - await originalItem.save(); + originalFixedPrice = await models.FixedPrice.findById(fixedPriceId); }); it(`should toggle the hasMinPrice boolean if there's a minPrice and update the rest of the data`, async() => { - const ctx = {args: { - id: fixedPriceId, - itemFk: originalFixedPrice.itemFk, - warehouseFk: 1, - rate2: 100, - rate3: 300, - started: now, - ended: now, - minPrice: 100, - hasMinPrice: false - }}; + const tx = await models.FixedPrice.beginTransaction({}); - const result = await app.models.FixedPrice.upsertFixedPrice(ctx, ctx.args.id); + try { + const options = {transaction: tx}; + const ctx = {args: { + id: fixedPriceId, + itemFk: originalFixedPrice.itemFk, + warehouseFk: 1, + rate2: 100, + rate3: 300, + started: now, + ended: now, + minPrice: 100, + hasMinPrice: false + }}; - delete ctx.args.started; - delete ctx.args.ended; - ctx.args.hasMinPrice = true; + const result = await models.FixedPrice.upsertFixedPrice(ctx, options); - expect(result).toEqual(jasmine.objectContaining(ctx.args)); + delete ctx.args.started; + delete ctx.args.ended; + ctx.args.hasMinPrice = true; + + expect(result).toEqual(jasmine.objectContaining(ctx.args)); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it(`should toggle the hasMinPrice boolean if there's no minPrice and update the rest of the data`, async() => { - const ctx = {args: { - id: fixedPriceId, - itemFk: originalFixedPrice.itemFk, - warehouseFk: 1, - rate2: 2.5, - rate3: 2, - started: now, - ended: now, - minPrice: 0, - hasMinPrice: true - }}; + const tx = await models.FixedPrice.beginTransaction({}); - const result = await app.models.FixedPrice.upsertFixedPrice(ctx, ctx.args.id); + try { + const options = {transaction: tx}; + const ctx = {args: { + id: fixedPriceId, + itemFk: originalFixedPrice.itemFk, + warehouseFk: 1, + rate2: 2.5, + rate3: 2, + started: now, + ended: now, + minPrice: 0, + hasMinPrice: true + }}; - delete ctx.args.started; - delete ctx.args.ended; - ctx.args.hasMinPrice = false; + const result = await models.FixedPrice.upsertFixedPrice(ctx, options); - expect(result).toEqual(jasmine.objectContaining(ctx.args)); + delete ctx.args.started; + delete ctx.args.ended; + ctx.args.hasMinPrice = false; + + expect(result).toEqual(jasmine.objectContaining(ctx.args)); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/fixed-price/upsertFixedPrice.js b/modules/item/back/methods/fixed-price/upsertFixedPrice.js index dbdeebdab1..ad35ec3a15 100644 --- a/modules/item/back/methods/fixed-price/upsertFixedPrice.js +++ b/modules/item/back/methods/fixed-price/upsertFixedPrice.js @@ -2,48 +2,50 @@ module.exports = Self => { Self.remoteMethod('upsertFixedPrice', { description: 'Inserts or updates a fixed price for an item', accessType: 'WRITE', - accepts: [{ - arg: 'ctx', - type: 'object', - http: {source: 'context'} - }, - { - arg: 'id', - type: 'number', - description: 'The fixed price id' - }, - { - arg: 'itemFk', - type: 'number' - }, - { - arg: 'warehouseFk', - type: 'number' - }, - { - arg: 'started', - type: 'date' - }, - { - arg: 'ended', - type: 'date' - }, - { - arg: 'rate2', - type: 'number' - }, - { - arg: 'rate3', - type: 'number' - }, - { - arg: 'minPrice', - type: 'number' - }, - { - arg: 'hasMinPrice', - type: 'any' - }], + accepts: [ + { + arg: 'ctx', + type: 'object', + http: {source: 'context'} + }, + { + arg: 'id', + type: 'number', + description: 'The fixed price id' + }, + { + arg: 'itemFk', + type: 'number' + }, + { + arg: 'warehouseFk', + type: 'number' + }, + { + arg: 'started', + type: 'date' + }, + { + arg: 'ended', + type: 'date' + }, + { + arg: 'rate2', + type: 'number' + }, + { + arg: 'rate3', + type: 'number' + }, + { + arg: 'minPrice', + type: 'number' + }, + { + arg: 'hasMinPrice', + type: 'any' + } + ], returns: { type: 'object', root: true @@ -54,21 +56,29 @@ module.exports = Self => { } }); - Self.upsertFixedPrice = async ctx => { + Self.upsertFixedPrice = async(ctx, options) => { const models = Self.app.models; - const args = ctx.args; - const tx = await models.Address.beginTransaction({}); - try { - const options = {transaction: tx}; - delete args.ctx; // removed unwanted data + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + delete args.ctx; // removed unwanted data + const fixedPrice = await models.FixedPrice.upsert(args, myOptions); + const targetItem = await models.Item.findById(args.itemFk, null, myOptions); - const fixedPrice = await models.FixedPrice.upsert(args, options); - const targetItem = await models.Item.findById(args.itemFk, null, options); await targetItem.updateAttributes({ minPrice: args.minPrice, hasMinPrice: args.minPrice ? true : false - }, options); + }, myOptions); const itemFields = [ 'minPrice', @@ -99,16 +109,17 @@ module.exports = Self => { } }; - const result = await models.FixedPrice.findById(fixedPrice.id, filter, options); + const result = await models.FixedPrice.findById(fixedPrice.id, filter, myOptions); const item = result.item(); for (let key of itemFields) result[key] = item[key]; - await tx.commit(); + if (tx) await tx.commit(); + return result; } catch (e) { - await tx.rollback(); + if (tx) await tx.rollback(); throw e; } }; diff --git a/modules/item/back/methods/item-barcode/specs/toItem.spec.js b/modules/item/back/methods/item-barcode/specs/toItem.spec.js index 9e81dc5907..5547a3886c 100644 --- a/modules/item/back/methods/item-barcode/specs/toItem.spec.js +++ b/modules/item/back/methods/item-barcode/specs/toItem.spec.js @@ -1,10 +1,20 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('item-barcode toItem()', () => { it('should return the same number if there is a barcode and a item with the same ID', async() => { - let barcode = 3; - let result = await app.models.ItemBarcode.toItem(barcode); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result).toBe(3); + try { + const barcode = 3; + const result = await models.ItemBarcode.toItem(barcode, options); + + expect(result).toBe(3); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item-barcode/toItem.js b/modules/item/back/methods/item-barcode/toItem.js index 0fbbf4508d..96e9d5981e 100644 --- a/modules/item/back/methods/item-barcode/toItem.js +++ b/modules/item/back/methods/item-barcode/toItem.js @@ -4,12 +4,12 @@ module.exports = Self => { accessType: 'READ', accepts: [{ arg: 'barcode', - type: 'Number', + type: 'number', required: true, description: 'barcode' }], returns: { - type: 'Number', + type: 'number', root: true }, http: { @@ -18,11 +18,18 @@ module.exports = Self => { } }); - Self.toItem = async barcode => { - let query = `SELECT vn.barcodeToItem(?)`; - let [item] = await Self.rawSql(query, [barcode]); + Self.toItem = async(barcode, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const query = `SELECT vn.barcodeToItem(?)`; + let [item] = await Self.rawSql(query, [barcode], myOptions); + if (item) - item = Object.values(item); - return item[0]; + item = Object.values(item)[0]; + + return item; }; }; diff --git a/modules/item/back/methods/item-tag/filterItemTags.js b/modules/item/back/methods/item-tag/filterItemTags.js index ed5973c17c..8a02f58802 100644 --- a/modules/item/back/methods/item-tag/filterItemTags.js +++ b/modules/item/back/methods/item-tag/filterItemTags.js @@ -5,17 +5,19 @@ module.exports = Self => { Self.remoteMethod('filterItemTags', { description: 'Returns the distinct values of a tag property', accessType: 'READ', - accepts: [{ - arg: 'tagFk', - type: 'number', - required: true, - description: 'The foreign key from tag table', - http: {source: 'path'} - }, { - arg: 'filter', - type: 'Object', - description: `Filter defining where, order, offset, and limit - must be a JSON-encoded string` - }], + accepts: [ + { + arg: 'tagFk', + type: 'number', + required: true, + description: 'The foreign key from tag table', + http: {source: 'path'} + }, { + arg: 'filter', + type: 'object', + description: `Filter defining where, order, offset, and limit - must be a JSON-encoded string` + } + ], returns: { root: true, type: ['object'] @@ -26,16 +28,21 @@ module.exports = Self => { } }); - Self.filterItemTags = async(tagFk, filter) => { - let conn = Self.dataSource.connector; - let where = {tagFk: tagFk}; - myFilter = mergeFilters(filter, {where}); + Self.filterItemTags = async(tagFk, filter, options) => { + const conn = Self.dataSource.connector; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const where = {tagFk: tagFk}; + const myFilter = mergeFilters(filter, {where}); stmt = new ParameterizedSQL( `SELECT DISTINCT(value) FROM itemTag`); stmt.merge(conn.makeSuffix(myFilter)); - return await conn.executeStmt(stmt); + return conn.executeStmt(stmt, myOptions); }; }; diff --git a/modules/item/back/methods/item-tag/specs/filterItemTags.spec.js b/modules/item/back/methods/item-tag/specs/filterItemTags.spec.js index 2723673275..3c6d2ccff3 100644 --- a/modules/item/back/methods/item-tag/specs/filterItemTags.spec.js +++ b/modules/item/back/methods/item-tag/specs/filterItemTags.spec.js @@ -1,9 +1,19 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('item filterItemTags()', () => { it('should filter ItemTags table', async() => { - let [result] = await app.models.ItemTag.filterItemTags(1, {}); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result.value).toEqual('Black'); + try { + const [result] = await models.ItemTag.filterItemTags(1, null, options); + + expect(result.value).toEqual('Black'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/clone.js b/modules/item/back/methods/item/clone.js index f543164fc4..3e6f3ab5ac 100644 --- a/modules/item/back/methods/item/clone.js +++ b/modules/item/back/methods/item/clone.js @@ -12,7 +12,7 @@ module.exports = Self => { http: {source: 'path'} }], returns: { - type: 'Object', + type: 'object', description: 'new cloned itemId', root: true, }, @@ -22,13 +22,21 @@ module.exports = Self => { } }); - Self.clone = async itemId => { - let tx = await Self.beginTransaction({}); + Self.clone = async(itemId, options) => { + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } try { - let options = {transaction: tx}; + const origin = await Self.findById(itemId, null, myOptions); - const origin = await Self.findById(itemId, null, options); if (!origin) throw new UserError(`This item doesn't exists`); @@ -38,16 +46,17 @@ module.exports = Self => { origin.comment = undefined; origin.size = undefined; - const newItem = await Self.create(origin, options); + const newItem = await Self.create(origin, myOptions); - await cloneTaxes(origin.id, newItem.id, options); - await cloneBotanical(origin.id, newItem.id, options); - await cloneTags(origin.id, newItem.id, options); + await cloneTaxes(origin.id, newItem.id, myOptions); + await cloneBotanical(origin.id, newItem.id, myOptions); + await cloneTags(origin.id, newItem.id, myOptions); + + if (tx) await tx.commit(); - await tx.commit(); return newItem; } catch (e) { - await tx.rollback(); + if (tx) await tx.rollback(); throw e; } }; @@ -62,7 +71,7 @@ module.exports = Self => { const models = Self.app.models; const originalTaxes = await models.ItemTaxCountry.find({ where: {itemFk: originalId}, - fields: ['botanical', 'countryFk', 'taxClassFk'] + fields: ['countryFk', 'taxClassFk'] }, options); const promises = []; @@ -90,7 +99,7 @@ module.exports = Self => { const models = Self.app.models; const botanical = await models.ItemBotanical.findOne({ where: {itemFk: originalId}, - fields: ['botanical', 'genusFk', 'specieFk'] + fields: ['genusFk', 'specieFk'] }, options); if (botanical) { diff --git a/modules/item/back/methods/item/createIntrastat.js b/modules/item/back/methods/item/createIntrastat.js index bd921f29a4..d43d2e27f7 100644 --- a/modules/item/back/methods/item/createIntrastat.js +++ b/modules/item/back/methods/item/createIntrastat.js @@ -2,23 +2,25 @@ module.exports = Self => { Self.remoteMethod('createIntrastat', { description: 'Creates a new item intrastat', accessType: 'WRITE', - accepts: [{ - arg: 'id', - type: 'number', - required: true, - description: 'The item id', - http: {source: 'path'} - }, - { - arg: 'intrastatId', - type: 'number', - required: true - }, - { - arg: 'description', - type: 'string', - required: true - }], + accepts: [ + { + arg: 'id', + type: 'number', + required: true, + description: 'The item id', + http: {source: 'path'} + }, + { + arg: 'intrastatId', + type: 'number', + required: true + }, + { + arg: 'description', + type: 'string', + required: true + } + ], returns: { type: 'boolean', root: true @@ -29,11 +31,16 @@ module.exports = Self => { } }); - Self.createIntrastat = async(id, intrastatId, description) => { + Self.createIntrastat = async(id, intrastatId, description, options) => { const models = Self.app.models; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + const country = await models.Country.findOne({ where: {code: 'ES'} - }); + }, myOptions); const itemTaxCountry = await models.ItemTaxCountry.findOne({ where: { @@ -41,19 +48,22 @@ module.exports = Self => { countryFk: country.id }, order: 'effectived DESC' - }); + }, myOptions); + const taxClassCode = await models.TaxClassCode.findOne({ where: { taxClassFk: itemTaxCountry.taxClassFk }, order: 'effectived DESC' - }); + }, myOptions); - return models.Intrastat.create({ + const intrastat = await models.Intrastat.create({ id: intrastatId, description: description, taxClassFk: itemTaxCountry.taxClassFk, taxCodeFk: taxClassCode.taxCodeFk - }); + }, myOptions); + + return intrastat; }; }; diff --git a/modules/item/back/methods/item/filter.js b/modules/item/back/methods/item/filter.js index eba0b0f918..cff36a2233 100644 --- a/modules/item/back/methods/item/filter.js +++ b/modules/item/back/methods/item/filter.js @@ -10,48 +10,62 @@ module.exports = Self => { accepts: [ { arg: 'filter', - type: 'Object', + type: 'object', description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', - }, { + }, + { arg: 'tags', - type: ['Object'], + type: ['object'], description: 'List of tags to filter with', - }, { + }, + { arg: 'search', - type: 'String', + type: 'string', description: `If it's and integer searchs by id, otherwise it searchs by name`, - }, { + }, + { arg: 'id', - type: 'Integer', + type: 'integer', description: 'Item id', - }, { + }, + { arg: 'categoryFk', - type: 'Integer', + type: 'integer', description: 'Category id', - }, { + }, + { arg: 'typeFk', - type: 'Integer', + type: 'integer', description: 'Type id', - }, { + }, + { arg: 'isActive', - type: 'Boolean', + type: 'boolean', description: 'Whether the the item is or not active', - }, { + }, + { arg: 'salesPersonFk', - type: 'Integer', + type: 'integer', description: 'The buyer of the item', - }, { + }, + { arg: 'description', - type: 'String', + type: 'string', description: 'The item description', - }, { + }, + { arg: 'stemMultiplier', - type: 'Integer', + type: 'integer', description: 'The item multiplier', + }, + { + arg: 'landed', + type: 'date', + description: 'The item last buy landed date', } ], returns: { - type: ['Object'], + type: ['object'], root: true }, http: { @@ -60,23 +74,30 @@ module.exports = Self => { } }); - Self.filter = async(ctx, filter) => { - let conn = Self.dataSource.connector; + Self.filter = async(ctx, filter, options) => { + const conn = Self.dataSource.connector; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + let codeWhere; if (ctx.args.search) { - let items = await Self.app.models.ItemBarcode.find({ + const items = await Self.app.models.ItemBarcode.find({ where: {code: ctx.args.search}, fields: ['itemFk'] - }); - let itemIds = []; + }, myOptions); + + const itemIds = []; + for (const item of items) itemIds.push(item.itemFk); codeWhere = {'i.id': {inq: itemIds}}; } - let where = buildFilter(ctx.args, (param, value) => { + const where = buildFilter(ctx.args, (param, value) => { switch (param) { case 'search': return /^\d+$/.test(value) @@ -90,24 +111,23 @@ module.exports = Self => { return {'i.stemMultiplier': value}; case 'typeFk': return {'i.typeFk': value}; - case 'category': - return {'ic.name': value}; + case 'categoryFk': + return {'ic.id': value}; case 'salesPersonFk': return {'it.workerFk': value}; case 'origin': return {'ori.code': value}; - case 'niche': - return {'ip.code': value}; case 'intrastat': return {'intr.description': value}; + case 'landed': + return {'lb.landed': value}; } }); + filter = mergeFilters(filter, {where}); - let stmts = []; - let stmt; - - stmt = new ParameterizedSQL( + const stmts = []; + const stmt = new ParameterizedSQL( `SELECT i.id, i.image, @@ -134,7 +154,7 @@ module.exports = Self => { intr.description AS intrastat, b.grouping, b.packing, - ip.code AS niche, @visibleCalc + lb.landing AS landed FROM item i LEFT JOIN itemType it ON it.id = i.typeFk LEFT JOIN itemCategory ic ON ic.id = it.categoryFk @@ -144,8 +164,7 @@ module.exports = Self => { LEFT JOIN producer pr ON pr.id = i.producerFk LEFT JOIN origin ori ON ori.id = i.originFk LEFT JOIN cache.last_buy lb ON lb.item_id = i.id AND lb.warehouse_id = it.warehouseFk - LEFT JOIN vn.buy b ON b.id = lb.buy_id - LEFT JOIN itemPlacement ip ON ip.itemFk = i.id AND ip.warehouseFk = it.warehouseFk` + LEFT JOIN vn.buy b ON b.id = lb.buy_id` ); if (ctx.args.tags) { @@ -173,9 +192,10 @@ module.exports = Self => { stmt.merge(conn.makeWhere(filter.where)); stmt.merge(conn.makePagination(filter)); - let itemsIndex = stmts.push(stmt) - 1; - let sql = ParameterizedSQL.join(stmts, ';'); - let result = await conn.executeStmt(sql); + const itemsIndex = stmts.push(stmt) - 1; + const sql = ParameterizedSQL.join(stmts, ';'); + const result = await conn.executeStmt(sql, myOptions); + return itemsIndex === 0 ? result : result[itemsIndex]; }; }; diff --git a/modules/item/back/methods/item/getBalance.js b/modules/item/back/methods/item/getBalance.js index 916757c463..50372652d5 100644 --- a/modules/item/back/methods/item/getBalance.js +++ b/modules/item/back/methods/item/getBalance.js @@ -19,9 +19,15 @@ module.exports = Self => { } }); - Self.getBalance = async filter => { + Self.getBalance = async(filter, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + const where = filter.where; - let [diary] = await Self.rawSql(`CALL vn.item_getBalance(?, ?)`, [where.itemFk, where.warehouseFk]); + const query = 'CALL vn.item_getBalance(?, ?)'; + const [diary] = await Self.rawSql(query, [where.itemFk, where.warehouseFk], myOptions); for (const entry of diary) if (entry.clientType === 'loses') entry.highlighted = true; diff --git a/modules/item/back/methods/item/getCard.js b/modules/item/back/methods/item/getCard.js index 69b5c11163..8bb88fc86b 100644 --- a/modules/item/back/methods/item/getCard.js +++ b/modules/item/back/methods/item/getCard.js @@ -19,12 +19,13 @@ module.exports = Self => { } }); - Self.getCard = async id => { - let item = {}; + Self.getCard = async(id, options) => { + const myOptions = {}; - // Item basic data - let filter = { - where: {id: id}, + if (typeof options == 'object') + Object.assign(myOptions, options); + + const filter = { include: [ { relation: 'itemType', @@ -58,8 +59,8 @@ module.exports = Self => { } ] }; - [item] = await Self.app.models.Item.find(filter); + const item = await Self.app.models.Item.findById(id, filter, myOptions); - return item; + return item ? item : {}; }; }; diff --git a/modules/item/back/methods/item/getSummary.js b/modules/item/back/methods/item/getSummary.js index 4ef9652cab..ffcfc806ec 100644 --- a/modules/item/back/methods/item/getSummary.js +++ b/modules/item/back/methods/item/getSummary.js @@ -19,14 +19,18 @@ module.exports = Self => { } }); - Self.getSummary = async(ctx, id) => { - let promises = []; - let summary = {}; + Self.getSummary = async(ctx, id, options) => { const models = Self.app.models; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const promises = []; + const summary = {}; // Item basic data and taxes let filter = { - where: {id: id}, include: [ {relation: 'itemType', scope: { @@ -67,7 +71,7 @@ module.exports = Self => { } ] }; - promises.push(models.Item.find(filter)); + promises.push(models.Item.findById(id, filter, myOptions)); // Tags filter = { @@ -79,35 +83,28 @@ module.exports = Self => { relation: 'tag' } }; - promises.push(models.ItemTag.find(filter)); + promises.push(models.ItemTag.find(filter, myOptions)); // Botanical filter = { where: {itemFk: id}, include: [{relation: 'genus'}, {relation: 'specie'}] }; - promises.push(models.ItemBotanical.find(filter)); - - // Niches - filter = { - where: {itemFk: id}, - include: {relation: 'warehouse'} - }; - promises.push(models.ItemNiche.find(filter)); + promises.push(models.ItemBotanical.find(filter, myOptions)); let res = await Promise.all(promises); - [summary.item] = res[0]; + summary.item = res[0]; summary.tags = res[1]; [summary.botanical] = res[2]; - summary.niches = res[3]; - const userConfig = await models.UserConfig.getUserConfig(ctx); + const userConfig = await models.UserConfig.getUserConfig(ctx, myOptions); - res = await models.Item.getVisibleAvailable(summary.item.id, userConfig.warehouseFk); + res = await models.Item.getVisibleAvailable(summary.item.id, userConfig.warehouseFk, null, myOptions); summary.available = res.available; summary.visible = res.visible; + return summary; }; }; diff --git a/modules/item/back/methods/item/getVisibleAvailable.js b/modules/item/back/methods/item/getVisibleAvailable.js index 0dd5787330..b291ad9b46 100644 --- a/modules/item/back/methods/item/getVisibleAvailable.js +++ b/modules/item/back/methods/item/getVisibleAvailable.js @@ -5,19 +5,20 @@ module.exports = Self => { accepts: [ { arg: 'id', - type: 'Number', + type: 'number', required: true, }, { arg: 'warehouseFk', - type: 'Number', + type: 'number', required: true, }, { arg: 'dated', - type: 'Date', + type: 'date', required: false, - }], + } + ], returns: { type: ['object'], root: true @@ -28,32 +29,43 @@ module.exports = Self => { } }); - Self.getVisibleAvailable = async(id, warehouseFk, dated = new Date()) => { - let stmts = []; + Self.getVisibleAvailable = async(id, warehouseFk, dated = new Date(), options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const stmts = []; stmts.push(new ParameterizedSQL( - 'CALL cache.available_refresh(@availableCalc, FALSE, ?, ?)', [ + 'CALL cache.available_refresh(@availableCalc, FALSE, ?, ?)', + [ warehouseFk, dated - ] + ], + myOptions )); + stmts.push(new ParameterizedSQL( 'CALL cache.visible_refresh(@visibleCalc, FALSE,?)', [ warehouseFk ] )); + const visibleIndex = stmts.push(new ParameterizedSQL( - 'SELECT visible FROM cache.visible WHERE calc_id = @visibleCalc AND item_id = ?', [ - id - ] + 'SELECT visible FROM cache.visible WHERE calc_id = @visibleCalc AND item_id = ?', + [id], + myOptions )) - 1; + const availableIndex = stmts.push(new ParameterizedSQL( - 'SELECT available FROM cache.available WHERE calc_id = @availableCalc AND item_id = ?', [ - id - ] + 'SELECT available FROM cache.available WHERE calc_id = @availableCalc AND item_id = ?', + [id], + myOptions )) - 1; + const sql = ParameterizedSQL.join(stmts, ';'); - let res = await Self.rawStmt(sql); + const res = await Self.rawStmt(sql, myOptions); return { available: res[availableIndex][0] ? res[availableIndex][0].available : 0, diff --git a/modules/item/back/methods/item/getWasteByItem.js b/modules/item/back/methods/item/getWasteByItem.js index 21a68c3591..a797667f54 100644 --- a/modules/item/back/methods/item/getWasteByItem.js +++ b/modules/item/back/methods/item/getWasteByItem.js @@ -17,7 +17,7 @@ module.exports = Self => { } ], returns: { - type: ['Object'], + type: ['object'], root: true }, http: { @@ -26,7 +26,12 @@ module.exports = Self => { } }); - Self.getWasteByItem = async(buyer, family) => { + Self.getWasteByItem = async(buyer, family, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + const wastes = await Self.rawSql(` SELECT *, 100 * dwindle / total AS percentage FROM ( @@ -41,7 +46,7 @@ module.exports = Self => { AND week = WEEK(TIMESTAMPADD(WEEK,-1,CURDATE()), 1) GROUP BY buyer, itemFk ) sub - ORDER BY family, percentage DESC`, [buyer, family]); + ORDER BY family, percentage DESC`, [buyer, family], myOptions); const details = []; diff --git a/modules/item/back/methods/item/getWasteByWorker.js b/modules/item/back/methods/item/getWasteByWorker.js index 032472696b..5e40831b95 100644 --- a/modules/item/back/methods/item/getWasteByWorker.js +++ b/modules/item/back/methods/item/getWasteByWorker.js @@ -4,7 +4,7 @@ module.exports = Self => { accessType: 'READ', accepts: [], returns: { - type: ['Object'], + type: ['object'], root: true }, http: { @@ -13,7 +13,12 @@ module.exports = Self => { } }); - Self.getWasteByWorker = async() => { + Self.getWasteByWorker = async options => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + const wastes = await Self.rawSql(` SELECT *, 100 * dwindle / total AS percentage FROM ( @@ -26,7 +31,7 @@ module.exports = Self => { AND week = WEEK(TIMESTAMPADD(WEEK,-1,CURDATE()), 1) GROUP BY buyer, family ) sub - ORDER BY percentage DESC`); + ORDER BY percentage DESC`, null, myOptions); const details = []; diff --git a/modules/item/back/methods/item/lastEntriesFilter.js b/modules/item/back/methods/item/lastEntriesFilter.js index 6f22f637fa..83a8fe7a28 100644 --- a/modules/item/back/methods/item/lastEntriesFilter.js +++ b/modules/item/back/methods/item/lastEntriesFilter.js @@ -21,8 +21,13 @@ module.exports = Self => { } }); - Self.lastEntriesFilter = async filter => { + Self.lastEntriesFilter = async(filter, options) => { const conn = Self.dataSource.connector; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + const stmt = new ParameterizedSQL( `SELECT w.id AS warehouseFk, @@ -64,6 +69,6 @@ module.exports = Self => { LEFT JOIN edi.ekt ek ON b.ektFk = ek.id`); stmt.merge(conn.makeSuffix(filter)); - return conn.executeStmt(stmt); + return conn.executeStmt(stmt, myOptions); }; }; diff --git a/modules/item/back/methods/item/new.js b/modules/item/back/methods/item/new.js index e6288aede1..0771b6b14a 100644 --- a/modules/item/back/methods/item/new.js +++ b/modules/item/back/methods/item/new.js @@ -2,7 +2,7 @@ let UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethod('new', { - description: 'Create a new item and returns the new ID', + description: 'returns the created item', accessType: 'WRITE', accepts: [{ arg: 'params', @@ -19,8 +19,20 @@ module.exports = Self => { } }); - Self.new = async params => { - let validUpdateParams = [ + Self.new = async(params, options) => { + 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; + } + + const validUpdateParams = [ 'provisionalName', 'typeFk', 'intrastatFk', @@ -33,20 +45,21 @@ module.exports = Self => { throw new UserError(`You don't have enough privileges to do that`); } - let tx = await Self.beginTransaction({}); try { - let options = {transaction: tx}; - - let provisionalName = params.provisionalName; + const provisionalName = params.provisionalName; delete params.provisionalName; - let item = await Self.app.models.Item.create(params, options); + const item = await models.Item.create(params, myOptions); + + const typeTags = await models.ItemTypeTag.find({ + where: {itemTypeFk: item.typeFk} + }, myOptions); - let typeTags = await Self.app.models.ItemTypeTag.find({where: {itemTypeFk: item.typeFk}}); let query = `SET @isTriggerDisabled = TRUE`; - await Self.rawSql(query, null, options); - let nameTag = await Self.app.models.Tag.findOne({where: {name: 'Nombre temporal'}}); + await Self.rawSql(query, null, myOptions); + + let nameTag = await models.Tag.findOne({where: {name: 'Nombre temporal'}}); let newTags = []; @@ -55,17 +68,19 @@ module.exports = Self => { newTags.push({itemFk: item.id, tagFk: typeTag.tagFk, value: '', priority: typeTag.priority}); }); - await Self.app.models.ItemTag.create(newTags, options); + await models.ItemTag.create(newTags, myOptions); query = `SET @isTriggerDisabled = FALSE`; - await Self.rawSql(query, null, options); + await Self.rawSql(query, null, myOptions); query = `CALL vn.itemRefreshTags(?)`; - await Self.rawSql(query, [item.id], options); - await tx.commit(); + await Self.rawSql(query, [item.id], myOptions); + + if (tx) await tx.commit(); + return item; } catch (e) { - await tx.rollback(); + if (tx) await tx.rollback(); throw e; } }; diff --git a/modules/item/back/methods/item/regularize.js b/modules/item/back/methods/item/regularize.js index bd908c2b78..0878e32422 100644 --- a/modules/item/back/methods/item/regularize.js +++ b/modules/item/back/methods/item/regularize.js @@ -2,22 +2,26 @@ module.exports = Self => { Self.remoteMethodCtx('regularize', { description: 'Sends items to the trash', accessType: 'WRITE', - accepts: [{ - arg: 'itemFk', - type: 'number', - required: true, - description: 'The item id', - }, { - arg: 'quantity', - type: 'number', - required: true, - description: 'The visible quantity', - }, { - arg: 'warehouseFk', - type: 'number', - required: true, - description: 'The id of the warehouse where the inventory happened', - }], + accepts: [ + { + arg: 'itemFk', + type: 'number', + required: true, + description: 'The item id', + }, + { + arg: 'quantity', + type: 'number', + required: true, + description: 'The visible quantity', + }, + { + arg: 'warehouseFk', + type: 'number', + required: true, + description: 'The id of the warehouse where the inventory happened', + } + ], returns: { type: 'boolean', root: true @@ -28,75 +32,75 @@ module.exports = Self => { } }); - Self.regularize = async(ctx, itemFk, quantity, warehouseFk) => { + Self.regularize = async(ctx, itemFk, quantity, warehouseFk, options) => { const models = Self.app.models; + const myOptions = {}; + let tx; - const itemDestination = await models.ClaimDestination.findOne({ - include: { - relation: 'address', - scope: { - fields: ['clientFk'] - } - }, - where: {description: 'Corregido'} - }); + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } - let tx = await Self.beginTransaction({}); try { - let options = {transaction: tx}; + const itemDestination = await models.ClaimDestination.findOne({ + include: { + relation: 'address', + scope: { + fields: ['clientFk'] + } + }, + where: {description: 'Corregido'} + }, myOptions); - let item = await models.Item.findById(itemFk); + const item = await models.Item.findById(itemFk, null, myOptions); - let ticketFk = await getTicketId({ + let ticketId = await getTicketId({ clientFk: itemDestination.address.clientFk, addressFk: itemDestination.addressFk, warehouseFk: warehouseFk - }, options); + }, myOptions); - if (!ticketFk) { - ticketFk = await createTicket(ctx, { + if (!ticketId) { + ctx.args = { clientId: itemDestination.address().clientFk, warehouseId: warehouseFk, addressId: itemDestination.addressFk - }, options); + }; + ticketId = await createTicket(ctx, myOptions); } - res = await models.Item.getVisibleAvailable(itemFk, warehouseFk); + const res = await models.Item.getVisibleAvailable(itemFk, warehouseFk, null, myOptions); - let newQuantity = res.visible - quantity; + const newQuantity = res.visible - quantity; await models.Sale.create({ - ticketFk: ticketFk, + ticketFk: ticketId, itemFk: itemFk, concept: item.name, quantity: newQuantity, discount: 100 - }, options); + }, myOptions); - await tx.commit(); - return ticketFk; + if (tx) await tx.commit(); + + return ticketId; } catch (e) { - await tx.rollback(); + if (tx) await tx.rollback(); throw e; } - async function createTicket(ctx, params, options) { - params.shipped = new Date(); - params.landed = new Date(); - params.companyId = null; - params.agencyModeId = null; - params.routeId = null; + async function createTicket(ctx, options) { + ctx.args.shipped = new Date(); + ctx.args.landed = new Date(); + ctx.args.companyId = null; + ctx.args.agencyModeId = null; + ctx.args.routeId = null; - const ticket = await Self.app.models.Ticket.new(ctx, - params.clientId, - params.shipped, - params.landed, - params.warehouseId, - params.companyId, - params.addressId, - params.agencyModeId, - params.routeId, - options); + const ticket = await Self.app.models.Ticket.new(ctx, options); return ticket.id; } diff --git a/modules/item/back/methods/item/specs/clone.spec.js b/modules/item/back/methods/item/specs/clone.spec.js index 55142ee631..d376b9e5bc 100644 --- a/modules/item/back/methods/item/specs/clone.spec.js +++ b/modules/item/back/methods/item/specs/clone.spec.js @@ -1,4 +1,4 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('item clone()', () => { let nextItemId; @@ -8,30 +8,47 @@ describe('item clone()', () => { LEFT JOIN vn.item i2 ON i1.id + 1 = i2.id WHERE i2.id IS NULL ORDER BY i1.id LIMIT 1`; - [nextAvailableId] = await app.models.Item.rawSql(query); + [nextAvailableId] = await models.Item.rawSql(query); nextItemId = nextAvailableId.id; }); it('should clone the given item and it should have the expected id', async() => { - let itemFk = 1; - let result = await app.models.Item.clone(itemFk); + const tx = await models.FixedPrice.beginTransaction({}); - expect(result.id).toEqual(nextItemId); - expect(result.image).toBeUndefined(); - expect(result.itemTag).toBeUndefined(); - expect(result.comment).toBeUndefined(); - expect(result.description).toBeUndefined(); + try { + const options = {transaction: tx}; + const itemFk = 1; + const result = await models.Item.clone(itemFk, options); + + expect(result.id).toEqual(nextItemId); + expect(result.image).toBeUndefined(); + expect(result.itemTag).toBeUndefined(); + expect(result.comment).toBeUndefined(); + expect(result.description).toBeUndefined(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should attempt to clone the given item but give an error as it doesnt exist', async() => { - let error; - let itemFk = 999; - await app.models.Item.clone(itemFk) - .catch(e => { - expect(e.message).toContain(`This item doesn't exists`); - error = e; - }); + const tx = await models.FixedPrice.beginTransaction({}); - expect(error).toBeDefined(); + let error; + + try { + const options = {transaction: tx}; + const itemFk = 999; + await models.Item.clone(itemFk, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toContain(`This item doesn't exists`); }); }); diff --git a/modules/item/back/methods/item/specs/createIntrastat.spec.js b/modules/item/back/methods/item/specs/createIntrastat.spec.js index fb10de858a..60c85a8102 100644 --- a/modules/item/back/methods/item/specs/createIntrastat.spec.js +++ b/modules/item/back/methods/item/specs/createIntrastat.spec.js @@ -1,22 +1,25 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('createIntrastat()', () => { - let newIntrastat; - - afterAll(async done => { - await app.models.Intrastat.destroyById(newIntrastat.id); - - done(); - }); - it('should create a new intrastat', async() => { - const intrastatId = 588420239; - const description = 'Tropical Flowers'; - const itemId = 9; - newIntrastat = await app.models.Item.createIntrastat(itemId, intrastatId, description); + const tx = await models.FixedPrice.beginTransaction({}); - expect(newIntrastat.description).toEqual(description); - expect(newIntrastat.taxClassFk).toEqual(1); - expect(newIntrastat.taxCodeFk).toEqual(21); + try { + const options = {transaction: tx}; + const intrastatId = 588420239; + const description = 'Tropical Flowers'; + const itemId = 9; + + const newIntrastat = await models.Item.createIntrastat(itemId, intrastatId, description, options); + + expect(newIntrastat.description).toEqual(description); + expect(newIntrastat.taxClassFk).toEqual(1); + expect(newIntrastat.taxCodeFk).toEqual(21); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/specs/filter.spec.js b/modules/item/back/methods/item/specs/filter.spec.js index 72175ccc4e..572aa0167c 100644 --- a/modules/item/back/methods/item/specs/filter.spec.js +++ b/modules/item/back/methods/item/specs/filter.spec.js @@ -1,30 +1,63 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('item filter()', () => { it('should return 1 result filtering by id', async() => { - let filter = {}; - let result = await app.models.Item.filter({args: {filter: filter, search: 1}}); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result.length).toEqual(1); - expect(result[0].id).toEqual(1); + try { + const filter = {}; + const ctx = {args: {filter: filter, search: 1}}; + const result = await models.Item.filter(ctx, filter, options); + + expect(result.length).toEqual(1); + expect(result[0].id).toEqual(1); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return 1 result filtering by barcode', async() => { - let filter = {}; - let result = await app.models.Item.filter({args: {filter: filter, search: 4444444444}}); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result.length).toEqual(1); - expect(result[0].id).toEqual(2); + try { + const filter = {}; + const ctx = {args: {filter: filter, search: 4444444444}}; + const result = await models.Item.filter(ctx, filter, options); + + expect(result.length).toEqual(1); + expect(result[0].id).toEqual(2); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return 2 results using filter and tags', async() => { - let filter = { - order: 'isActive ASC, name', - limit: 8 - }; - let tags = [{value: 'medical box', tagFk: 58}]; - let result = await app.models.Item.filter({args: {filter: filter, typeFk: 5, tags: tags}}); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result.length).toEqual(2); + try { + const filter = { + order: 'isActive ASC, name', + limit: 8 + }; + const tags = [{value: 'medical box', tagFk: 58}]; + const ctx = {args: {filter: filter, typeFk: 5, tags: tags}}; + const result = await models.Item.filter(ctx, filter, options); + + expect(result.length).toEqual(2); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/specs/getBalance.spec.js b/modules/item/back/methods/item/specs/getBalance.spec.js index 671b8c1036..5143a346fd 100644 --- a/modules/item/back/methods/item/specs/getBalance.spec.js +++ b/modules/item/back/methods/item/specs/getBalance.spec.js @@ -1,33 +1,39 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('item getBalance()', () => { it('should return the balance lines of a client type loses in which one has highlighted true', async() => { - const activeCtx = { - accessToken: {userId: 9}, - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - const losesClientId = 111; - const ticket = await app.models.Ticket.findById(7); - const originalClientId = ticket.clientFk; - await ticket.updateAttribute('clientFk', losesClientId); + try { + const activeCtx = { + accessToken: {userId: 9}, + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); + const losesClientId = 1111; + const ticket = await models.Ticket.findById(7, null, options); - const filter = { - where: { - itemFk: 1, - warehouseFk: 1 - } - }; - const results = await app.models.Item.getBalance(filter); + await ticket.updateAttribute('clientFk', losesClientId, options); - const result = results.find(element => element.clientType == 'loses'); + const filter = { + where: { + itemFk: 1, + warehouseFk: 1 + } + }; + const results = await models.Item.getBalance(filter, options); - expect(result.highlighted).toBe(true); + const result = results.find(element => element.clientType == 'loses'); - // restores - await ticket.updateAttribute('clientFk', originalClientId); + expect(result.highlighted).toBe(true); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/specs/getCard.spec.js b/modules/item/back/methods/item/specs/getCard.spec.js new file mode 100644 index 0000000000..b604a7c1ae --- /dev/null +++ b/modules/item/back/methods/item/specs/getCard.spec.js @@ -0,0 +1,23 @@ +const models = require('vn-loopback/server/server').models; + +describe('item getCard()', () => { + it('should return the item', async() => { + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; + + try { + const itemId = 1; + + const result = await models.Item.getCard(itemId, options); + + expect(result.id).toEqual(itemId); + expect(result.itemType()).toEqual(jasmine.any(Object)); + expect(result.tags()).toEqual(jasmine.any(Array)); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); +}); diff --git a/modules/item/back/methods/item/specs/getDiary.spec.js b/modules/item/back/methods/item/specs/getDiary.spec.js deleted file mode 100644 index 2903fc426e..0000000000 --- a/modules/item/back/methods/item/specs/getDiary.spec.js +++ /dev/null @@ -1,12 +0,0 @@ -const app = require('vn-loopback/server/server'); - -describe('item getBalance()', () => { - it('should check the property balance of the 4 resultant entries', async() => { - let params = {where: {itemFk: 1, warehouseFk: 2}}; - let result = await app.models.Item.getBalance(params); - - expect(result.length).toBe(2); - expect(result[0].balance).toBe(-100); - expect(result[1].balance).toBe(-200); - }); -}); diff --git a/modules/item/back/methods/item/specs/getSummary.spec.js b/modules/item/back/methods/item/specs/getSummary.spec.js index 4a6d18e1b1..eec737d11e 100644 --- a/modules/item/back/methods/item/specs/getSummary.spec.js +++ b/modules/item/back/methods/item/specs/getSummary.spec.js @@ -1,16 +1,26 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('item getSummary()', () => { - it('should return summary with item, tags, botanical, niches, available and visible defined ', async() => { - const ctx = {req: {accessToken: {userId: 1}}}; - let result = await app.models.Item.getSummary(ctx, 1); - let keys = Object.keys(result); + it('should return summary with item, tags, botanical, available and visible defined ', async() => { + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(keys).toContain('item'); - expect(keys).toContain('tags'); - expect(keys).toContain('botanical'); - expect(keys).toContain('niches'); - expect(keys).toContain('available'); - expect(keys).toContain('visible'); + try { + const ctx = {req: {accessToken: {userId: 1}}}; + + const result = await models.Item.getSummary(ctx, 1, options); + const keys = Object.keys(result); + + expect(keys).toContain('item'); + expect(keys).toContain('tags'); + expect(keys).toContain('botanical'); + expect(keys).toContain('available'); + expect(keys).toContain('visible'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/specs/getVisibleAvailable.spec.js b/modules/item/back/methods/item/specs/getVisibleAvailable.spec.js index 77e6cea8f2..8e4864ee8f 100644 --- a/modules/item/back/methods/item/specs/getVisibleAvailable.spec.js +++ b/modules/item/back/methods/item/specs/getVisibleAvailable.spec.js @@ -1,33 +1,46 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('item getVisibleAvailable()', () => { it('should check available visible for today', async() => { - const itemFk = 1; - const warehouseFk = 1; - const dated = new Date(); - let result = await app.models.Item.getVisibleAvailable(itemFk, warehouseFk, dated); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result.available).toEqual(187); - expect(result.visible).toEqual(92); - }); + try { + const itemFk = 1; + const warehouseFk = 1; + const dated = new Date(); - it('should check available visible for no dated', async() => { - const itemFk = 1; - const warehouseFk = 1; - let result = await app.models.Item.getVisibleAvailable(itemFk, warehouseFk); + const result = await models.Item.getVisibleAvailable(itemFk, warehouseFk, dated, options); - expect(result.available).toEqual(187); - expect(result.visible).toEqual(92); + expect(result.available).toEqual(187); + expect(result.visible).toEqual(92); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should check available visible for yesterday', async() => { - const itemFk = 1; - const warehouseFk = 1; - let dated = new Date(); - dated.setDate(dated.getDate() - 1); - let result = await app.models.Item.getVisibleAvailable(itemFk, warehouseFk, dated); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result.available).toEqual(0); - expect(result.visible).toEqual(92); + try { + const itemFk = 1; + const warehouseFk = 1; + const dated = new Date(); + dated.setDate(dated.getDate() - 1); + + const result = await models.Item.getVisibleAvailable(itemFk, warehouseFk, dated, options); + + expect(result.available).toEqual(0); + expect(result.visible).toEqual(92); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/specs/getWasteByItem.spec.js b/modules/item/back/methods/item/specs/getWasteByItem.spec.js index dabad4fc67..68ba028879 100644 --- a/modules/item/back/methods/item/specs/getWasteByItem.spec.js +++ b/modules/item/back/methods/item/specs/getWasteByItem.spec.js @@ -1,14 +1,24 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Item getWasteByItem()', () => { it('should check for the waste breakdown by worker and item', async() => { - const result = await app.models.Item.getWasteByItem('CharlesXavier', 'Cymbidium'); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - const length = result.length; - const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + try { + const result = await models.Item.getWasteByItem('CharlesXavier', 'Cymbidium', options); - expect(anyResult.buyer).toEqual('CharlesXavier'); - expect(anyResult.family).toEqual('Cymbidium'); - expect(anyResult.lines.length).toBeGreaterThanOrEqual(2); + const length = result.length; + const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + + expect(anyResult.buyer).toEqual('CharlesXavier'); + expect(anyResult.family).toEqual('Cymbidium'); + expect(anyResult.lines.length).toBeGreaterThanOrEqual(2); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/specs/getWasteByWorker.spec.js b/modules/item/back/methods/item/specs/getWasteByWorker.spec.js index 9ffe96bf72..c8b9d5e156 100644 --- a/modules/item/back/methods/item/specs/getWasteByWorker.spec.js +++ b/modules/item/back/methods/item/specs/getWasteByWorker.spec.js @@ -1,13 +1,23 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Item getWasteByWorker()', () => { it('should check for the waste breakdown for every worker', async() => { - const result = await app.models.Item.getWasteByWorker(); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - const length = result.length; - const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + try { + const result = await models.Item.getWasteByWorker(options); - expect(anyResult.buyer).toMatch(/(CharlesXavier|HankPym|DavidCharlesHaller)/); - expect(anyResult.lines.length).toBeGreaterThanOrEqual(3); + const length = result.length; + const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + + expect(anyResult.buyer).toMatch(/(CharlesXavier|HankPym|DavidCharlesHaller)/); + expect(anyResult.lines.length).toBeGreaterThanOrEqual(3); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/specs/lastEntriesFilter.spec.js b/modules/item/back/methods/item/specs/lastEntriesFilter.spec.js index f64bfed8a3..6c692848b0 100644 --- a/modules/item/back/methods/item/specs/lastEntriesFilter.spec.js +++ b/modules/item/back/methods/item/specs/lastEntriesFilter.spec.js @@ -1,4 +1,4 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('item lastEntriesFilter()', () => { const minDate = new Date(value); @@ -7,18 +7,38 @@ describe('item lastEntriesFilter()', () => { maxHour.setHours(23, 59, 59, 59); it('should return one entry for a given item', async() => { - const filter = {where: {itemFk: 1, landed: {between: [minDate, maxDate]}}}; - const result = await app.models.Item.lastEntriesFilter(filter); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result.length).toEqual(1); + try { + const filter = {where: {itemFk: 1, landed: {between: [minDate, maxDate]}}}; + const result = await models.Item.lastEntriesFilter(filter, options); + + expect(result.length).toEqual(1); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return five entries for a given item', async() => { - minDate.setMonth(minDate.getMonth() - 2, 1); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - const filter = {where: {itemFk: 1, landed: {between: [minDate, maxDate]}}}; - const result = await app.models.Item.lastEntriesFilter(filter); + try { + minDate.setMonth(minDate.getMonth() - 2, 1); - expect(result.length).toEqual(5); + const filter = {where: {itemFk: 1, landed: {between: [minDate, maxDate]}}}; + const result = await models.Item.lastEntriesFilter(filter, options); + + expect(result.length).toEqual(5); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/specs/new.spec.js b/modules/item/back/methods/item/specs/new.spec.js index da2d99bb62..049ad0ff2e 100644 --- a/modules/item/back/methods/item/specs/new.spec.js +++ b/modules/item/back/methods/item/specs/new.spec.js @@ -1,45 +1,41 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('item new()', () => { - let item; - - afterAll(async done => { - try { - let sql = 'DELETE FROM vn.itemLog WHERE originFk = ?'; - await app.models.Item.rawSql(sql, [item.id]); - - sql = 'DELETE FROM vn.item WHERE id = ?'; - await app.models.Item.rawSql(sql, [item.id]); - } catch (error) { - console.error(error); - } - - done(); - }); - it('should create a new item, adding the name as a tag', async() => { - let itemParams = { - intrastatFk: 5080000, - originFk: 1, - provisionalName: 'planta', - typeFk: 2, - relevancy: 0 - }; - item = await app.models.Item.new(itemParams); - let temporalNameTag = await app.models.Tag.findOne({where: {name: 'Nombre temporal'}}); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - let temporalName = await app.models.ItemTag.findOne({ - where: { - itemFk: item.id, - tagFk: temporalNameTag.id, - } - }); - item = await app.models.Item.findById(item.id); + try { + const itemParams = { + intrastatFk: 5080000, + originFk: 1, + provisionalName: 'planta', + typeFk: 2, + relevancy: 0 + }; - expect(item.intrastatFk).toEqual(5080000); - expect(item.originFk).toEqual(1); - expect(item.typeFk).toEqual(2); - expect(item.name).toEqual('planta'); - expect(temporalName.value).toEqual('planta'); + let item = await models.Item.new(itemParams, options); + const temporalNameTag = await models.Tag.findOne({where: {name: 'Nombre temporal'}}, options); + + const temporalName = await models.ItemTag.findOne({ + where: { + itemFk: item.id, + tagFk: temporalNameTag.id, + } + }, options); + + item = await models.Item.findById(item.id, null, options); + + expect(item.intrastatFk).toEqual(5080000); + expect(item.originFk).toEqual(1); + expect(item.typeFk).toEqual(2); + expect(item.name).toEqual('planta'); + expect(temporalName.value).toEqual('planta'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/specs/regularize.spec.js b/modules/item/back/methods/item/specs/regularize.spec.js index d34dca25f4..ea0cdfa5a9 100644 --- a/modules/item/back/methods/item/specs/regularize.spec.js +++ b/modules/item/back/methods/item/specs/regularize.spec.js @@ -1,29 +1,32 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('regularize()', () => { - const itemFk = 1; - const warehouseFk = 1; - const trashAddress = 11; - let trashTicket; - - afterAll(async done => { - await app.models.Ticket.destroyById(trashTicket.id); - - done(); - }); - it('should create a new ticket and add a line', async() => { - let ctx = {req: {accessToken: {userId: 18}}}; - let res = await app.models.Item.getVisibleAvailable(itemFk, warehouseFk); - let visible = res.visible; - let saleQuantity = visible - 11; + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - let ticketFk = await app.models.Item.regularize(ctx, itemFk, 11, warehouseFk); - let sale = await app.models.Sale.findOne({where: {ticketFk: ticketFk}}); - trashTicket = await app.models.Ticket.findById(ticketFk); + try { + const ctx = {req: {accessToken: {userId: 18}}}; + const itemId = 1; + const warehouseId = 1; + const quantity = 11; + const date = undefined; - expect(sale.quantity).toEqual(saleQuantity); - expect(sale.discount).toEqual(100); - expect(trashTicket.addressFk).toEqual(trashAddress); + const res = await models.Item.getVisibleAvailable(itemId, warehouseId, date, options); + + const visible = res.visible; + const expectedQuantity = visible - quantity; + + const ticketId = await models.Item.regularize(ctx, itemId, quantity, warehouseId, options); + const sale = await models.Sale.findOne({where: {ticketFk: ticketId}}, options); + + expect(sale.quantity).toEqual(expectedQuantity); + expect(sale.discount).toEqual(100); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/specs/updateTaxes.spec.js b/modules/item/back/methods/item/specs/updateTaxes.spec.js index 7ed6fa29ae..66d2ce81c4 100644 --- a/modules/item/back/methods/item/specs/updateTaxes.spec.js +++ b/modules/item/back/methods/item/specs/updateTaxes.spec.js @@ -1,34 +1,47 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('item updateTaxes()', () => { - let taxesInFixtures = [{id: 3, taxClassFk: 1}]; - it('should throw an error if the taxClassFk is blank', async() => { + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; + let error; - let taxes = [{id: 3, taxClassFk: undefined}]; - await app.models.Item.updateTaxes(taxes) - .catch(err => { - expect(err.message).toEqual('Tax class cannot be blank'); - error = err; - }); + try { + const taxes = [{id: 3, taxClassFk: undefined}]; - expect(error).toBeDefined(); + await models.Item.updateTaxes(taxes, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toEqual('Tax class cannot be blank'); }); it('should update the tax of a given country of an item', async() => { - let taxCountry = await app.models.ItemTaxCountry.findById(3); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(taxCountry.taxClassFk).toEqual(1); + try { + let taxCountry = await models.ItemTaxCountry.findById(3, null, options); - let taxes = [{id: 3, taxClassFk: 2}]; + expect(taxCountry.taxClassFk).toEqual(1); - await app.models.Item.updateTaxes(taxes); - taxCountry = await app.models.ItemTaxCountry.findById(3); + const taxes = [{id: 3, taxClassFk: 2}]; - expect(taxCountry.taxClassFk).toEqual(2); + await models.Item.updateTaxes(taxes, options); - // restores - await app.models.Item.updateTaxes(taxesInFixtures); + taxCountry = await models.ItemTaxCountry.findById(3, null, options); + + expect(taxCountry.taxClassFk).toEqual(2); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/updateTaxes.js b/modules/item/back/methods/item/updateTaxes.js index 9b7ffd372b..70a82757a4 100644 --- a/modules/item/back/methods/item/updateTaxes.js +++ b/modules/item/back/methods/item/updateTaxes.js @@ -21,18 +21,38 @@ module.exports = Self => { } }); - Self.updateTaxes = async taxes => { - let promises = []; - for (let tax of taxes) { - if (!tax.taxClassFk) - throw new UserError('Tax class cannot be blank'); + Self.updateTaxes = async(taxes, options) => { + const myOptions = {}; + let tx; - promises.push(Self.app.models.ItemTaxCountry.update( - {id: tax.id}, - {taxClassFk: tax.taxClassFk} - )); + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const promises = []; + + for (let tax of taxes) { + if (!tax.taxClassFk) + throw new UserError('Tax class cannot be blank'); + + promises.push(Self.app.models.ItemTaxCountry.update( + {id: tax.id}, + {taxClassFk: tax.taxClassFk} + ), myOptions); + } + await Promise.all(promises); + + if (tx) await tx.commit(); + + return true; + } catch (e) { + if (tx) await tx.rollback(); + throw e; } - await Promise.all(promises); - return true; }; }; diff --git a/modules/item/back/methods/tag/filterValue.js b/modules/item/back/methods/tag/filterValue.js index 84e44e554c..062127a748 100644 --- a/modules/item/back/methods/tag/filterValue.js +++ b/modules/item/back/methods/tag/filterValue.js @@ -3,17 +3,20 @@ const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; module.exports = Self => { Self.remoteMethod('filterValue', { description: 'Returns a list of tag values', - accepts: [{ - arg: 'id', - type: 'Number', - required: true, - description: 'The tag id', - http: {source: 'path'} - }, { - arg: 'filter', - type: 'Object', - description: `Filter defining where, order, offset, and limit - must be a JSON-encoded string` - }], + accepts: [ + { + arg: 'id', + type: 'number', + required: true, + description: 'The tag id', + http: {source: 'path'} + }, + { + arg: 'filter', + type: 'object', + description: `Filter defining where, order, offset, and limit - must be a JSON-encoded string` + } + ], returns: { type: ['object'], root: true @@ -24,11 +27,16 @@ module.exports = Self => { } }); - Self.filterValue = async(id, filter) => { + Self.filterValue = async(id, filter, options) => { const conn = Self.dataSource.connector; - const tag = await Self.findById(id); + const myOptions = {}; + if (typeof options == 'object') + Object.assign(myOptions, options); + + const tag = await Self.findById(id); let stmt; + if (!tag.isFree && tag.sourceTable) { stmt = new ParameterizedSQL( `SELECT value FROM ( @@ -36,7 +44,7 @@ module.exports = Self => { } else stmt = new ParameterizedSQL(`SELECT value FROM itemTag`); - let where = filter.where; + const where = filter.where; if (where && where.value) { stmt.merge(conn.makeWhere({value: {like: `%${where.value}%`}})); stmt.merge(` @@ -46,6 +54,6 @@ module.exports = Self => { stmt.merge(conn.makeLimit(filter)); - return conn.executeStmt(stmt); + return conn.executeStmt(stmt, myOptions); }; }; diff --git a/modules/item/back/methods/tag/specs/filterValue.spec.js b/modules/item/back/methods/tag/specs/filterValue.spec.js index 8647c9fa2b..9e5cf2da26 100644 --- a/modules/item/back/methods/tag/specs/filterValue.spec.js +++ b/modules/item/back/methods/tag/specs/filterValue.spec.js @@ -1,37 +1,76 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('tag filterValue()', () => { const colorTagId = 1; it('should return a list of color values', async() => { - const filter = {limit: 5}; - const result = await app.models.Tag.filterValue(colorTagId, filter); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result.length).toEqual(5); + try { + const filter = {limit: 5}; + const result = await models.Tag.filterValue(colorTagId, filter, options); + + expect(result.length).toEqual(5); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the values matching color "Blue"', async() => { - const filter = {where: {value: 'Blue'}, limit: 5}; - const result = await app.models.Tag.filterValue(colorTagId, filter); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result.length).toEqual(2); - expect(result[0].value).toEqual('Blue'); - expect(result[1].value).toEqual('Blue/Silver'); + try { + const filter = {where: {value: 'Blue'}, limit: 5}; + const result = await models.Tag.filterValue(colorTagId, filter, options); + + expect(result.length).toEqual(2); + expect(result[0].value).toEqual('Blue'); + expect(result[1].value).toEqual('Blue/Silver'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the values matching color "Blue/Silver"', async() => { - const filter = {where: {value: 'Blue/Silver'}, limit: 5}; - const result = await app.models.Tag.filterValue(colorTagId, filter); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result.length).toEqual(1); - expect(result[0].value).toEqual('Blue/Silver'); + try { + const filter = {where: {value: 'Blue/Silver'}, limit: 5}; + const result = await models.Tag.filterValue(colorTagId, filter, options); + + expect(result.length).toEqual(1); + expect(result[0].value).toEqual('Blue/Silver'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the values matching color "Silver"', async() => { - const filter = {where: {value: 'Silver'}, limit: 5}; - const result = await app.models.Tag.filterValue(colorTagId, filter); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result.length).toEqual(2); - expect(result[0].value).toEqual('Silver'); - expect(result[1].value).toEqual('Blue/Silver'); + try { + const filter = {where: {value: 'Silver'}, limit: 5}; + const result = await models.Tag.filterValue(colorTagId, filter, options); + + expect(result.length).toEqual(2); + expect(result[0].value).toEqual('Silver'); + expect(result[1].value).toEqual('Blue/Silver'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/model-config.json b/modules/item/back/model-config.json index 9f101f9c7a..6e171e9b09 100644 --- a/modules/item/back/model-config.json +++ b/modules/item/back/model-config.json @@ -26,9 +26,6 @@ "ItemLog": { "dataSource": "vn" }, - "ItemNiche": { - "dataSource": "vn" - }, "ItemPlacement": { "dataSource": "vn" }, @@ -65,18 +62,6 @@ "Tag": { "dataSource": "vn" }, - "TaxClass": { - "dataSource": "vn" - }, - "TaxClassCode": { - "dataSource": "vn" - }, - "TaxCode": { - "dataSource": "vn" - }, - "TaxType": { - "dataSource": "vn" - }, "FixedPrice": { "dataSource": "vn" } diff --git a/modules/item/back/models/item-botanical.json b/modules/item/back/models/item-botanical.json index 5412181452..6c465f0eee 100644 --- a/modules/item/back/models/item-botanical.json +++ b/modules/item/back/models/item-botanical.json @@ -3,8 +3,7 @@ "base": "Loggable", "log": { "model": "ItemLog", - "relation": "item", - "showField": "botanical" + "relation": "item" }, "options": { "mysql": { diff --git a/modules/item/back/models/item-niche.js b/modules/item/back/models/item-niche.js deleted file mode 100644 index b9e3888815..0000000000 --- a/modules/item/back/models/item-niche.js +++ /dev/null @@ -1,9 +0,0 @@ -const UserError = require('vn-loopback/util/user-error'); - -module.exports = Self => { - Self.rewriteDbError(function(err) { - if (err.code === 'ER_DUP_ENTRY') - return new UserError(`The warehouse can't be repeated`); - return err; - }); -}; diff --git a/modules/item/back/models/item-niche.json b/modules/item/back/models/item-niche.json deleted file mode 100644 index 260eb07b90..0000000000 --- a/modules/item/back/models/item-niche.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "ItemNiche", - "base": "Loggable", - "log": { - "model": "ItemLog", - "relation": "item", - "showField": "code" - }, - "options": { - "mysql": { - "table": "itemPlacement" - } - }, - "properties": { - "id": { - "type": "Number", - "id": 1, - "description": "Identifier" - }, - "warehouseFk": { - "type": "Number", - "description": "Identifier" - }, - "code": { - "type": "String", - "required": true - } - }, - "relations": { - "item": { - "type": "belongsTo", - "model": "Item", - "foreignKey": "itemFk" - }, - "warehouse": { - "type": "belongsTo", - "model": "Warehouse", - "foreignKey": "warehouseFk", - "required": true - } - } -} diff --git a/modules/item/back/models/item.json b/modules/item/back/models/item.json index ce03ba1ea5..1c09ca4f4a 100644 --- a/modules/item/back/models/item.json +++ b/modules/item/back/models/item.json @@ -196,21 +196,18 @@ "model": "ItemTaxCountry", "foreignKey": "itemFk" }, - "itemNiche": { - "type": "hasMany", - "model": "ItemNiche", - "foreignKey": "itemFk" - }, "packaging": { "type": "hasOne", "model": "Packaging", "foreignKey": "itemFk" } }, - "scope": { - "where": { - "name": { - "neq": "" + "scopes": { + "withName": { + "where": { + "name": { + "neq": "" + } } } } diff --git a/modules/item/front/fixed-price/index.html b/modules/item/front/fixed-price/index.html index 99b8cea754..f7819de371 100644 --- a/modules/item/front/fixed-price/index.html +++ b/modules/item/front/fixed-price/index.html @@ -51,7 +51,7 @@ class="dense" ng-if="!price.itemFk" vn-focus - url="Items" + url="Items/withName" ng-model="price.itemFk" show-field="name" value-field="id" diff --git a/modules/item/front/index.js b/modules/item/front/index.js index 8cb22ef40e..c328b1c8d8 100644 --- a/modules/item/front/index.js +++ b/modules/item/front/index.js @@ -16,7 +16,6 @@ import './log'; import './request'; import './request-search-panel'; import './last-entries'; -import './niche'; import './botanical'; import './barcode'; import './summary'; diff --git a/modules/item/front/index/index.html b/modules/item/front/index/index.html index bcebaee484..5b1e7fdc8a 100644 --- a/modules/item/front/index/index.html +++ b/modules/item/front/index/index.html @@ -18,7 +18,6 @@ Description Stems Size - Niche Type Category Intrastat @@ -27,6 +26,7 @@ Density Multiplier Active + Landed @@ -63,7 +63,6 @@
{{::item.stems}} {{::item.size}} - {{::item.niche}} {{::item.typeName}} @@ -89,6 +88,7 @@ ng-model="::item.isActive">
+ {{::item.landed | date:'dd/MM/yyyy'}} Ig Warehouse - Landed + Landed Entry P.P.U P.P.P @@ -49,7 +49,7 @@ {{::entry.warehouse| dashIfEmpty}} - {{::entry.landed | date:'dd/MM/yyyy HH:mm'}} + {{::entry.landed | date:'dd/MM/yyyy HH:mm'}} - - - - - -
- - - - - - - - - - - - - - - - - - - - - - -
\ No newline at end of file diff --git a/modules/item/front/niche/index.js b/modules/item/front/niche/index.js deleted file mode 100644 index 51621b7148..0000000000 --- a/modules/item/front/niche/index.js +++ /dev/null @@ -1,17 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; - -export default class Controller extends Section { - onSubmit() { - this.$.watcher.check(); - this.$.model.save().then(() => { - this.$.watcher.notifySaved(); - this.$.watcher.updateOriginalData(); - }); - } -} - -ngModule.vnComponent('vnItemNiche', { - template: require('./index.html'), - controller: Controller -}); diff --git a/modules/item/front/routes.json b/modules/item/front/routes.json index f6b3bfe293..8f3e037469 100644 --- a/modules/item/front/routes.json +++ b/modules/item/front/routes.json @@ -15,7 +15,6 @@ {"state": "item.card.basicData", "icon": "settings"}, {"state": "item.card.tags", "icon": "icon-tags"}, {"state": "item.card.tax", "icon": "icon-tax"}, - {"state": "item.card.niche", "icon": "place"}, {"state": "item.card.botanical", "icon": "local_florist"}, {"state": "item.card.itemBarcode", "icon": "icon-barcode"}, {"state": "item.card.diary", "icon": "icon-transaction"}, @@ -79,16 +78,6 @@ "description": "Tax", "acl": ["administrative","buyer"] }, - { - "url" : "/niche", - "state": "item.card.niche", - "component": "vn-item-niche", - "description": "Niches", - "params": { - "item": "$ctrl.item" - }, - "acl": ["buyer","replenisher"] - }, { "url" : "/botanical", "state": "item.card.botanical", diff --git a/modules/item/front/search-panel/locale/es.yml b/modules/item/front/search-panel/locale/es.yml index 197da0695c..67a5200d7e 100644 --- a/modules/item/front/search-panel/locale/es.yml +++ b/modules/item/front/search-panel/locale/es.yml @@ -1,6 +1,6 @@ Ink: Tinta Origin: Origen -Producer: Productor. +Producer: Productor With visible: Con visible Field: Campo More fields: Más campos diff --git a/modules/item/front/summary/index.html b/modules/item/front/summary/index.html index 90d51bb636..b5ea79efb5 100644 --- a/modules/item/front/summary/index.html +++ b/modules/item/front/summary/index.html @@ -138,24 +138,6 @@ value="{{tax.taxClass.description}}"> - -

- - Niche - -

-

- Niche -

- - -

{ } }); - Self.deleteOrders = async(deletes, options) => { + Self.deleteOrders = async(deletes = [], options) => { const models = Self.app.models; let myOptions = {}; diff --git a/modules/monitor/back/methods/sales-monitor/salesFilter.js b/modules/monitor/back/methods/sales-monitor/salesFilter.js index b84dff8a07..6483a906ac 100644 --- a/modules/monitor/back/methods/sales-monitor/salesFilter.js +++ b/modules/monitor/back/methods/sales-monitor/salesFilter.js @@ -223,7 +223,8 @@ module.exports = Self => { MINUTE(z.hour) AS zoneMinute, z.name AS zoneName, z.id AS zoneFk, - CAST(z.hour AS CHAR) AS hour + CAST(z.hour AS CHAR) AS hour, + TIME_FORMAT(zed.etc, '%H:%i') AS practicalHour FROM ticket t LEFT JOIN invoiceOut io ON t.refFk = io.ref LEFT JOIN zone z ON z.id = t.zoneFk @@ -235,7 +236,8 @@ module.exports = Self => { LEFT JOIN state st ON st.id = ts.stateFk LEFT JOIN client c ON c.id = t.clientFk LEFT JOIN worker wk ON wk.id = c.salesPersonFk - LEFT JOIN account.user u ON u.id = wk.userFk`); + LEFT JOIN account.user u ON u.id = wk.userFk + LEFT JOIN zoneEstimatedDelivery zed ON zed.zoneFk = t.zoneFk`); if (args.orderFk) { stmt.merge({ @@ -254,7 +256,7 @@ module.exports = Self => { ENGINE = MEMORY SELECT f.id ticketFk, f.clientFk, f.warehouseFk, f.shipped FROM tmp.filter f - LEFT JOIN alertLevel al ON al.alertLevel = f.alertLevel + LEFT JOIN alertLevel al ON al.id = f.alertLevel WHERE (al.code = 'FREE' OR f.alertLevel IS NULL) AND f.shipped >= CURDATE()`); stmts.push('CALL ticket_getProblems(FALSE)'); @@ -264,38 +266,33 @@ module.exports = Self => { FROM tmp.filter f LEFT JOIN tmp.ticket_problems tp ON tp.ticketFk = f.id`); - if (args.problems != undefined && (!args.from && !args.to)) + const hasProblems = args.problems; + if (hasProblems != undefined && (!args.from && !args.to)) throw new UserError('Choose a date range or days forward'); - let condition; - let hasProblem; - let range; - let hasWhere; - switch (args.problems) { - case true: - condition = `or`; - hasProblem = true; - range = 0; - hasWhere = true; - break; - - case false: - condition = `and`; - hasProblem = null; - range = null; - hasWhere = true; - break; + let problemsFilter; + if (hasProblems === true) { + problemsFilter = {or: [ + {'tp.isFreezed': true}, + {'tp.risk': {gt: 0}}, + {'tp.hasTicketRequest': true}, + {'tp.hasComponentLack': true}, + {'tp.isTaxDataChecked': false}, + {'tp.isAvailable': false} + ]}; + } else if (hasProblems === false) { + problemsFilter = {and: [ + {'tp.isFreezed': false}, + {'tp.risk': 0}, + {'tp.hasTicketRequest': false}, + {'tp.hasComponentLack': false}, + {'tp.isTaxDataChecked': true}, + {'tp.isAvailable': true} + ]}; } - let problems = {[condition]: [ - {'tp.isFreezed': hasProblem}, - {'tp.risk': hasProblem}, - {'tp.hasTicketRequest': hasProblem}, - {'tp.isAvailable': range} - ]}; - - if (hasWhere) - stmt.merge(conn.makeWhere(problems)); + if (problemsFilter) + stmt.merge(conn.makeWhere(problemsFilter)); stmt.merge(conn.makeOrderBy(filter.order)); stmt.merge(conn.makeLimit(filter)); diff --git a/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js b/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js index 54615b22b2..53cd9941ef 100644 --- a/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js +++ b/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js @@ -23,7 +23,7 @@ describe('SalesMonitor salesFilter()', () => { const filter = {}; const result = await app.models.SalesMonitor.salesFilter(ctx, filter); - expect(result.length).toEqual(4); + expect(result.length).toEqual(9); }); it('should return the tickets matching the problems on false', async() => { @@ -41,7 +41,7 @@ describe('SalesMonitor salesFilter()', () => { const filter = {}; const result = await app.models.SalesMonitor.salesFilter(ctx, filter); - expect(result.length).toEqual(6); + expect(result.length).toEqual(0); }); it('should return the tickets matching the problems on null', async() => { @@ -103,4 +103,40 @@ describe('SalesMonitor salesFilter()', () => { expect(result.length).toEqual(4); }); + + it('should return the tickets sorted by problems descendant', async() => { + const yesterday = new Date(); + yesterday.setDate(yesterday.getDate() - 1); + yesterday.setHours(0, 0, 0, 0); + const today = new Date(); + today.setHours(23, 59, 59, 59); + + const ctx = {req: {accessToken: {userId: 18}}, args: {}}; + const filter = {order: 'totalProblems DESC'}; + const result = await app.models.SalesMonitor.salesFilter(ctx, filter); + + const firstTicket = result.shift(); + const secondTicket = result.shift(); + + expect(firstTicket.totalProblems).toEqual(3); + expect(secondTicket.totalProblems).toEqual(2); + }); + + it('should return the tickets sorted by problems ascendant', async() => { + const yesterday = new Date(); + yesterday.setDate(yesterday.getDate() - 1); + yesterday.setHours(0, 0, 0, 0); + const today = new Date(); + today.setHours(23, 59, 59, 59); + + const ctx = {req: {accessToken: {userId: 18}}, args: {}}; + const filter = {order: 'totalProblems ASC'}; + const result = await app.models.SalesMonitor.salesFilter(ctx, filter); + + const firstTicket = result.shift(); + const secondTicket = result.shift(); + + expect(firstTicket.totalProblems).toEqual(null); + expect(secondTicket.totalProblems).toEqual(null); + }); }); diff --git a/modules/monitor/front/index/locale/es.yml b/modules/monitor/front/index/locale/es.yml index 41d29064d3..4eef3c93f2 100644 --- a/modules/monitor/front/index/locale/es.yml +++ b/modules/monitor/front/index/locale/es.yml @@ -5,4 +5,7 @@ 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 -Minimize/Maximize: Minimizar/Maximizar \ No newline at end of file +Minimize/Maximize: Minimizar/Maximizar +Problems: Problemas +Theoretical: Teórica +Practical: Práctica \ No newline at end of file diff --git a/modules/monitor/front/index/tickets/index.html b/modules/monitor/front/index/tickets/index.html index f61c62f167..82adf27656 100644 --- a/modules/monitor/front/index/tickets/index.html +++ b/modules/monitor/front/index/tickets/index.html @@ -33,16 +33,17 @@ - + Problems Client Salesperson Date - Hour - Closure + Prep. + Theoretical + Practical Province State Zone - Total + Total @@ -77,6 +78,7 @@ @@ -111,6 +113,7 @@ {{::ticket.shipped | date: 'HH:mm'}} {{::ticket.zoneLanding | date: 'HH:mm'}} + {{::ticket.practicalHour | date: 'HH:mm'}} {{::ticket.province}} - + {{::(ticket.totalWithVat ? ticket.totalWithVat : 0) | currency: 'EUR': 2}} diff --git a/modules/monitor/front/index/tickets/index.js b/modules/monitor/front/index/tickets/index.js index 26581f1f60..d8832d1b54 100644 --- a/modules/monitor/front/index/tickets/index.js +++ b/modules/monitor/front/index/tickets/index.js @@ -74,12 +74,8 @@ export default class Controller extends Section { return {'t.shipped': { between: this.dateRange(value)} }; - case 'id': - case 'refFk': case 'zoneFk': case 'nickname': - case 'agencyModeFk': - case 'warehouseFk': return {[`t.${param}`]: value}; } } diff --git a/modules/monitor/front/index/tickets/style.scss b/modules/monitor/front/index/tickets/style.scss index 2638007e86..b767aa57c8 100644 --- a/modules/monitor/front/index/tickets/style.scss +++ b/modules/monitor/front/index/tickets/style.scss @@ -32,4 +32,8 @@ vn-monitor-sales-tickets { vn-tbody a[ng-repeat].vn-tr:focus { background-color: $color-primary-light } + + .highRisk i { + color: $color-alert + } } \ No newline at end of file diff --git a/modules/order/back/methods/order/getItemTypeAvailable.js b/modules/order/back/methods/order/getItemTypeAvailable.js index 56f6a8c0ec..906095f417 100644 --- a/modules/order/back/methods/order/getItemTypeAvailable.js +++ b/modules/order/back/methods/order/getItemTypeAvailable.js @@ -28,30 +28,57 @@ module.exports = Self => { }); Self.getItemTypeAvailable = async(orderId, itemCategoryId) => { - let stmts = []; + const stmts = []; let stmt; - let order = await app.models.Order.findById(orderId); + const order = await app.models.Order.findById(orderId); stmt = new ParameterizedSQL('call vn.available_calc(?, ?, ?)', [ order.landed, order.addressFk, order.agencyModeFk ]); stmts.push(stmt); - stmt = new ParameterizedSQL(` - SELECT it.id, it.name, ic.name categoryName + + stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.item'); + + stmt = new ParameterizedSQL( + `CREATE TEMPORARY TABLE tmp.item + (PRIMARY KEY (itemFk)) ENGINE = MEMORY + SELECT DISTINCT + i.id AS itemFk, + it.id AS typeFk, + it.name, + ic.name AS categoryName FROM tmp.availableCalc ac JOIN cache.available a ON a.calc_id = ac.calcFk - JOIN item i ON i.id = a.item_id - JOIN itemType it ON it.id = i.typeFk - JOIN itemCategory ic ON ic.id = it.categoryFk - WHERE it.categoryFk = ? - GROUP BY it.id`, [itemCategoryId] + JOIN vn.item i ON i.id = a.item_id + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + WHERE it.categoryFk = ?`, [itemCategoryId] ); - let categoriesIndex = stmts.push(stmt) - 1; + stmts.push(stmt); - let sql = ParameterizedSQL.join(stmts, ';'); - let result = await Self.rawStmt(sql); + stmt = new ParameterizedSQL( + 'CALL vn.catalog_calculate(?, ?, ?)', [ + order.landed, + order.addressFk, + order.agencyModeFk, + ] + ); + stmts.push(stmt); + + stmt = new ParameterizedSQL(` + SELECT i.typeFk AS id, i.name, i.categoryName + FROM tmp.item i + JOIN tmp.ticketCalculateItem tci ON tci.itemFk = i.itemFk + GROUP BY i.typeFk` + ); + const categoriesIndex = stmts.push(stmt) - 1; + + stmts.push('DROP TEMPORARY TABLE tmp.item'); + + const sql = ParameterizedSQL.join(stmts, ';'); + const result = await Self.rawStmt(sql); return result[categoriesIndex]; }; diff --git a/modules/order/back/methods/order/specs/summary.spec.js b/modules/order/back/methods/order/specs/summary.spec.js index f6f917edea..f23ad570e1 100644 --- a/modules/order/back/methods/order/specs/summary.spec.js +++ b/modules/order/back/methods/order/specs/summary.spec.js @@ -5,7 +5,7 @@ describe('order summary()', () => { let result = await app.models.Order.summary(1); expect(result.id).toEqual(1); - expect(result.clientFk).toEqual(101); + expect(result.clientFk).toEqual(1101); }); it('should return a summary object containing sales from 1 order', async() => { diff --git a/modules/order/front/basic-data/index.html b/modules/order/front/basic-data/index.html index 7ad73e1be0..109168e29d 100644 --- a/modules/order/front/basic-data/index.html +++ b/modules/order/front/basic-data/index.html @@ -35,7 +35,8 @@ search-function="$search" show-field="nickname" value-field="id" - ng-model="$ctrl.order.addressFk"> + ng-model="$ctrl.order.addressFk" + on-change="$ctrl.getAvailableAgencies()"> {{::nickname}} @@ -43,17 +44,16 @@ + ng-model="$ctrl.order.landed" + on-change="$ctrl.getAvailableAgencies()"> - {{::id}}: {{::name}} diff --git a/modules/order/front/basic-data/index.js b/modules/order/front/basic-data/index.js index 3719eb42fc..16a3cea5e3 100644 --- a/modules/order/front/basic-data/index.js +++ b/modules/order/front/basic-data/index.js @@ -20,6 +20,32 @@ class Controller extends Section { } }); } + + 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', { diff --git a/modules/order/front/basic-data/index.spec.js b/modules/order/front/basic-data/index.spec.js index 4442fadccb..01009d0850 100644 --- a/modules/order/front/basic-data/index.spec.js +++ b/modules/order/front/basic-data/index.spec.js @@ -3,13 +3,15 @@ import './index.js'; describe('Order', () => { describe('Component vnOrderBasicData', () => { let $httpBackend; + let $httpParamSerializer; let controller; let $scope; beforeEach(ngModule('order')); - beforeEach(inject(($compile, _$httpBackend_, $rootScope) => { + beforeEach(inject(($compile, _$httpBackend_, $rootScope, _$httpParamSerializer_) => { $httpBackend = _$httpBackend_; + $httpParamSerializer = _$httpParamSerializer_; $scope = $rootScope.$new(); $httpBackend.whenRoute('GET', 'Addresses') @@ -30,10 +32,35 @@ describe('Order', () => { describe('constructor()', () => { it('should update the address after the client changes', async() => { - controller.selection = {id: 2, defaultAddressFk: 2}; + const addressId = 999; + const id = 444; + + controller.selection = {id: id, defaultAddressFk: addressId}; $scope.$digest(); - expect(controller.order.addressFk).toEqual(2); + 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 = new Date(); + + 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/create/card.js b/modules/order/front/create/card.js index de04484bda..315cc82557 100644 --- a/modules/order/front/create/card.js +++ b/modules/order/front/create/card.js @@ -37,7 +37,7 @@ class Controller extends Component { }; filter = encodeURIComponent(JSON.stringify(filter)); let query = `Clients?filter=${filter}`; - this.$http.get(query).then(res=> { + this.$http.get(query).then(res => { if (res.data) { let client = res.data[0]; let defaultAddress = client.defaultAddress; diff --git a/modules/order/front/create/card.spec.js b/modules/order/front/create/card.spec.js index 99e8c1f8ae..e37900af6b 100644 --- a/modules/order/front/create/card.spec.js +++ b/modules/order/front/create/card.spec.js @@ -54,17 +54,17 @@ describe('Order', () => { describe('set addressFk', () => { it(`should set agencyModeFk property to null and addressFk to a value`, () => { - controller.addressFk = 101; + controller.addressFk = 1101; - expect(controller.addressFk).toEqual(101); + 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 = 101; - controller.order.landed = 101; + controller.order.addressFk = 1101; + controller.order.landed = 1101; $httpBackend.whenRoute('GET', 'Agencies/landsThatDay') .respond({data: 1}); @@ -85,13 +85,13 @@ describe('Order', () => { describe('createOrder()', () => { it(`should make a query, call vnApp.showSuccess and $state.go if the response is defined`, () => { - controller.order.landed = 101; - controller.order.addressFk = 101; - controller.order.agencyModeFk = 101; + 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: 101, addressId: 101, agencyModeId: 101}).respond(200, 1); + $httpBackend.expect('POST', 'Orders/new', {landed: 1101, addressId: 1101, agencyModeId: 1101}).respond(200, 1); controller.createOrder(); $httpBackend.flush(); diff --git a/modules/order/front/prices-popover/index.spec.js b/modules/order/front/prices-popover/index.spec.js index 653682e52c..734a9e254a 100644 --- a/modules/order/front/prices-popover/index.spec.js +++ b/modules/order/front/prices-popover/index.spec.js @@ -138,7 +138,7 @@ describe('Order', () => { controller.prices = [ {warehouseFk: 1, grouping: 10, quantity: 0}, - {warehouseFk: 1, grouping: 100, quantity: 101} + {warehouseFk: 1, grouping: 100, quantity: 1101} ]; controller.submit(); diff --git a/modules/order/front/routes.json b/modules/order/front/routes.json index 7ebba32c7f..c22ff24d17 100644 --- a/modules/order/front/routes.json +++ b/modules/order/front/routes.json @@ -22,17 +22,20 @@ "abstract": true, "component": "vn-order", "description": "Orders" - }, { + }, + { "url": "/index?q", "state": "order.index", "component": "vn-order-index", "description": "Orders" - }, { + }, + { "url": "/:id", "state": "order.card", "abstract": true, "component": "vn-order-card" - }, { + }, + { "url": "/summary", "state": "order.card.summary", "component": "vn-order-summary", @@ -40,7 +43,8 @@ "params": { "order": "$ctrl.order" } - }, { + }, + { "url": "/catalog?q&categoryId&typeId&tagGroups", "state": "order.card.catalog", "component": "vn-order-catalog", @@ -48,7 +52,8 @@ "params": { "order": "$ctrl.order" } - }, { + }, + { "url": "/volume", "state": "order.card.volume", "component": "vn-order-volume", @@ -56,7 +61,8 @@ "params": { "order": "$ctrl.order" } - }, { + }, + { "url": "/line", "state": "order.card.line", "component": "vn-order-line", @@ -64,12 +70,14 @@ "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", diff --git a/modules/route/back/methods/route/summary.js b/modules/route/back/methods/route/summary.js index ad65edb4a3..10cfe38ee8 100644 --- a/modules/route/back/methods/route/summary.js +++ b/modules/route/back/methods/route/summary.js @@ -48,12 +48,12 @@ module.exports = Self => { scope: { fields: ['id', 'm3', 'numberPlate'] } - } - ], + }, + ] }; summary.route = await Self.app.models.Route.findOne(filter); - summary.tickets = await Self.app.models.Route.getTickets({id: id}); + summary.tickets = await Self.app.models.Route.getTickets({id: id, order: 'priority ASC'}); return summary; }; diff --git a/modules/route/front/index/index.spec.js b/modules/route/front/index/index.spec.js index 8143f11572..80e660b761 100644 --- a/modules/route/front/index/index.spec.js +++ b/modules/route/front/index/index.spec.js @@ -133,7 +133,7 @@ describe('Component vnRouteIndex', () => { }); describe('insert()', () => { - it('should make a HTTP patch query and then call both refresh and showSuccess methods', () => { + it('should perform a HTTP patch query and then call both refresh and showSuccess methods', () => { jest.spyOn(controller.$.model, 'refresh').mockReturnThis(); jest.spyOn(controller.vnApp, 'showSuccess'); diff --git a/modules/route/front/tickets/index.js b/modules/route/front/tickets/index.js index ffae4bac52..efb3d1498f 100644 --- a/modules/route/front/tickets/index.js +++ b/modules/route/front/tickets/index.js @@ -131,6 +131,7 @@ class Controller extends Section { .then(() => { this.$.model.data = this.$.model.data.concat(tickets); this.vnApp.showSuccess(this.$t('Data saved!')); + this.updateVolume(); }); } @@ -157,8 +158,7 @@ class Controller extends Section { const query = `Routes/${this.route.id}/insertTicket`; return this.$http.patch(query, {ticketId}).then(() => { this.vnApp.showSuccess(this.$t('Data saved!')); - this.$.model.refresh(); - this.card.reload(); + this.updateVolume(); }).catch(error => { if (error.status == 404) return this.vnApp.showError(this.$t('Ticket not found')); diff --git a/modules/route/front/tickets/index.spec.js b/modules/route/front/tickets/index.spec.js index 1fcf924489..4fafc47509 100644 --- a/modules/route/front/tickets/index.spec.js +++ b/modules/route/front/tickets/index.spec.js @@ -129,19 +129,20 @@ describe('Route', () => { describe('removeTicketFromRoute()', () => { it('should perform a patch query then call showSuccess and updateVolume methods', () => { - jest.spyOn(controller, 'updateVolume').mockReturnThis(); + controller.$params = {id: 1101}; + jest.spyOn(controller.vnApp, 'showSuccess'); jest.spyOn(controller.$.model, 'remove'); let ticketId = 1; controller.selectedTicket = ticketId; + $httpBackend.whenPOST(`Routes/${controller.$params.id}/updateVolume`).respond(200); $httpBackend.expectPATCH(`Tickets/${ticketId}/`).respond('ok'); controller.removeTicketFromRoute(); $httpBackend.flush(); expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Ticket removed from route'); - expect(controller.updateVolume).toHaveBeenCalledWith(); }); }); @@ -196,9 +197,8 @@ describe('Route', () => { describe('setTicketsRoute()', () => { it('should perform a POST query to add tickets to the route', () => { - controller.$.model = {data: [ - {id: 1, checked: false} - ]}; + controller.$params = {id: 1101}; + controller.$.model.data = [{id: 1, checked: false}]; const existingTicket = controller.$.model.data[0]; @@ -217,7 +217,8 @@ describe('Route', () => { {id: 5} ]; - $httpBackend.expectPOST(`Tickets/crud`).respond(); + $httpBackend.whenPOST(`Routes/${controller.$params.id}/updateVolume`).respond(200); + $httpBackend.expectPOST('Tickets/crud').respond(); controller.setTicketsRoute(); $httpBackend.flush(); @@ -273,11 +274,15 @@ describe('Route', () => { describe('insert()', () => { it('should make a HTTP patch query and then call both refresh and showSuccess methods', () => { + controller.$params = {id: 1101}; + jest.spyOn(controller.$.model, 'refresh').mockReturnThis(); jest.spyOn(controller.vnApp, 'showSuccess'); const ticketId = 11; const data = {ticketId}; + + $httpBackend.whenPOST(`Routes/${controller.$params.id}/updateVolume`).respond(200); $httpBackend.expect('PATCH', `Routes/1/insertTicket`, data).respond(); controller.insert(ticketId); $httpBackend.flush(); diff --git a/modules/supplier/back/models/supplier-account.js b/modules/supplier/back/models/supplier-account.js index 85bf375101..ec571464a7 100644 --- a/modules/supplier/back/models/supplier-account.js +++ b/modules/supplier/back/models/supplier-account.js @@ -1,4 +1,5 @@ const validateIban = require('vn-loopback/util/validateIban'); +const LoopBackContext = require('loopback-context'); module.exports = Self => { Self.validateAsync('iban', ibanValidation, { @@ -19,4 +20,16 @@ module.exports = Self => { err(); done(); } + Self.observe('after save', async ctx => { + const loopBackContext = LoopBackContext.getCurrentContext(); + const models = Self.app.models; + const user = await models.user.findById(loopBackContext.active.accessToken.userId); + const bankEntity = await models.BankEntity.findById(ctx.instance.bankEntityFk); + await Self.app.models.Mail.create({ + sender: 'finanzas@verdnatura.es', + subject: 'Añadida cuenta bancaria al proveedor' + ctx.instance.supplierFk, + body: user.username + ' ha añadido: ' + + ctx.instance.iban + ', entidad: ' + bankEntity.name + ', bic: ' + bankEntity.bic + }); + }); }; diff --git a/modules/supplier/front/account/index.html b/modules/supplier/front/account/index.html index 7264f6f2c7..5f9d7c82a5 100644 --- a/modules/supplier/front/account/index.html +++ b/modules/supplier/front/account/index.html @@ -15,30 +15,40 @@
- + - + + + + - - - - - + + + + + - \ No newline at end of file + on-accept="$ctrl.onAccept($data)"> + + + + \ No newline at end of file diff --git a/modules/supplier/front/account/index.js b/modules/supplier/front/account/index.js index 26f4af9887..6c6e77d2ee 100644 --- a/modules/supplier/front/account/index.js +++ b/modules/supplier/front/account/index.js @@ -10,6 +10,14 @@ class Controller extends Section { fields: ['countryFk', 'id', 'name', 'bic'] } }; + const filter = { + where: {code: 'wireTransfer'} + }; + + this.$http.get(`payMethods/findOne`, {filter}) + .then(res => { + this.wireTransferFk = res.data.id; + }); } add() { @@ -18,32 +26,24 @@ class Controller extends Section { }); } - onResponse(response) { - const data = this.$.model.data; - const supplierAccount = data[this.currentRowIndex]; - supplierAccount.bankEntityFk = response.id; - } - - showBankEntity(event, $index) { - if (event.defaultPrevented) return; - event.preventDefault(); - this.currentRowIndex = $index; - this.$.bankEntity.open(); - } - - onBankEntityAccept() { - const query = `SupplierAccounts/${this.$params.id}/createBankEntity`; - return this.$http.patch(query, this.newBankEntity) - .then(res => this.supplierAccount.bankEntityFk = res.data.id); + onAccept(data) { + const accounts = this.supplierAccounts; + const targetAccount = accounts[data.index]; + targetAccount.bankEntityFk = data.id; } onSubmit() { this.$.watcher.check(); - this.$.model.save().then(() => { - this.$.watcher.notifySaved(); - this.$.watcher.updateOriginalData(); - this.card.reload(); - }); + return this.$.model.save() + .then(() => { + this.$.watcher.notifySaved(); + this.$.watcher.updateOriginalData(); + return this.card.reload(); + }) + .then(() => { + if (this.supplier.payMethodFk != this.wireTransferFk) + this.$.payMethodToTransfer.show(); + }); } } diff --git a/modules/supplier/front/account/index.spec.js b/modules/supplier/front/account/index.spec.js index ca16712078..5c824907f6 100644 --- a/modules/supplier/front/account/index.spec.js +++ b/modules/supplier/front/account/index.spec.js @@ -1,19 +1,22 @@ import './index.js'; +import watcher from 'core/mocks/watcher'; +import crudModel from 'core/mocks/crud-model'; describe('Supplier Component vnSupplierAccount', () => { let $scope; - let $element; let controller; - let $httpBackend; beforeEach(ngModule('supplier')); beforeEach(inject(($componentController, $rootScope, _$httpBackend_) => { - $httpBackend = _$httpBackend_; $scope = $rootScope.$new(); + $scope.model = crudModel; + $scope.watcher = watcher; + $scope.bankEntity = { open: () => {} }; - $element = angular.element(''); + + const $element = angular.element(''); controller = $componentController('vnSupplierAccount', {$element, $scope}); controller.supplierAccount = { supplierFk: 442, @@ -21,50 +24,46 @@ describe('Supplier Component vnSupplierAccount', () => { }; })); - describe('showBankEntity()', () => { - it('should do nothing if it default is prevented', () => { - const event = { - defaultPrevented: true, - preventDefault: () => {} + describe('onAccept()', () => { + it('should set the created bank entity id into the target account', () => { + controller.supplierAccounts = [{}, {}, {}]; + + const data = { + id: 999, + index: 1 }; - jest.spyOn(event, 'preventDefault'); - jest.spyOn(controller.$.bankEntity, 'open'); - controller.showBankEntity(event); + controller.onAccept(data); - expect(event.preventDefault).not.toHaveBeenCalledWith(); - expect(controller.$.bankEntity.open).not.toHaveBeenCalledWith(); + const targetAccount = controller.supplierAccounts[data.index]; + + expect(targetAccount.bankEntityFk).toEqual(data.id); }); + }); - it('should call preventDefault() and open() when the default is not prevented', () => { - const event = { - defaultPrevented: false, - preventDefault: () => {} - }; + describe('onSubmit()', () => { + it(`should reload the card`, done => { + controller.card = {reload: () => {}}; + controller.$.payMethodToTransfer = {show: () => {}}; + jest.spyOn(controller.$.payMethodToTransfer, 'show'); + jest.spyOn(controller.$.model, 'save').mockReturnValue(new Promise(resolve => { + return resolve({ + id: 1234 + }); + })); + jest.spyOn(controller.card, 'reload').mockReturnValue(new Promise(resolve => { + return resolve({ + id: 1234 + }); + })); - jest.spyOn(event, 'preventDefault'); - jest.spyOn(controller.$.bankEntity, 'open'); - - controller.showBankEntity(event); - - expect(event.preventDefault).toHaveBeenCalledWith(); - expect(controller.$.bankEntity.open).toHaveBeenCalledWith(); - }); - - it('should request to create a new bank entity', () => { - controller.bankEntity = { - name: 'My new bank entity', - bic: 'ES1234', - countryFk: 1, - id: 2200 - }; - - const query = `SupplierAccounts/${controller.$.bankEntity.id}/createBankEntity`; - $httpBackend.expectPATCH(query).respond({id: 2200}); - controller.onBankEntityAccept(); - $httpBackend.flush(); - - expect(controller.supplierAccount.bankEntityFk).toEqual(controller.bankEntity.id); + controller.wireTransferFk = 'a'; + controller.supplier = {payMethodFk: 'b'}; + controller.onSubmit().then(() => { + expect(controller.card.reload).toHaveBeenCalledWith(); + expect(controller.$.payMethodToTransfer.show).toHaveBeenCalled(); + done(); + }).catch(done.fail); }); }); }); diff --git a/modules/supplier/front/account/locale/es.yml b/modules/supplier/front/account/locale/es.yml index c9c6971711..f445a3fb81 100644 --- a/modules/supplier/front/account/locale/es.yml +++ b/modules/supplier/front/account/locale/es.yml @@ -2,4 +2,5 @@ Bank entity: Entidad bancaria swift: Swift BIC Add account: Añadir cuenta Beneficiary: Beneficiario -Beneficiary information: Nombre del titular de la cuenta bancaria en caso de ser diferente del proveedor \ No newline at end of file +Beneficiary information: Nombre del titular de la cuenta bancaria en caso de ser diferente del proveedor +Do you want to change the pay method to wire transfer?: ¿Quieres modificar la forma de pago a transferencia? \ No newline at end of file diff --git a/modules/supplier/front/card/index.js b/modules/supplier/front/card/index.js index 613b99cc9d..13fc3d52d5 100644 --- a/modules/supplier/front/card/index.js +++ b/modules/supplier/front/card/index.js @@ -37,7 +37,7 @@ class Controller extends ModuleCard { } ] }; - this.$http.get(`Suppliers/${this.$params.id}`, {filter}) + return this.$http.get(`Suppliers/${this.$params.id}`, {filter}) .then(response => this.supplier = response.data); } } diff --git a/modules/ticket/back/methods/sale/deleteSales.js b/modules/ticket/back/methods/sale/deleteSales.js index 31899a501b..a604da8582 100644 --- a/modules/ticket/back/methods/sale/deleteSales.js +++ b/modules/ticket/back/methods/sale/deleteSales.js @@ -6,18 +6,18 @@ module.exports = Self => { accessType: 'WRITE', accepts: [{ arg: 'sales', - type: ['Object'], + type: ['object'], required: true, description: 'The sales to remove' }, { arg: 'ticketId', - type: 'Number', + type: 'number', required: true, description: 'The ticket id' }], returns: { - type: ['Object'], + type: ['object'], root: true }, http: { @@ -27,10 +27,25 @@ module.exports = Self => { }); Self.deleteSales = async(ctx, sales, ticketId) => { + const $t = ctx.req.__; // $translate const models = Self.app.models; const canEditSales = await models.Sale.canEdit(ctx, sales); + const ticket = await models.Ticket.findById(ticketId, { + include: { + relation: 'client', + scope: { + include: { + relation: 'salesPersonUser', + scope: { + fields: ['id', 'name'] + } + } + } + } + }); + const isTicketEditable = await models.Ticket.isEditable(ctx, ticketId); if (!isTicketEditable) throw new UserError(`The sales of this ticket can't be modified`); @@ -39,11 +54,26 @@ module.exports = Self => { throw new UserError(`Sale(s) blocked, please contact production`); const promises = []; + let deletions = ''; for (let sale of sales) { const deletedSale = models.Sale.destroyById(sale.id); + deletions += `\r\n-${sale.itemFk}: ${sale.concept} (${sale.quantity})`; + promises.push(deletedSale); } + const salesPerson = ticket.client().salesPersonUser(); + if (salesPerson) { + const origin = ctx.req.headers.origin; + + const message = $t('Deleted sales from ticket', { + ticketId: ticketId, + ticketUrl: `${origin}/#!/ticket/${ticketId}/sale`, + deletions: deletions + }); + await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); + } + return Promise.all(promises); }; }; diff --git a/modules/ticket/back/methods/sale/reserve.js b/modules/ticket/back/methods/sale/reserve.js index 96c794e7ca..639827fa7d 100644 --- a/modules/ticket/back/methods/sale/reserve.js +++ b/modules/ticket/back/methods/sale/reserve.js @@ -5,24 +5,27 @@ module.exports = Self => { Self.remoteMethodCtx('reserve', { description: 'Change the state of a ticket', accessType: 'WRITE', - accepts: [{ - arg: 'ticketId', - type: 'Number', - required: true, - description: 'The ticket id' - }, { - arg: 'sales', - type: ['Object'], - required: true, - description: 'The sale to reserve' - }, - { - arg: 'reserved', - type: 'Boolean', - required: true - }], + accepts: [ + { + arg: 'ticketId', + type: 'number', + required: true, + description: 'The ticket id' + }, + { + arg: 'sales', + type: ['object'], + required: true, + description: 'The sale to reserve' + }, + { + arg: 'reserved', + type: 'boolean', + required: true + } + ], returns: { - type: ['Object'], + type: ['object'], root: true }, http: { @@ -32,7 +35,9 @@ module.exports = Self => { }); Self.reserve = async(ctx, ticketId, sales, reserved) => { + const $t = ctx.req.__; // $translate const models = Self.app.models; + const isTicketEditable = await models.Ticket.isEditable(ctx, ticketId); if (!isTicketEditable) throw new UserError(`The sales of this ticket can't be modified`); @@ -42,12 +47,50 @@ module.exports = Self => { if (!canEditSale) throw new UserError(`Sale(s) blocked, please contact production`); + let changesMade = ''; const promises = []; + for (let sale of sales) { - const reservedSale = models.Sale.update({id: sale.id}, {reserved: reserved}); - promises.push(reservedSale); + if (sale.reserved != reserved) { + const oldState = sale.reserved ? 'reserved' : 'regular'; + const newState = reserved ? 'reserved' : 'regular'; + + const reservedSale = models.Sale.update({id: sale.id}, {reserved: reserved}); + + promises.push(reservedSale); + + changesMade += `\r\n-${sale.itemFk}: ${sale.concept} (${sale.quantity}) ${$t('State')}: ${$t(oldState)} ➔ *${$t(newState)}*`; + } } - return Promise.all(promises); + const result = await Promise.all(promises); + + const ticket = await models.Ticket.findById(ticketId, { + include: { + relation: 'client', + scope: { + include: { + relation: 'salesPersonUser', + scope: { + fields: ['id', 'name'] + } + } + } + } + }); + + const salesPerson = ticket.client().salesPersonUser(); + if (salesPerson) { + const origin = ctx.req.headers.origin; + + const message = $t('Changed sale reserved state', { + ticketId: ticketId, + ticketUrl: `${origin}/#!/ticket/${ticketId}/sale`, + changes: changesMade + }); + await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); + } + + return result; }; }; diff --git a/modules/ticket/back/methods/sale/specs/deleteSales.spec.js b/modules/ticket/back/methods/sale/specs/deleteSales.spec.js index 22ac49452c..aabc383754 100644 --- a/modules/ticket/back/methods/sale/specs/deleteSales.spec.js +++ b/modules/ticket/back/methods/sale/specs/deleteSales.spec.js @@ -17,7 +17,14 @@ describe('sale deleteSales()', () => { }); it('should throw an error if the ticket of the given sales is not editable', async() => { - let ctx = {req: {accessToken: {userId: 9}}}; + let ctx = { + req: { + accessToken: {userId: 9}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + let error; const sales = [{id: 1, instance: 0}, {id: 2, instance: 1}]; @@ -33,7 +40,13 @@ describe('sale deleteSales()', () => { }); it('should delete the sale', async() => { - let ctx = {req: {accessToken: {userId: 9}}}; + let ctx = { + req: { + accessToken: {userId: 9}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; const sales = [{id: newSale.id, instance: 0}]; const ticketId = 16; diff --git a/modules/ticket/back/methods/sale/specs/reserve.spec.js b/modules/ticket/back/methods/sale/specs/reserve.spec.js index fce7bd95e0..3752a2b6b9 100644 --- a/modules/ticket/back/methods/sale/specs/reserve.spec.js +++ b/modules/ticket/back/methods/sale/specs/reserve.spec.js @@ -1,7 +1,14 @@ const app = require('vn-loopback/server/server'); describe('sale reserve()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const ctx = { + req: { + accessToken: {userId: 9}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + afterAll(async done => { let ctx = {req: {accessToken: {userId: 9}}}; let params = { diff --git a/modules/ticket/back/methods/sale/specs/updatePrice.spec.js b/modules/ticket/back/methods/sale/specs/updatePrice.spec.js index ec4376adb4..ea8a65c27b 100644 --- a/modules/ticket/back/methods/sale/specs/updatePrice.spec.js +++ b/modules/ticket/back/methods/sale/specs/updatePrice.spec.js @@ -17,7 +17,13 @@ describe('sale updatePrice()', () => { }); it('should throw an error if the ticket is not editable', async() => { - let ctx = {req: {accessToken: {userId: 18}}}; + const ctx = { + req: { + accessToken: {userId: 18}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; let immutableSaleId = 1; let price = 5; @@ -31,7 +37,14 @@ describe('sale updatePrice()', () => { }); it('should return 0 if the price is an empty string', async() => { - let ctx = {req: {accessToken: {userId: 18}}}; + const ctx = { + req: { + accessToken: {userId: 18}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + let price = ''; await app.models.Sale.updatePrice(ctx, saleId, price); @@ -46,7 +59,14 @@ describe('sale updatePrice()', () => { }); it('should now set price as a number in a string', async() => { - let ctx = {req: {accessToken: {userId: 18}}}; + const ctx = { + req: { + accessToken: {userId: 18}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + let price = '8'; await app.models.Sale.updatePrice(ctx, saleId, price); diff --git a/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js b/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js index 16221b55ce..dabdac3840 100644 --- a/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js +++ b/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js @@ -1,7 +1,13 @@ const app = require('vn-loopback/server/server'); describe('sale updateQuantity()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const ctx = { + req: { + accessToken: {userId: 9}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; it('should throw an error if the quantity is not a number', async() => { let error; diff --git a/modules/ticket/back/methods/sale/updatePrice.js b/modules/ticket/back/methods/sale/updatePrice.js index 2195c2b7b9..cb86296c93 100644 --- a/modules/ticket/back/methods/sale/updatePrice.js +++ b/modules/ticket/back/methods/sale/updatePrice.js @@ -19,7 +19,7 @@ module.exports = Self => { } ], returns: { - type: 'Number', + type: 'number', root: true }, http: { @@ -29,29 +29,37 @@ module.exports = Self => { }); Self.updatePrice = async(ctx, id, newPrice) => { - let models = Self.app.models; - let tx = await Self.beginTransaction({}); + const $t = ctx.req.__; // $translate + const models = Self.app.models; + const tx = await Self.beginTransaction({}); try { - let options = {transaction: tx}; + const options = {transaction: tx}; - let filter = { + const filter = { include: { relation: 'ticket', scope: { include: { relation: 'client', scope: { - fields: ['salesPersonFk'] + fields: ['salesPersonFk'], + include: { + relation: 'salesPersonUser', + scope: { + fields: ['id', 'name'] + } + } } }, fields: ['id', 'clientFk'] } } }; - let sale = await models.Sale.findById(id, filter, options); - let isEditable = await models.Ticket.isEditable(ctx, sale.ticketFk); + const sale = await models.Sale.findById(id, filter, options); + + const isEditable = await models.Ticket.isEditable(ctx, sale.ticketFk); if (!isEditable) throw new UserError(`The sales of this ticket can't be modified`); @@ -60,21 +68,19 @@ module.exports = Self => { if (!canEditSale) throw new UserError(`Sale(s) blocked, please contact production`); + const oldPrice = sale.price; const userId = ctx.req.accessToken.userId; + const usesMana = await models.WorkerMana.findOne({where: {workerFk: userId}, fields: 'amount'}, options); + const componentCode = usesMana ? 'mana' : 'buyerDiscount'; + const discount = await models.Component.findOne({where: {code: componentCode}}, options); + const componentId = discount.id; + const componentValue = newPrice - sale.price; - let usesMana = await models.WorkerMana.findOne({where: {workerFk: userId}, fields: 'amount'}, options); - - let componentCode = usesMana ? 'mana' : 'buyerDiscount'; - - let discount = await models.Component.findOne({where: {code: componentCode}}, options); - let componentId = discount.id; - let componentValue = newPrice - sale.price; - - let where = { + const where = { componentFk: componentId, saleFk: id }; - let saleComponent = await models.SaleComponent.findOne({where}, options); + const saleComponent = await models.SaleComponent.findOne({where}, options); if (saleComponent) { await models.SaleComponent.updateAll(where, { @@ -92,6 +98,22 @@ module.exports = Self => { query = `CALL vn.manaSpellersRequery(?)`; await Self.rawSql(query, [userId], options); + const salesPerson = sale.ticket().client().salesPersonUser(); + if (salesPerson) { + const origin = ctx.req.headers.origin; + const message = $t('Changed sale price', { + ticketId: sale.ticket().id, + itemId: sale.itemFk, + concept: sale.concept, + quantity: sale.quantity, + oldPrice: oldPrice, + newPrice: newPrice, + ticketUrl: `${origin}/#!/ticket/${sale.ticket().id}/sale`, + itemUrl: `${origin}/#!/item/${sale.itemFk}/summary` + }); + await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); + } + await tx.commit(); return sale; diff --git a/modules/ticket/back/methods/sale/updateQuantity.js b/modules/ticket/back/methods/sale/updateQuantity.js index 00df49b9f7..62e09f1f58 100644 --- a/modules/ticket/back/methods/sale/updateQuantity.js +++ b/modules/ticket/back/methods/sale/updateQuantity.js @@ -26,7 +26,8 @@ module.exports = Self => { } }); - Self.updateQuantity = async(ctx, id, quantity) => { + Self.updateQuantity = async(ctx, id, newQuantity) => { + const $t = ctx.req.__; // $translate const models = Self.app.models; const canEditSale = await models.Sale.canEdit(ctx, [id]); @@ -34,13 +35,51 @@ module.exports = Self => { if (!canEditSale) throw new UserError(`Sale(s) blocked, please contact production`); - if (isNaN(quantity)) + if (isNaN(newQuantity)) throw new UserError(`The value should be a number`); - let currentLine = await models.Sale.findOne({where: {id: id}}); - if (quantity > currentLine.quantity) + const filter = { + include: { + relation: 'ticket', + scope: { + include: { + relation: 'client', + scope: { + include: { + relation: 'salesPersonUser', + scope: { + fields: ['id', 'name'] + } + } + } + } + } + } + }; + + const sale = await models.Sale.findById(id, filter); + + if (newQuantity > sale.quantity) throw new UserError('The new quantity should be smaller than the old one'); - return await currentLine.updateAttributes({quantity: quantity}); + const oldQuantity = sale.quantity; + const result = await sale.updateAttributes({quantity: newQuantity}); + + const salesPerson = sale.ticket().client().salesPersonUser(); + if (salesPerson) { + const origin = ctx.req.headers.origin; + const message = $t('Changed sale quantity', { + ticketId: sale.ticket().id, + itemId: sale.itemFk, + concept: sale.concept, + oldQuantity: oldQuantity, + newQuantity: newQuantity, + ticketUrl: `${origin}/#!/ticket/${sale.ticket().id}/sale`, + itemUrl: `${origin}/#!/item/${sale.itemFk}/summary` + }); + await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); + } + + return result; }; }; diff --git a/modules/ticket/back/methods/ticket-dms/specs/removeFile.spec.js b/modules/ticket/back/methods/ticket-dms/specs/removeFile.spec.js index b1cd5686ad..1cd3b16cb6 100644 --- a/modules/ticket/back/methods/ticket-dms/specs/removeFile.spec.js +++ b/modules/ticket/back/methods/ticket-dms/specs/removeFile.spec.js @@ -3,7 +3,7 @@ const app = require('vn-loopback/server/server'); describe('TicketDms removeFile()', () => { const ticketDmsId = 1; it(`should return an error for a user without enough privileges`, async() => { - let clientId = 101; + let clientId = 1101; let ctx = {req: {accessToken: {userId: clientId}}}; let error; diff --git a/modules/ticket/back/methods/ticket-request/specs/filter.spec.js b/modules/ticket/back/methods/ticket-request/specs/filter.spec.js index 13636341c0..82bdfbd38f 100644 --- a/modules/ticket/back/methods/ticket-request/specs/filter.spec.js +++ b/modules/ticket/back/methods/ticket-request/specs/filter.spec.js @@ -57,7 +57,7 @@ describe('ticket-request filter()', () => { }); it('should return the ticket request matching the client ID', async() => { - ctx.args = {clientFk: 102}; + ctx.args = {clientFk: 1102}; const result = await app.models.TicketRequest.filter(ctx); const requestId = result[0].id; diff --git a/modules/ticket/back/methods/ticket-weekly/specs/filter.spec.js b/modules/ticket/back/methods/ticket-weekly/specs/filter.spec.js index e600fbfa96..690fa669b9 100644 --- a/modules/ticket/back/methods/ticket-weekly/specs/filter.spec.js +++ b/modules/ticket/back/methods/ticket-weekly/specs/filter.spec.js @@ -32,12 +32,12 @@ describe('ticket-weekly filter()', () => { }); it('should return the ticket matching the client id', async() => { - const ctx = {req: {accessToken: {userId: authUserId}}, args: {search: 101}}; + const ctx = {req: {accessToken: {userId: authUserId}}, args: {search: 1101}}; const filter = {}; const result = await app.models.TicketWeekly.filter(ctx, filter); const firstRow = result[0]; - expect(firstRow.clientFk).toEqual(101); + expect(firstRow.clientFk).toEqual(1101); expect(firstRow.clientName).toEqual('Bruce Wayne'); }); }); diff --git a/modules/ticket/back/methods/ticket/addSale.js b/modules/ticket/back/methods/ticket/addSale.js index 365355df2c..527b861a16 100644 --- a/modules/ticket/back/methods/ticket/addSale.js +++ b/modules/ticket/back/methods/ticket/addSale.js @@ -7,23 +7,23 @@ module.exports = Self => { accessType: 'WRITE', accepts: [{ arg: 'id', - type: 'Number', + type: 'number', required: true, description: 'The ticket id', http: {source: 'path'} }, { arg: 'itemId', - type: 'Number', + type: 'number', required: true }, { arg: 'quantity', - type: 'Number', + type: 'number', required: true }], returns: { - type: 'Object', + type: 'object', root: true }, http: { @@ -32,37 +32,81 @@ module.exports = Self => { } }); - Self.addSale = async(ctx, id, itemId, quantity) => { + Self.addSale = async(ctx, id, itemId, quantity, options) => { + const $t = ctx.req.__; // $translate const models = Self.app.models; + const myOptions = {}; + let tx; - const isEditable = await models.Ticket.isEditable(ctx, id); - if (!isEditable) - throw new UserError(`The sales of this ticket can't be modified`); + if (typeof options == 'object') + Object.assign(myOptions, options); - const item = await models.Item.findById(itemId); - const ticket = await models.Ticket.findById(id); + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } - const res = await models.Item.getVisibleAvailable(itemId, ticket.warehouseFk, ticket.shipped); + try { + const isEditable = await models.Ticket.isEditable(ctx, id, myOptions); + if (!isEditable) + throw new UserError(`The sales of this ticket can't be modified`); - const isPackaging = item.family == 'EMB'; - if (!isPackaging && res.available < quantity) - throw new UserError(`This item is not available`); + const item = await models.Item.findById(itemId, null, myOptions); + const ticket = await models.Ticket.findById(id, { + include: { + relation: 'client', + scope: { + include: { + relation: 'salesPersonUser', + scope: { + fields: ['id', 'name'] + } + } + } + } + }, myOptions); - const newSale = await models.Sale.create({ - ticketFk: id, - itemFk: item.id, - concept: item.name, - quantity: quantity - }); + const itemInfo = await models.Item.getVisibleAvailable(itemId, ticket.warehouseFk, ticket.shipped, myOptions); - await Self.rawSql('CALL vn.sale_calculateComponent(?, NULL)', [newSale.id]); + const isPackaging = item.family == 'EMB'; + if (!isPackaging && itemInfo.available < quantity) + throw new UserError(`This item is not available`); - const sale = await models.Sale.findById(newSale.id, { - include: { - relation: 'item' + const newSale = await models.Sale.create({ + ticketFk: id, + itemFk: item.id, + concept: item.name, + quantity: quantity + }, myOptions); + + await Self.rawSql('CALL vn.sale_calculateComponent(?, NULL)', [newSale.id], myOptions); + + const sale = await models.Sale.findById(newSale.id, { + include: { + relation: 'item' + } + }, myOptions); + + const addition = `\r\n-${sale.itemFk}: ${sale.concept} (${sale.quantity})`; + + const salesPerson = ticket.client().salesPersonUser(); + if (salesPerson) { + const origin = ctx.req.headers.origin; + + const message = $t('Added sale to ticket', { + ticketId: id, + ticketUrl: `${origin}/#!/ticket/${id}/sale`, + addition: addition + }); + await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); } - }); - return sale; + if (tx) await tx.commit(); + + return sale; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } }; }; diff --git a/modules/ticket/back/methods/ticket/canBeInvoiced.js b/modules/ticket/back/methods/ticket/canBeInvoiced.js index 8300ae1106..a009d63cf1 100644 --- a/modules/ticket/back/methods/ticket/canBeInvoiced.js +++ b/modules/ticket/back/methods/ticket/canBeInvoiced.js @@ -4,11 +4,10 @@ module.exports = function(Self) { accessType: 'READ', accepts: [ { - arg: 'id', - type: 'number', - required: true, - description: 'The ticket id', - http: {source: 'path'} + arg: 'ticketsIds', + description: 'The tickets id', + type: ['number'], + required: true } ], returns: { @@ -17,26 +16,44 @@ module.exports = function(Self) { root: true }, http: { - path: `/:id/canBeInvoiced`, + path: `/canBeInvoiced`, verb: 'get' } }); - Self.canBeInvoiced = async id => { - let ticket = await Self.app.models.Ticket.findById(id, { + Self.canBeInvoiced = async(ticketsIds, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const tickets = await Self.find({ + where: { + id: {inq: ticketsIds} + }, fields: ['id', 'refFk', 'shipped', 'totalWithVat'] + }, myOptions); + + const query = ` + SELECT vn.hasSomeNegativeBase(t.id) AS hasSomeNegativeBase + FROM ticket t + WHERE id IN(?)`; + const ticketBases = await Self.rawSql(query, [ticketsIds], myOptions); + const hasSomeNegativeBase = ticketBases.some( + ticketBases => ticketBases.hasSomeNegativeBase + ); + + const today = new Date(); + + const invalidTickets = tickets.some(ticket => { + const shipped = new Date(ticket.shipped); + const shippingInFuture = shipped.getTime() > today.getTime(); + const isInvoiced = ticket.refFk; + const priceZero = ticket.totalWithVat == 0; + + return isInvoiced || priceZero || shippingInFuture; }); - let query = `SELECT vn.hasSomeNegativeBase(?) AS hasSomeNegativeBase`; - let [result] = await Self.rawSql(query, [id]); - let hasSomeNegativeBase = result.hasSomeNegativeBase; - - let today = new Date(); - let shipped = new Date(ticket.shipped); - - if (ticket.refFk || ticket.totalWithVat == 0 || shipped.getTime() > today.getTime() || hasSomeNegativeBase) - return false; - - return true; + return !(invalidTickets || hasSomeNegativeBase); }; }; diff --git a/modules/ticket/back/methods/ticket/canHaveStowaway.js b/modules/ticket/back/methods/ticket/canHaveStowaway.js index 69be212d1b..9246d0308b 100644 --- a/modules/ticket/back/methods/ticket/canHaveStowaway.js +++ b/modules/ticket/back/methods/ticket/canHaveStowaway.js @@ -19,8 +19,13 @@ module.exports = Self => { } }); - Self.canHaveStowaway = async id => { + Self.canHaveStowaway = async(id, options) => { const models = Self.app.models; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + const ticket = await models.Ticket.findById(id, { include: { relation: 'ship', @@ -28,8 +33,10 @@ module.exports = Self => { fields: ['id'] } } - }); - const warehouse = await models.Warehouse.findById(ticket.warehouseFk); + }, myOptions); + + const warehouse = await models.Warehouse.findById(ticket.warehouseFk, null, myOptions); + const hasStowaway = ticket.ship() ? true : false; const validStowaway = warehouse && warehouse.hasStowaway && !hasStowaway; diff --git a/modules/ticket/back/methods/ticket/changeWorker.js b/modules/ticket/back/methods/ticket/changeWorker.js deleted file mode 100644 index 896c8a7f9e..0000000000 --- a/modules/ticket/back/methods/ticket/changeWorker.js +++ /dev/null @@ -1,47 +0,0 @@ -module.exports = function(Self) { - Self.remoteMethodCtx('changeWorker', { - description: 'Change worker of tickets state', - accepts: [ - { - arg: 'worker', - type: 'number', - required: true, - description: 'worker id', - http: {source: 'path'} - } - ], - returns: { - arg: 'response', - type: 'boolean' - }, - http: { - verb: 'put', - path: '/:worker/changeWorker' - } - }); - - Self.changeWorker = function(ctx, worker, cb) { - let tickets = ctx.req.body.tickets; - changeWorker(worker, tickets, cb); - }; - - function changeWorker(worker, tickets, cb) { - let ticketTracking = Self.app.models.ticketTracking; - let toSave = []; - for (let ticket of tickets) { - toSave.push( - { - stateFk: 20, - ticketFk: ticket, - workerFk: worker - } - ); - } - ticketTracking.create(toSave, function(err, info) { - if (err) - cb(err, null); - else - cb(null, info); - }); - } -}; diff --git a/modules/ticket/back/methods/ticket/componentUpdate.js b/modules/ticket/back/methods/ticket/componentUpdate.js index b66179eb8e..133cdeb032 100644 --- a/modules/ticket/back/methods/ticket/componentUpdate.js +++ b/modules/ticket/back/methods/ticket/componentUpdate.js @@ -90,8 +90,8 @@ module.exports = Self => { Self.componentUpdate = async(ctx, options) => { const args = ctx.args; + const myOptions = {}; let tx; - let myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); @@ -167,35 +167,26 @@ module.exports = Self => { args.option ], myOptions); - if (originalTicket.addressFk != updatedTicket.addressFk) { - const ticketObservation = await models.TicketObservation.findOne({ - where: { - ticketFk: args.id, - observationTypeFk: observationTypeDelivery.id} + if (originalTicket.addressFk != updatedTicket.addressFk && args.id) { + await models.TicketObservation.destroyAll({ + ticketFk: args.id }, myOptions); - if (ticketObservation) - await ticketObservation.destroy(myOptions); - const address = await models.Address.findOne({ where: {id: args.addressFk}, include: { - relation: 'observations', - scope: { - where: {observationTypeFk: observationTypeDelivery.id}, - include: { - relation: 'observationType' - } - } + relation: 'observations' } }, myOptions); - const [observation] = address.observations(); - if (observation) { - await models.TicketObservation.create({ - ticketFk: args.id, - observationTypeFk: observation.observationTypeFk, - description: observation.description - }, myOptions); + const observations = address.observations(); + if (observations.length) { + const clonedObservations = observations.map(observation => { + observation.ticketFk = args.id; + observation.id = undefined; + return observation; + }); + + await models.TicketObservation.create(clonedObservations, myOptions); } } @@ -230,7 +221,7 @@ module.exports = Self => { ticketUrl: `${origin}/#!/ticket/${args.id}/sale`, changes: changesMade }); - await models.Chat.sendCheckingPresence(ctx, salesPersonId, message, myOptions); + await models.Chat.sendCheckingPresence(ctx, salesPersonId, message); } if (tx) await tx.commit(); diff --git a/modules/ticket/back/methods/ticket/deleteStowaway.js b/modules/ticket/back/methods/ticket/deleteStowaway.js index b86cdc4645..c3e5e0db11 100644 --- a/modules/ticket/back/methods/ticket/deleteStowaway.js +++ b/modules/ticket/back/methods/ticket/deleteStowaway.js @@ -19,69 +19,87 @@ module.exports = Self => { } }); - Self.deleteStowaway = async(ctx, id) => { + Self.deleteStowaway = async(ctx, id, options) => { const models = Self.app.models; const $t = ctx.req.__; // $translate - const ticket = await Self.findById(id, { - include: [{ - relation: 'ship' - }, { - relation: 'stowaway' - }, { - relation: 'client', - scope: { - include: { - relation: 'salesPersonUser', - scope: { - fields: ['id', 'name'] + const myOptions = {}; + let tx; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const ticket = await Self.findById(id, { + include: [{ + relation: 'ship' + }, { + relation: 'stowaway' + }, { + relation: 'client', + scope: { + include: { + relation: 'salesPersonUser', + scope: { + fields: ['id', 'name'] + } } } + }] + }, myOptions); + + let stowawayFk; + let shipFk; + if (ticket.stowaway()) { + shipFk = ticket.stowaway().shipFk; + stowawayFk = ticket.stowaway().id; + } else if (ticket.ship()) { + shipFk = ticket.ship().shipFk; + stowawayFk = ticket.ship().id; + } + + const stowaway = await models.Stowaway.findOne({ + where: { + id: stowawayFk, + shipFk: shipFk } - }] - }); + }, myOptions); + const result = await stowaway.destroy(myOptions); - let stowawayFk; - let shipFk; - if (ticket.stowaway()) { - shipFk = ticket.stowaway().shipFk; - stowawayFk = ticket.stowaway().id; - } else if (ticket.ship()) { - shipFk = ticket.ship().shipFk; - stowawayFk = ticket.ship().id; + const state = await models.State.findOne({ + where: { + code: 'BOARDING' + } + }, myOptions); + const ticketTracking = await models.TicketTracking.findOne({ + where: { + ticketFk: shipFk, + stateFk: state.id + } + }, myOptions); + + await ticketTracking.destroy(myOptions); + + const salesPerson = ticket.client().salesPersonUser(); + if (salesPerson) { + const origin = ctx.req.headers.origin; + const message = $t('This ticket is not an stowaway anymore', { + ticketId: stowawayFk, + ticketUrl: `${origin}/#!/ticket/${stowawayFk}/sale` + }); + await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); + } + + if (tx) await tx.commit(); + + return result; + } catch (e) { + if (tx) await tx.rollback(); + throw e; } - - const stowaway = await models.Stowaway.findOne({ - where: { - id: stowawayFk, - shipFk: shipFk - } - }); - const result = await stowaway.destroy(); - - const state = await models.State.findOne({ - where: { - code: 'BOARDING' - } - }); - const ticketTracking = await models.TicketTracking.findOne({ - where: { - ticketFk: shipFk, - stateFk: state.id - } - }); - - await ticketTracking.destroy(); - - const salesPerson = ticket.client().salesPersonUser(); - if (salesPerson) { - const origin = ctx.req.headers.origin; - const message = $t('This ticket is not an stowaway anymore', { - ticketId: stowawayFk, - ticketUrl: `${origin}/#!/ticket/${stowawayFk}/sale` - }); - await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); - } - - return result; }; }; diff --git a/modules/ticket/back/methods/ticket/filter.js b/modules/ticket/back/methods/ticket/filter.js index 31834112ee..79006e77dd 100644 --- a/modules/ticket/back/methods/ticket/filter.js +++ b/modules/ticket/back/methods/ticket/filter.js @@ -107,7 +107,12 @@ module.exports = Self => { arg: 'alertLevel', type: 'number', description: `The alert level of the tickets` - } + }, + { + arg: 'collectionFk', + type: 'number', + description: `The collection id filter` + }, ], returns: { type: ['object'], @@ -119,12 +124,17 @@ module.exports = Self => { } }); - Self.filter = async(ctx, filter) => { + Self.filter = async(ctx, filter, options) => { const userId = ctx.req.accessToken.userId; const conn = Self.dataSource.connector; const models = Self.app.models; const args = ctx.args; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + // Apply filter by team const teamMembersId = []; if (args.myTeam != null) { @@ -132,7 +142,8 @@ module.exports = Self => { include: { relation: 'collegues' } - }); + }, myOptions); + const collegues = worker.collegues() || []; collegues.forEach(collegue => { teamMembersId.push(collegue.collegueFk); @@ -204,7 +215,7 @@ module.exports = Self => { filter = mergeFilters(filter, {where}); - let stmts = []; + const stmts = []; let stmt; stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.filter'); @@ -263,6 +274,15 @@ module.exports = Self => { }); } + if (args.collectionFk) { + stmt.merge({ + sql: ` + JOIN collection cll ON cll.id = ? + JOIN ticketCollection tc ON tc.collectionFk = cll.id AND tc.ticketFk = t.id`, + params: [args.collectionFk] + }); + } + stmt.merge(conn.makeWhere(filter.where)); stmts.push(stmt); @@ -273,7 +293,7 @@ module.exports = Self => { ENGINE = MEMORY SELECT f.id ticketFk, f.clientFk, f.warehouseFk, f.shipped FROM tmp.filter f - LEFT JOIN alertLevel al ON al.alertLevel = f.alertLevel + LEFT JOIN alertLevel al ON al.id = f.alertLevel WHERE (al.code = 'FREE' OR f.alertLevel IS NULL) AND f.shipped >= CURDATE()`); stmts.push('CALL ticket_getProblems(FALSE)'); @@ -306,7 +326,7 @@ module.exports = Self => { break; } - let problems = {[condition]: [ + const problems = {[condition]: [ {'tp.isFreezed': hasProblem}, {'tp.risk': hasProblem}, {'tp.hasTicketRequest': hasProblem}, @@ -318,15 +338,15 @@ module.exports = Self => { stmt.merge(conn.makeOrderBy(filter.order)); stmt.merge(conn.makeLimit(filter)); - let ticketsIndex = stmts.push(stmt) - 1; + const ticketsIndex = stmts.push(stmt) - 1; stmts.push( `DROP TEMPORARY TABLE tmp.filter, tmp.ticket_problems`); - let sql = ParameterizedSQL.join(stmts, ';'); - let result = await conn.executeStmt(sql); + const sql = ParameterizedSQL.join(stmts, ';'); + const result = await conn.executeStmt(sql, myOptions); return result[ticketsIndex]; }; diff --git a/modules/ticket/back/methods/ticket/freightCost.js b/modules/ticket/back/methods/ticket/freightCost.js index 008121f8f3..85dc99bae6 100644 --- a/modules/ticket/back/methods/ticket/freightCost.js +++ b/modules/ticket/back/methods/ticket/freightCost.js @@ -10,7 +10,7 @@ module.exports = Self => { http: {source: 'path'} }, returns: { - type: 'Number', + type: 'number', root: true }, http: { @@ -19,8 +19,14 @@ module.exports = Self => { } }); - Self.freightCost = async ticketFk => { - const [freightCost] = await Self.rawSql(`SELECT vn.ticket_getFreightCost(?) total`, [ticketFk]); + Self.freightCost = async(ticketFk, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const [freightCost] = await Self.rawSql(`SELECT vn.ticket_getFreightCost(?) total`, [ticketFk], myOptions); + return freightCost.total; }; }; diff --git a/modules/ticket/back/methods/ticket/getComponentsSum.js b/modules/ticket/back/methods/ticket/getComponentsSum.js index c611913d84..276f96414c 100644 --- a/modules/ticket/back/methods/ticket/getComponentsSum.js +++ b/modules/ticket/back/methods/ticket/getComponentsSum.js @@ -10,7 +10,7 @@ module.exports = Self => { http: {source: 'path'} }, returns: { - type: 'Number', + type: 'number', root: true }, http: { @@ -18,10 +18,15 @@ module.exports = Self => { verb: 'GET' } }); - Self.getComponentsSum = async id => { + Self.getComponentsSum = async(id, options) => { const models = Self.app.models; - let componentsSum = []; - let sales = await models.Sale.find({ + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const componentsSum = []; + const sales = await models.Sale.find({ include: { relation: 'components', scope: {fields: ['value', 'componentFk'], @@ -31,10 +36,10 @@ module.exports = Self => { } }, where: {ticketFk: id} - }); + }, myOptions); for (let sale of sales) { for (let component of sale.components()) { - let componentId = componentsSum[component.componentFk]; + const componentId = componentsSum[component.componentFk]; if (!componentId) { componentsSum[component.componentFk] = { componentFk: component.componentFk, diff --git a/modules/ticket/back/methods/ticket/getPossibleStowaways.js b/modules/ticket/back/methods/ticket/getPossibleStowaways.js index 675270840e..c97e3de893 100644 --- a/modules/ticket/back/methods/ticket/getPossibleStowaways.js +++ b/modules/ticket/back/methods/ticket/getPossibleStowaways.js @@ -20,25 +20,30 @@ module.exports = Self => { } }); - Self.getPossibleStowaways = async ticketFk => { + Self.getPossibleStowaways = async(ticketFk, options) => { const models = Self.app.models; - const canHaveStowaway = await models.Ticket.canHaveStowaway(ticketFk); + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const canHaveStowaway = await models.Ticket.canHaveStowaway(ticketFk, myOptions); if (!canHaveStowaway) throw new UserError(`Can't create stowaway for this ticket`); - let ship = await models.Ticket.findById(ticketFk); + const ship = await models.Ticket.findById(ticketFk, null, myOptions); if (!ship || !ship.shipped) return []; - let lowestDate = new Date(ship.shipped.getTime()); + const lowestDate = new Date(ship.shipped.getTime()); lowestDate.setHours(0, 0, -1, 0); - let highestDate = new Date(ship.shipped.getTime()); + const highestDate = new Date(ship.shipped.getTime()); highestDate.setHours(23, 59, 59); - let possibleStowaways = await models.Ticket.find({ + const possibleStowaways = await models.Ticket.find({ where: { id: {neq: ticketFk}, clientFk: ship.clientFk, @@ -62,7 +67,7 @@ module.exports = Self => { }, }, ] - }); + }, myOptions); return possibleStowaways; }; diff --git a/modules/ticket/back/methods/ticket/getSales.js b/modules/ticket/back/methods/ticket/getSales.js index 7bd2eabbe1..c3c7fd8605 100644 --- a/modules/ticket/back/methods/ticket/getSales.js +++ b/modules/ticket/back/methods/ticket/getSales.js @@ -23,7 +23,7 @@ module.exports = Self => { Self.getSales = async(id, options) => { const models = Self.app.models; - let myOptions = {}; + const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); @@ -60,8 +60,12 @@ module.exports = Self => { const [salesAvailable] = await Self.rawSql(query, [id], myOptions); const itemAvailable = new Map(); - for (let sale of salesAvailable) - itemAvailable.set(sale.itemFk, sale.available); + for (let sale of salesAvailable) { + itemAvailable.set(sale.itemFk, { + visible: sale.visible, + available: sale.available + }); + } // Get claimed sales const saleIds = sales.map(sale => sale.id); @@ -84,7 +88,9 @@ module.exports = Self => { for (let sale of sales) { const problems = saleProblems.get(sale.id); - sale.available = itemAvailable.get(sale.itemFk); + const itemStock = itemAvailable.get(sale.itemFk); + sale.available = itemStock.available; + sale.visible = itemStock.visible; sale.claim = claimedSales.get(sale.id); if (problems) { sale.isAvailable = problems.isAvailable; diff --git a/modules/ticket/back/methods/ticket/getSalesPersonMana.js b/modules/ticket/back/methods/ticket/getSalesPersonMana.js index 42faec61bf..c200f869a1 100644 --- a/modules/ticket/back/methods/ticket/getSalesPersonMana.js +++ b/modules/ticket/back/methods/ticket/getSalesPersonMana.js @@ -18,8 +18,13 @@ module.exports = Self => { } }); - Self.getSalesPersonMana = async ticketId => { + Self.getSalesPersonMana = async(ticketId, options) => { + const myOptions = {}; const models = Self.app.models; + + if (typeof options == 'object') + Object.assign(myOptions, options); + const ticket = await models.Ticket.findById(ticketId, { include: [{ relation: 'client', @@ -28,14 +33,16 @@ module.exports = Self => { } }], fields: ['id', 'clientFk'] - }); + }, myOptions); if (!ticket) return 0; const mana = await models.WorkerMana.findOne({ where: { workerFk: ticket.client().salesPersonFk - }, fields: 'amount'}); + }, + fields: 'amount' + }, myOptions); return mana ? mana.amount : 0; }; diff --git a/modules/ticket/back/methods/ticket/getTotalVolume.js b/modules/ticket/back/methods/ticket/getTotalVolume.js index 117c3c62f6..81927aae5c 100644 --- a/modules/ticket/back/methods/ticket/getTotalVolume.js +++ b/modules/ticket/back/methods/ticket/getTotalVolume.js @@ -18,7 +18,16 @@ module.exports = Self => { } }); - Self.getTotalVolume = async ticketFk => { - return (await Self.rawSql(`SELECT vn.ticketTotalVolume(?) totalVolume, vn.ticketTotalVolumeBoxes(?) totalBoxes`, [ticketFk, ticketFk]))[0]; + Self.getTotalVolume = async(ticketFk, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const volumeData = await Self.rawSql(` + SELECT vn.ticketTotalVolume(?) totalVolume, vn.ticketTotalVolumeBoxes(?) totalBoxes + `, [ticketFk, ticketFk], myOptions); + + return volumeData[0]; }; }; diff --git a/modules/ticket/back/methods/ticket/getVolume.js b/modules/ticket/back/methods/ticket/getVolume.js index 149f650ec6..376c9ee4e8 100644 --- a/modules/ticket/back/methods/ticket/getVolume.js +++ b/modules/ticket/back/methods/ticket/getVolume.js @@ -19,8 +19,13 @@ module.exports = Self => { } }); - Self.getVolume = async ticketFk => { + Self.getVolume = async(ticketFk, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + return Self.rawSql(`SELECT * FROM vn.saleVolume - WHERE ticketFk = ?`, [ticketFk]); + WHERE ticketFk = ?`, [ticketFk], myOptions); }; }; diff --git a/modules/ticket/back/methods/ticket/isEditable.js b/modules/ticket/back/methods/ticket/isEditable.js index 1cdca9f119..a444691ac2 100644 --- a/modules/ticket/back/methods/ticket/isEditable.js +++ b/modules/ticket/back/methods/ticket/isEditable.js @@ -32,7 +32,9 @@ module.exports = Self => { const isSalesAssistant = await Self.app.models.Account.hasRole(userId, 'salesAssistant', myOptions); const isProductionBoss = await Self.app.models.Account.hasRole(userId, 'productionBoss', myOptions); - const isValidRole = isSalesAssistant || isProductionBoss; + const isBuyer = await Self.app.models.Account.hasRole(userId, 'buyer', myOptions); + + const isValidRole = isSalesAssistant || isProductionBoss || isBuyer; let alertLevel = state ? state.alertLevel : null; let ticket = await Self.app.models.Ticket.findById(id, { diff --git a/modules/ticket/back/methods/ticket/isEmpty.js b/modules/ticket/back/methods/ticket/isEmpty.js index 0465589e6d..315687894d 100644 --- a/modules/ticket/back/methods/ticket/isEmpty.js +++ b/modules/ticket/back/methods/ticket/isEmpty.js @@ -12,7 +12,7 @@ module.exports = function(Self) { } ], returns: { - type: 'Boolean', + type: 'boolean', root: true }, http: { @@ -24,25 +24,27 @@ module.exports = function(Self) { Self.isEmpty = async(id, options) => { const models = Self.app.models; - if ((typeof options) != 'object') - options = {}; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); const hasSales = await models.Sale.count({ ticketFk: id - }, options); + }, myOptions); const hasPackages = await models.TicketPackaging.count({ ticketFk: id - }, options); + }, myOptions); const hasServices = await models.TicketService.count({ ticketFk: id - }, options); + }, myOptions); const hasPurchaseRequests = await models.TicketRequest.count({ ticketFk: id, isOk: true - }, options); + }, myOptions); const isEmpty = !hasSales && !hasPackages && !hasServices && !hasPurchaseRequests; diff --git a/modules/ticket/back/methods/ticket/isLocked.js b/modules/ticket/back/methods/ticket/isLocked.js index a6c3cc0360..947c93811c 100644 --- a/modules/ticket/back/methods/ticket/isLocked.js +++ b/modules/ticket/back/methods/ticket/isLocked.js @@ -25,7 +25,7 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - const ticket = await Self.app.models.Ticket.findById(id, { + const ticket = await Self.findById(id, { fields: ['isDeleted', 'refFk'] }, myOptions); diff --git a/modules/ticket/back/methods/ticket/makeInvoice.js b/modules/ticket/back/methods/ticket/makeInvoice.js index a44c41e169..befc75ffc7 100644 --- a/modules/ticket/back/methods/ticket/makeInvoice.js +++ b/modules/ticket/back/methods/ticket/makeInvoice.js @@ -2,15 +2,14 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = function(Self) { Self.remoteMethodCtx('makeInvoice', { - description: 'Make out an invoice from a ticket id', + description: 'Make out an invoice from one or more tickets', accessType: 'WRITE', accepts: [ { - arg: 'id', - type: 'string', - required: true, - description: 'Ticket id', - http: {source: 'path'} + arg: 'ticketsIds', + description: 'The tickets id', + type: ['number'], + required: true } ], returns: { @@ -19,62 +18,102 @@ module.exports = function(Self) { root: true }, http: { - path: `/:id/makeInvoice`, + path: `/makeInvoice`, verb: 'POST' } }); - Self.makeInvoice = async(ctx, id) => { + Self.makeInvoice = async(ctx, ticketsIds, options) => { const userId = ctx.req.accessToken.userId; const models = Self.app.models; - const tx = await Self.beginTransaction({}); + const myOptions = {}; + let tx; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + let serial; + let invoiceId; try { - const options = {transaction: tx}; + const tickets = await models.Ticket.find({ + where: { + id: {inq: ticketsIds} + }, + fields: ['id', 'clientFk', 'companyFk'] + }, myOptions); - const filter = {fields: ['id', 'clientFk', 'companyFk']}; - const ticket = await models.Ticket.findById(id, filter, options); + const [firstTicket] = tickets; + const clientId = firstTicket.clientFk; + const companyId = firstTicket.companyFk; - const clientCanBeInvoiced = await models.Client.canBeInvoiced(ticket.clientFk); + const isSameClient = tickets.every(ticket => ticket.clientFk == clientId); + if (!isSameClient) + throw new UserError(`You can't invoice tickets from multiple clients`); + + const clientCanBeInvoiced = await models.Client.canBeInvoiced(clientId, myOptions); if (!clientCanBeInvoiced) throw new UserError(`This client can't be invoiced`); - const ticketCanBeInvoiced = await models.Ticket.canBeInvoiced(ticket.id); + const ticketCanBeInvoiced = await models.Ticket.canBeInvoiced(ticketsIds, myOptions); if (!ticketCanBeInvoiced) - throw new UserError(`This ticket can't be invoiced`); + throw new UserError(`Some of the selected tickets are not billable`); const query = `SELECT vn.invoiceSerial(?, ?, ?) AS serial`; - const [result] = await Self.rawSql(query, [ticket.clientFk, ticket.companyFk, 'R'], options); - const serial = result.serial; + const [result] = await Self.rawSql(query, [ + clientId, + companyId, + 'R' + ], myOptions); + serial = result.serial; - await Self.rawSql('CALL invoiceFromTicket(?)', [id], options); - await Self.rawSql('CALL invoiceOut_new(?, CURDATE(), null, @invoiceId)', [serial], options); + await Self.rawSql(` + DROP TEMPORARY TABLE IF EXISTS ticketToInvoice; + CREATE TEMPORARY TABLE ticketToInvoice + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT id FROM vn.ticket + WHERE id IN(?) AND refFk IS NULL + `, [ticketsIds], myOptions); - const [resultInvoice] = await Self.rawSql('SELECT @invoiceId id', [], options); + await Self.rawSql('CALL invoiceOut_new(?, CURDATE(), null, @invoiceId)', [serial], myOptions); - const invoiceId = resultInvoice.id; + const [resultInvoice] = await Self.rawSql('SELECT @invoiceId id', [], myOptions); - const ticketInvoice = await models.Ticket.findById(id, {fields: ['refFk']}, options); + invoiceId = resultInvoice.id; - await models.TicketLog.create({ - originFk: ticket.id, - userFk: userId, - action: 'insert', - changedModel: 'Ticket', - changedModelId: ticket.id, - newInstance: ticketInvoice - }, options); + for (let ticket of tickets) { + const ticketInvoice = await models.Ticket.findById(ticket.id, { + fields: ['refFk'] + }, myOptions); - if (serial != 'R' && invoiceId) { - await Self.rawSql('CALL invoiceOutBooking(?)', [invoiceId], options); - await models.InvoiceOut.createPdf(ctx, invoiceId, options); + await models.TicketLog.create({ + originFk: ticket.id, + userFk: userId, + action: 'insert', + changedModel: 'Ticket', + changedModelId: ticket.id, + newInstance: ticketInvoice + }, myOptions); } - await tx.commit(); - return {invoiceFk: invoiceId, serial}; + if (serial != 'R' && invoiceId) + await Self.rawSql('CALL invoiceOutBooking(?)', [invoiceId], myOptions); + + if (tx) await tx.commit(); } catch (e) { - await tx.rollback(); + if (tx) await tx.rollback(); throw e; } + + if (serial != 'R' && invoiceId) + await models.InvoiceOut.createPdf(ctx, invoiceId); + + return {invoiceFk: invoiceId, serial: serial}; }; }; diff --git a/modules/ticket/back/methods/ticket/new.js b/modules/ticket/back/methods/ticket/new.js index cec7857bd1..a72ea6c45e 100644 --- a/modules/ticket/back/methods/ticket/new.js +++ b/modules/ticket/back/methods/ticket/new.js @@ -57,77 +57,78 @@ module.exports = Self => { } }); - Self.new = async(ctx, clientId, shipped, landed, warehouseId, - companyId, addressId, agencyModeId, routeId, options) => { + Self.new = async(ctx, options) => { + const args = ctx.args; const myUserId = ctx.req.accessToken.userId; const models = Self.app.models; - const address = await models.Address.findOne({ - where: {id: addressId}, - fields: ['id', 'clientFk'], - include: { - relation: 'client', - scope: { - include: { - relation: 'type' - } - } - } - }); - - if (!address) - throw new UserError(`This address doesn't exist`); - - let agencyMode; - if (agencyModeId) - agencyMode = await models.AgencyMode.findById(agencyModeId); - - if (address.client().type().code === 'normal' && (!agencyMode || agencyMode.code != 'refund')) { - const canCreateTicket = await models.Client.canCreateTicket(clientId); - if (!canCreateTicket) - throw new UserError(`You can't create a ticket for a inactive client`); - } - + const myOptions = {}; let tx; - if ((typeof options) != 'object') - options = {}; + if (typeof options == 'object') + Object.assign(myOptions, options); - if (!options.transaction) { + if (!myOptions.transaction) { tx = await Self.beginTransaction({}); - options.transaction = tx; + myOptions.transaction = tx; } try { - if (!shipped && landed) { - const shippedResult = await models.Agency.getShipped(landed, - address.id, agencyModeId, warehouseId); - shipped = (shippedResult && shippedResult.shipped) || landed; + const address = await models.Address.findOne({ + where: {id: args.addressId}, + fields: ['id', 'clientFk'], + include: { + relation: 'client', + scope: { + include: { + relation: 'type' + } + } + } + }, myOptions); + + if (!address) + throw new UserError(`This address doesn't exist`); + + let agencyMode; + if (args.agencyModeId) + agencyMode = await models.AgencyMode.findById(args.agencyModeId, null, myOptions); + + if (address.client().type().code === 'normal' && (!agencyMode || agencyMode.code != 'refund')) { + const canCreateTicket = await models.Client.canCreateTicket(args.clientId, myOptions); + if (!canCreateTicket) + throw new UserError(`You can't create a ticket for a inactive client`); } - if (shipped && !landed) { - const landedResult = await models.Agency.getLanded(shipped, - address.id, agencyModeId, warehouseId, false); - landed = landedResult && landedResult.landed; + if (!args.shipped && args.landed) { + const shippedResult = await models.Agency.getShipped(args.landed, + address.id, args.agencyModeId, args.warehouseId, myOptions); + args.shipped = (shippedResult && shippedResult.shipped) || args.landed; + } + + if (args.shipped && !args.landed) { + const landedResult = await models.Agency.getLanded(args.shipped, + address.id, args.agencyModeId, args.warehouseId, false, myOptions); + args.landed = landedResult && landedResult.landed; } query = `CALL vn.ticketCreateWithUser(?, ?, ?, ?, ?, ?, ?, ?, ?, @result); SELECT @result newTicketId;`; - let result = await Self.rawSql(query, [ - clientId, - shipped, - warehouseId, - companyId || 442, - addressId, - agencyModeId || null, - routeId || null, - landed, + const result = await Self.rawSql(query, [ + args.clientId, + args.shipped, + args.warehouseId, + args.companyId || 442, + args.addressId, + args.agencyModeId || null, + args.routeId || null, + args.landed, myUserId - ], options); + ], myOptions); - let ticket = await models.Ticket.findById(result[1][0].newTicketId, null, options); - let cleanInstance = JSON.parse(JSON.stringify(ticket)); + const ticket = await models.Ticket.findById(result[1][0].newTicketId, null, myOptions); + const cleanInstance = JSON.parse(JSON.stringify(ticket)); - let logRecord = { + const logRecord = { originFk: cleanInstance.id, userFk: myUserId, action: 'insert', @@ -137,9 +138,10 @@ module.exports = Self => { newInstance: cleanInstance }; - await models.TicketLog.create(logRecord, options); + await models.TicketLog.create(logRecord, myOptions); if (tx) await tx.commit(); + return await ticket; } catch (e) { if (tx) await tx.rollback(); diff --git a/modules/ticket/back/methods/ticket/priceDifference.js b/modules/ticket/back/methods/ticket/priceDifference.js index 2631481c63..202a619a50 100644 --- a/modules/ticket/back/methods/ticket/priceDifference.js +++ b/modules/ticket/back/methods/ticket/priceDifference.js @@ -6,43 +6,43 @@ module.exports = Self => { accessType: 'READ', accepts: [{ arg: 'id', - type: 'Number', + type: 'number', required: true, description: 'The ticket id', http: {source: 'path'} }, { arg: 'landed', - type: 'Date', + type: 'date', description: 'The landing date', required: true }, { arg: 'addressId', - type: 'Number', + type: 'number', description: 'The address id', required: true }, { arg: 'agencyModeId', - type: 'Number', + type: 'number', description: 'The agencyMode id', required: true }, { arg: 'zoneId', - type: 'Number', + type: 'number', description: 'The zone id', required: true }, { arg: 'warehouseId', - type: 'Number', + type: 'number', description: 'The warehouse id', required: true }], returns: { - type: ['Object'], + type: ['object'], root: true }, http: { @@ -51,38 +51,57 @@ module.exports = Self => { } }); - Self.priceDifference = async(ctx, id, landed, addressId, agencyModeId, zoneId, warehouseId) => { + Self.priceDifference = async(ctx, options) => { + const args = ctx.args; const models = Self.app.models; - const isEditable = await Self.isEditable(ctx, id); const userId = ctx.req.accessToken.userId; + const myOptions = {}; + let tx; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + const isEditable = await Self.isEditable(ctx, args.id, myOptions); if (!isEditable) throw new UserError(`The sales of this ticket can't be modified`); - const isProductionBoss = await models.Account.hasRole(userId, 'productionBoss'); + const isProductionBoss = await models.Account.hasRole(userId, 'productionBoss', myOptions); if (!isProductionBoss) { - const zoneShipped = await models.Agency.getShipped(landed, addressId, agencyModeId, warehouseId); + const zoneShipped = await models.Agency.getShipped( + args.landed, + args.addressId, + args.agencyModeId, + args.warehouseId, + myOptions); - if (!zoneShipped || zoneShipped.zoneFk != zoneId) + if (!zoneShipped || zoneShipped.zoneFk != args.zoneId) throw new UserError(`You don't have privileges to change the zone`); } - let salesObj = { - items: await models.Sale.find({ - where: { - ticketFk: id - }, - order: 'concept ASC', - include: 'item' - }), + const items = await models.Sale.find({ + where: { + ticketFk: args.id + }, + order: 'concept ASC', + include: 'item' + }, myOptions); + + const salesObj = { + items: items, totalUnitPrice: 0.00, totalNewPrice: 0.00, totalDifference: 0.00, }; const query = `CALL vn.ticket_priceDifference(?, ?, ?, ?, ?)`; - const args = [id, landed, addressId, zoneId, warehouseId]; - const [difComponents] = await Self.rawSql(query, args); + const params = [args.id, args.landed, args.addressId, args.zoneId, args.warehouseId]; + const [difComponents] = await Self.rawSql(query, params, myOptions); const map = new Map(); diff --git a/modules/ticket/back/methods/ticket/specs/addSale.spec.js b/modules/ticket/back/methods/ticket/specs/addSale.spec.js index c2650bf4b8..cfd1495114 100644 --- a/modules/ticket/back/methods/ticket/specs/addSale.spec.js +++ b/modules/ticket/back/methods/ticket/specs/addSale.spec.js @@ -1,52 +1,88 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('ticket addSale()', () => { const ticketId = 13; - let newSale; - - afterAll(async done => { - const sale = await app.models.Sale.findById(newSale.id); - await sale.destroy(); - - done(); - }); it('should create a new sale for the ticket with id 13', async() => { - let ctx = {req: {accessToken: {userId: 9}}}; - const itemId = 4; - const quantity = 10; - newSale = await app.models.Ticket.addSale(ctx, ticketId, itemId, quantity); + const tx = await models.Ticket.beginTransaction({}); - expect(newSale.itemFk).toEqual(4); + try { + const options = {transaction: tx}; + + const ctx = { + req: { + accessToken: {userId: 9}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + const itemId = 4; + const quantity = 10; + const newSale = await models.Ticket.addSale(ctx, ticketId, itemId, quantity, options); + + expect(newSale.itemFk).toEqual(4); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should not be able to add a sale if the item quantity is not available', async() => { - let ctx = {req: {accessToken: {userId: 9}}}; - const itemId = 11; - const quantity = 10; + const tx = await models.Ticket.beginTransaction({}); let error; - await app.models.Ticket.addSale(ctx, ticketId, itemId, quantity).catch(e => { - error = e; - }).finally(() => { - expect(error.message).toEqual(`This item is not available`); - }); - expect(error).toBeDefined(); + try { + const options = {transaction: tx}; + + const ctx = { + req: { + accessToken: {userId: 9}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + const itemId = 11; + const quantity = 10; + + await models.Ticket.addSale(ctx, ticketId, itemId, quantity, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toEqual(`This item is not available`); }); it('should not be able to add a sale if the ticket is not editable', async() => { - let ctx = {req: {accessToken: {userId: 9}}}; - const notEditableTicketId = 1; - const itemId = 4; - const quantity = 10; - let error; - await app.models.Ticket.addSale(ctx, notEditableTicketId, itemId, quantity).catch(e => { - error = e; - }).finally(() => { - expect(error.message).toEqual(`The sales of this ticket can't be modified`); - }); + const tx = await models.Ticket.beginTransaction({}); - expect(error).toBeDefined(); + let error; + + try { + const options = {transaction: tx}; + const ctx = { + req: { + accessToken: {userId: 9}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + const notEditableTicketId = 1; + const itemId = 4; + const quantity = 10; + await models.Ticket.addSale(ctx, notEditableTicketId, itemId, quantity, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toEqual(`The sales of this ticket can't be modified`); }); }); diff --git a/modules/ticket/back/methods/ticket/specs/canBeInvoiced.spec.js b/modules/ticket/back/methods/ticket/specs/canBeInvoiced.spec.js new file mode 100644 index 0000000000..05853acba2 --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/canBeInvoiced.spec.js @@ -0,0 +1,99 @@ +const models = require('vn-loopback/server/server').models; +const LoopBackContext = require('loopback-context'); + +describe('ticket canBeInvoiced()', () => { + const userId = 19; + const ticketId = 11; + const activeCtx = { + accessToken: {userId: userId} + }; + + beforeAll(async done => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); + + done(); + }); + + it('should return falsy for an already invoiced ticket', async() => { + const tx = await models.Ticket.beginTransaction({}); + + try { + const options = {transaction: tx}; + + const ticket = await models.Ticket.findById(ticketId, null, options); + await ticket.updateAttribute('refFk', 'T1111111', options); + + const canBeInvoiced = await models.Ticket.canBeInvoiced([ticketId], options); + + expect(canBeInvoiced).toEqual(false); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should return falsy for a ticket with a price of zero', async() => { + const tx = await models.Ticket.beginTransaction({}); + + try { + const options = {transaction: tx}; + + const ticket = await models.Ticket.findById(ticketId, null, options); + await ticket.updateAttribute('totalWithVat', 0, options); + + const canBeInvoiced = await models.Ticket.canBeInvoiced([ticketId], options); + + expect(canBeInvoiced).toEqual(false); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should return falsy for a ticket shipping in future', async() => { + const tx = await models.Ticket.beginTransaction({}); + + try { + const options = {transaction: tx}; + + const ticket = await models.Ticket.findById(ticketId, null, options); + + const shipped = new Date(); + shipped.setDate(shipped.getDate() + 1); + + await ticket.updateAttribute('shipped', shipped, options); + + const canBeInvoiced = await models.Ticket.canBeInvoiced([ticketId], options); + + expect(canBeInvoiced).toEqual(false); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should return truthy for an invoiceable ticket', async() => { + const tx = await models.Ticket.beginTransaction({}); + + try { + const options = {transaction: tx}; + + const canBeInvoiced = await models.Ticket.canBeInvoiced([ticketId], options); + + expect(canBeInvoiced).toEqual(true); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/canHaveStowaway.spec.js b/modules/ticket/back/methods/ticket/specs/canHaveStowaway.spec.js index 231f2581b1..2bd25c2d2e 100644 --- a/modules/ticket/back/methods/ticket/specs/canHaveStowaway.spec.js +++ b/modules/ticket/back/methods/ticket/specs/canHaveStowaway.spec.js @@ -1,17 +1,39 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('ticket canHaveStowaway()', () => { it('should return true if the ticket warehouse have hasStowaway equal 1', async() => { - const ticketId = 16; - let canStowaway = await app.models.Ticket.canHaveStowaway(ticketId); + const tx = await models.Ticket.beginTransaction({}); - expect(canStowaway).toBeTruthy(); + try { + const options = {transaction: tx}; + + const ticketId = 16; + const canStowaway = await models.Ticket.canHaveStowaway(ticketId, options); + + expect(canStowaway).toBeTruthy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return false if the ticket warehouse dont have hasStowaway equal 0', async() => { - const ticketId = 10; - let canStowaway = await app.models.Ticket.canHaveStowaway(ticketId); + const tx = await models.Ticket.beginTransaction({}); - expect(canStowaway).toBeFalsy(); + try { + const options = {transaction: tx}; + + const ticketId = 10; + const canStowaway = await models.Ticket.canHaveStowaway(ticketId, options); + + expect(canStowaway).toBeFalsy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js b/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js index 1347af8889..9fa69b595e 100644 --- a/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js +++ b/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js @@ -1,7 +1,7 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('ticket componentUpdate()', () => { - const userID = 101; + const userID = 1101; const ticketID = 11; const today = new Date(); const tomorrow = new Date(); @@ -16,27 +16,27 @@ describe('ticket componentUpdate()', () => { let componentValue; beforeAll(async() => { - const deliveryComponenet = await app.models.Component.findOne({where: {code: 'delivery'}}); + const deliveryComponenet = await models.Component.findOne({where: {code: 'delivery'}}); deliveryComponentId = deliveryComponenet.id; componentOfSaleSeven = `SELECT value FROM vn.saleComponent WHERE saleFk = 7 AND componentFk = ${deliveryComponentId}`; componentOfSaleEight = `SELECT value FROM vn.saleComponent WHERE saleFk = 8 AND componentFk = ${deliveryComponentId}`; - [componentValue] = await app.models.SaleComponent.rawSql(componentOfSaleSeven); + [componentValue] = await models.SaleComponent.rawSql(componentOfSaleSeven); firstvalueBeforeChange = componentValue.value; - [componentValue] = await app.models.SaleComponent.rawSql(componentOfSaleEight); + [componentValue] = await models.SaleComponent.rawSql(componentOfSaleEight); secondvalueBeforeChange = componentValue.value; }); it('should change the agencyMode to modify the sale components value', async() => { - const tx = await app.models.SaleComponent.beginTransaction({}); + const tx = await models.SaleComponent.beginTransaction({}); try { const options = {transaction: tx}; const args = { id: ticketID, - clientFk: 102, + clientFk: 1102, agencyModeFk: 8, addressFk: 122, zoneFk: 5, @@ -59,12 +59,12 @@ describe('ticket componentUpdate()', () => { } }; - await app.models.Ticket.componentUpdate(ctx, options); + await models.Ticket.componentUpdate(ctx, options); - [componentValue] = await app.models.SaleComponent.rawSql(componentOfSaleSeven, null, options); + [componentValue] = await models.SaleComponent.rawSql(componentOfSaleSeven, null, options); let firstvalueAfterChange = componentValue.value; - [componentValue] = await app.models.SaleComponent.rawSql(componentOfSaleEight, null, options); + [componentValue] = await models.SaleComponent.rawSql(componentOfSaleEight, null, options); let secondvalueAfterChange = componentValue.value; expect(firstvalueBeforeChange).not.toEqual(firstvalueAfterChange); @@ -78,14 +78,14 @@ describe('ticket componentUpdate()', () => { }); it('should change the addressFk and check that delivery observations have been changed', async() => { - const tx = await app.models.SaleComponent.beginTransaction({}); + const tx = await models.SaleComponent.beginTransaction({}); try { const options = {transaction: tx}; const args = { id: ticketID, - clientFk: 102, + clientFk: 1102, agencyModeFk: 8, addressFk: 2, zoneFk: 5, @@ -107,10 +107,10 @@ describe('ticket componentUpdate()', () => { } } }; - const observationTypeDelivery = await app.models.ObservationType.findOne({ + const observationTypeDelivery = await models.ObservationType.findOne({ where: {code: 'delivery'} }, options); - const originalTicketObservation = await app.models.TicketObservation.findOne({ + const originalTicketObservation = await models.TicketObservation.findOne({ where: { ticketFk: args.id, observationTypeFk: observationTypeDelivery.id} @@ -118,9 +118,9 @@ describe('ticket componentUpdate()', () => { expect(originalTicketObservation).toBeDefined(); - await app.models.Ticket.componentUpdate(ctx, options); + await models.Ticket.componentUpdate(ctx, options); - const removedTicketObservation = await app.models.TicketObservation.findOne({ + const removedTicketObservation = await models.TicketObservation.findOne({ where: { ticketFk: ticketID, observationTypeFk: observationTypeDelivery.id} diff --git a/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js b/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js index 563c1334db..62bfc71bed 100644 --- a/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js +++ b/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js @@ -1,4 +1,4 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('ticket deleteStowaway()', () => { const shipId = 16; @@ -14,51 +14,62 @@ describe('ticket deleteStowaway()', () => { }; it(`should create an stowaway, delete it and see the states of both stowaway and ship go back to the last states`, async() => { - await app.models.Stowaway.rawSql(` - INSERT INTO stowaway (id, shipFk) VALUES (?, ?) - `, [stowawayId, shipId]); - await app.models.Stowaway.rawSql( - `CALL ticketStateUpdate(?, ?)`, [shipId, 'BOARDING']); - await app.models.Stowaway.rawSql( - `CALL ticketStateUpdate(?, ?)`, [stowawayId, 'BOARDING']); + const tx = await models.Ticket.beginTransaction({}); - let createdStowaways = await app.models.Stowaway.count({id: stowawayId, shipFk: shipId}); + try { + const options = {transaction: tx}; - expect(createdStowaways).toEqual(1); + await models.Stowaway.rawSql(` + INSERT INTO stowaway (id, shipFk) VALUES (?, ?) + `, [stowawayId, shipId], options); + await models.Stowaway.rawSql( + `CALL ticketStateUpdate(?, ?)`, [shipId, 'BOARDING'], options); + await models.Stowaway.rawSql( + `CALL ticketStateUpdate(?, ?)`, [stowawayId, 'BOARDING'], options); - let shipState = await app.models.TicketLastState.findOne({ - where: { - ticketFk: shipId - } - }); - let stowawayState = await app.models.TicketLastState.findOne({ - where: { - ticketFk: stowawayId - } - }); + let createdStowaways = await models.Stowaway.count({id: stowawayId, shipFk: shipId}, options); - expect(shipState.name).toEqual('Embarcando'); - expect(stowawayState.name).toEqual('Embarcando'); + expect(createdStowaways).toEqual(1); - await app.models.Ticket.deleteStowaway(ctx, shipId); - await app.models.Ticket.deleteStowaway(ctx, stowawayId); + let shipState = await models.TicketLastState.findOne({ + where: { + ticketFk: shipId + } + }, options); + let stowawayState = await models.TicketLastState.findOne({ + where: { + ticketFk: stowawayId + } + }, options); - createdStowaways = await app.models.Stowaway.count({id: stowawayId, shipFk: shipId}); + expect(shipState.name).toEqual('Embarcando'); + expect(stowawayState.name).toEqual('Embarcando'); - expect(createdStowaways).toEqual(0); + await models.Ticket.deleteStowaway(ctx, shipId, options); + await models.Ticket.deleteStowaway(ctx, stowawayId, options); - shipState = await app.models.TicketLastState.findOne({ - where: { - ticketFk: shipId - } - }); - stowawayState = await app.models.TicketLastState.findOne({ - where: { - ticketFk: stowawayId - } - }); + createdStowaways = await models.Stowaway.count({id: stowawayId, shipFk: shipId}, options); - expect(shipState.name).toEqual('OK'); - expect(stowawayState.name).toEqual('Libre'); + expect(createdStowaways).toEqual(0); + + shipState = await models.TicketLastState.findOne({ + where: { + ticketFk: shipId + } + }, options); + stowawayState = await models.TicketLastState.findOne({ + where: { + ticketFk: stowawayId + } + }, options); + + expect(shipState.name).toEqual('OK'); + expect(stowawayState.name).toEqual('Libre'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/ticket/back/methods/ticket/specs/filter.spec.js b/modules/ticket/back/methods/ticket/specs/filter.spec.js index c742de41db..01a652b737 100644 --- a/modules/ticket/back/methods/ticket/specs/filter.spec.js +++ b/modules/ticket/back/methods/ticket/specs/filter.spec.js @@ -1,106 +1,224 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('ticket filter()', () => { it('should return the tickets matching the filter', async() => { - const ctx = {req: {accessToken: {userId: 9}}, args: {}}; - const filter = {order: 'id DESC'}; - const result = await app.models.Ticket.filter(ctx, filter); + const tx = await models.Ticket.beginTransaction({}); - expect(result.length).toEqual(24); + try { + const options = {transaction: tx}; + + const ctx = {req: {accessToken: {userId: 9}}, args: {}}; + const filter = {order: 'id DESC'}; + const result = await models.Ticket.filter(ctx, filter, options); + + expect(result.length).toEqual(24); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the tickets matching the problems on true', async() => { - const yesterday = new Date(); - yesterday.setHours(0, 0, 0, 0); - const today = new Date(); - today.setHours(23, 59, 59, 59); + const tx = await models.Ticket.beginTransaction({}); - const ctx = {req: {accessToken: {userId: 9}}, args: { - problems: true, - from: yesterday, - to: today - }}; - const filter = {}; - const result = await app.models.Ticket.filter(ctx, filter); + try { + const options = {transaction: tx}; - expect(result.length).toEqual(4); + const yesterday = new Date(); + yesterday.setHours(0, 0, 0, 0); + const today = new Date(); + today.setHours(23, 59, 59, 59); + + const ctx = {req: {accessToken: {userId: 9}}, args: { + problems: true, + from: yesterday, + to: today + }}; + const filter = {}; + const result = await models.Ticket.filter(ctx, filter, options); + + expect(result.length).toEqual(4); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the tickets matching the problems on false', async() => { - const yesterday = new Date(); - yesterday.setDate(yesterday.getDate() - 1); - yesterday.setHours(0, 0, 0, 0); - const today = new Date(); - today.setHours(23, 59, 59, 59); + const tx = await models.Ticket.beginTransaction({}); - const ctx = {req: {accessToken: {userId: 9}}, args: { - problems: false, - from: yesterday, - to: today - }}; - const filter = {}; - const result = await app.models.Ticket.filter(ctx, filter); + try { + const options = {transaction: tx}; - expect(result.length).toEqual(6); + const yesterday = new Date(); + yesterday.setDate(yesterday.getDate() - 1); + yesterday.setHours(0, 0, 0, 0); + const today = new Date(); + today.setHours(23, 59, 59, 59); + + const ctx = {req: {accessToken: {userId: 9}}, args: { + problems: false, + from: yesterday, + to: today + }}; + const filter = {}; + const result = await models.Ticket.filter(ctx, filter, options); + + expect(result.length).toEqual(6); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the tickets matching the problems on null', async() => { - const ctx = {req: {accessToken: {userId: 9}}, args: {problems: null}}; - const filter = {}; - const result = await app.models.Ticket.filter(ctx, filter); + const tx = await models.Ticket.beginTransaction({}); - expect(result.length).toEqual(24); + try { + const options = {transaction: tx}; + + const ctx = {req: {accessToken: {userId: 9}}, args: {problems: null}}; + const filter = {}; + const result = await models.Ticket.filter(ctx, filter, options); + + expect(result.length).toEqual(24); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the tickets matching the orderId 11', async() => { - const ctx = {req: {accessToken: {userId: 9}}, args: {orderFk: 11}}; - const filter = {}; - const result = await app.models.Ticket.filter(ctx, filter); - const firstRow = result[0]; + const tx = await models.Ticket.beginTransaction({}); - expect(result.length).toEqual(1); - expect(firstRow.id).toEqual(11); + try { + const options = {transaction: tx}; + + const ctx = {req: {accessToken: {userId: 9}}, args: {orderFk: 11}}; + const filter = {}; + const result = await models.Ticket.filter(ctx, filter, options); + const firstRow = result[0]; + + expect(result.length).toEqual(1); + expect(firstRow.id).toEqual(11); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the tickets with grouped state "Pending" and not "Ok" nor "BOARDING"', async() => { - const ctx = {req: {accessToken: {userId: 9}}, args: {pending: true}}; - const filter = {}; - const result = await app.models.Ticket.filter(ctx, filter); + const tx = await models.Ticket.beginTransaction({}); - const length = result.length; - const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + try { + const options = {transaction: tx}; - expect(length).toEqual(7); - expect(anyResult.state).toMatch(/(Libre|Arreglar)/); + const ctx = {req: {accessToken: {userId: 9}}, args: {pending: true}}; + const filter = {}; + const result = await models.Ticket.filter(ctx, filter, options); + + const length = result.length; + const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + + expect(length).toEqual(7); + expect(anyResult.state).toMatch(/(Libre|Arreglar)/); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the tickets that are not pending', async() => { - const ctx = {req: {accessToken: {userId: 9}}, args: {pending: false}}; - const filter = {}; - const result = await app.models.Ticket.filter(ctx, filter); - const firstRow = result[0]; - const secondRow = result[1]; - const thirdRow = result[2]; + const tx = await models.Ticket.beginTransaction({}); - expect(result.length).toEqual(12); - expect(firstRow.state).toEqual('Entregado'); - expect(secondRow.state).toEqual('Entregado'); - expect(thirdRow.state).toEqual('Entregado'); + try { + const options = {transaction: tx}; + + const ctx = {req: {accessToken: {userId: 9}}, args: {pending: false}}; + const filter = {}; + const result = await models.Ticket.filter(ctx, filter, options); + const firstRow = result[0]; + const secondRow = result[1]; + const thirdRow = result[2]; + + expect(result.length).toEqual(12); + expect(firstRow.state).toEqual('Entregado'); + expect(secondRow.state).toEqual('Entregado'); + expect(thirdRow.state).toEqual('Entregado'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the tickets from the worker team', async() => { - const ctx = {req: {accessToken: {userId: 18}}, args: {myTeam: true}}; - const filter = {}; - const result = await app.models.Ticket.filter(ctx, filter); + const tx = await models.Ticket.beginTransaction({}); - expect(result.length).toEqual(20); + try { + const options = {transaction: tx}; + + const ctx = {req: {accessToken: {userId: 18}}, args: {myTeam: true}}; + const filter = {}; + const result = await models.Ticket.filter(ctx, filter, options); + + expect(result.length).toEqual(20); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the tickets that are not from the worker team', async() => { - const ctx = {req: {accessToken: {userId: 18}}, args: {myTeam: false}}; - const filter = {}; - const result = await app.models.Ticket.filter(ctx, filter); + const tx = await models.Ticket.beginTransaction({}); - expect(result.length).toEqual(4); + try { + const options = {transaction: tx}; + + const ctx = {req: {accessToken: {userId: 18}}, args: {myTeam: false}}; + const filter = {}; + const result = await models.Ticket.filter(ctx, filter, options); + + expect(result.length).toEqual(4); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should return the tickets belonging to the collection id 1', async() => { + const tx = await models.Ticket.beginTransaction({}); + + try { + const options = {transaction: tx}; + + const ctx = {req: {accessToken: {userId: 18}}, args: {collectionFk: 1}}; + const filter = {}; + const result = await models.Ticket.filter(ctx, filter, options); + + expect(result.length).toEqual(2); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/ticket/back/methods/ticket/specs/freightCost.spec.js b/modules/ticket/back/methods/ticket/specs/freightCost.spec.js index cb8f5a562e..6edb4cebbe 100644 --- a/modules/ticket/back/methods/ticket/specs/freightCost.spec.js +++ b/modules/ticket/back/methods/ticket/specs/freightCost.spec.js @@ -1,17 +1,39 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('ticket freightCost()', () => { it('should return the freight cost of a given ticket', async() => { - let ticketId = 7; - let freightCost = await app.models.Ticket.freightCost(ticketId); + const tx = await models.Ticket.beginTransaction({}); - expect(freightCost).toBe(4); + try { + const options = {transaction: tx}; + + const ticketId = 7; + const freightCost = await models.Ticket.freightCost(ticketId, options); + + expect(freightCost).toBe(4); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return null if the ticket does not exist', async() => { - let ticketId = 99; - let freightCost = await app.models.Ticket.freightCost(ticketId); + const tx = await models.Ticket.beginTransaction({}); - expect(freightCost).toBeNull(); + try { + const options = {transaction: tx}; + + const ticketId = 99; + const freightCost = await models.Ticket.freightCost(ticketId, options); + + expect(freightCost).toBeNull(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/ticket/back/methods/ticket/specs/getComponentsSum.spec.js b/modules/ticket/back/methods/ticket/specs/getComponentsSum.spec.js index 4be8de3f08..5c4de44631 100644 --- a/modules/ticket/back/methods/ticket/specs/getComponentsSum.spec.js +++ b/modules/ticket/back/methods/ticket/specs/getComponentsSum.spec.js @@ -1,20 +1,42 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('ticket getComponentsSum()', () => { it('should get the list of component for the ticket sales', async() => { - const ticketId = 7; - const components = await app.models.Ticket.getComponentsSum(ticketId); - const length = components.length; - const anyComponent = components[Math.floor(Math.random() * Math.floor(length))]; + const tx = await models.Ticket.beginTransaction({}); - expect(components.length).toBeGreaterThan(0); - expect(anyComponent.componentFk).toBeDefined(); + try { + const options = {transaction: tx}; + + const ticketId = 7; + const components = await models.Ticket.getComponentsSum(ticketId, options); + const length = components.length; + const anyComponent = components[Math.floor(Math.random() * Math.floor(length))]; + + expect(components.length).toBeGreaterThan(0); + expect(anyComponent.componentFk).toBeDefined(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return 0 if the given ticket does not have sales', async() => { - const ticketWithoutSales = 21; - const components = await app.models.Ticket.getComponentsSum(ticketWithoutSales); + const tx = await models.Ticket.beginTransaction({}); - expect(components.length).toEqual(0); + try { + const options = {transaction: tx}; + + const ticketWithoutSales = 21; + const components = await models.Ticket.getComponentsSum(ticketWithoutSales, options); + + expect(components.length).toEqual(0); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/ticket/back/methods/ticket/specs/getPossibleStowaways.spec.js b/modules/ticket/back/methods/ticket/specs/getPossibleStowaways.spec.js index 7e667ad36b..ed1a327d46 100644 --- a/modules/ticket/back/methods/ticket/specs/getPossibleStowaways.spec.js +++ b/modules/ticket/back/methods/ticket/specs/getPossibleStowaways.spec.js @@ -1,30 +1,60 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; let UserError = require('vn-loopback/util/user-error'); describe('ticket getPossibleStowaways()', () => { it(`should throw an error if Can't create stowaway for this ticket`, async() => { - let error; - let ticketId = 10; + const tx = await models.Ticket.beginTransaction({}); - await app.models.Ticket.getPossibleStowaways(ticketId) - .catch(e => { - error = e; - }); + let error; + + try { + const options = {transaction: tx}; + + const ticketId = 10; + await models.Ticket.getPossibleStowaways(ticketId, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } expect(error).toEqual(new UserError(`Can't create stowaway for this ticket`)); }); it('should return an empty list of tickets for a valid ticket', async() => { - let ticketId = 12; - let possibleStowaways = await app.models.Ticket.getPossibleStowaways(ticketId); + const tx = await models.Ticket.beginTransaction({}); - expect(possibleStowaways.length).toEqual(0); + try { + const options = {transaction: tx}; + + const ticketId = 12; + const possibleStowaways = await models.Ticket.getPossibleStowaways(ticketId, options); + + expect(possibleStowaways.length).toEqual(0); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return allowed list of tickets for a valid ticket', async() => { - let ticketId = 16; - let possibleStowaways = await app.models.Ticket.getPossibleStowaways(ticketId); + const tx = await models.Ticket.beginTransaction({}); - expect(possibleStowaways.length).toEqual(1); + try { + const options = {transaction: tx}; + + const ticketId = 16; + const possibleStowaways = await models.Ticket.getPossibleStowaways(ticketId, options); + + expect(possibleStowaways.length).toEqual(1); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/ticket/back/methods/ticket/specs/getSales.spec.js b/modules/ticket/back/methods/ticket/specs/getSales.spec.js index 4e57f570f1..b9f78e40bd 100644 --- a/modules/ticket/back/methods/ticket/specs/getSales.spec.js +++ b/modules/ticket/back/methods/ticket/specs/getSales.spec.js @@ -1,14 +1,25 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('ticket getSales()', () => { it('should return the sales of a ticket', async() => { - let sales = await app.models.Ticket.getSales(16); + const tx = await models.Ticket.beginTransaction({}); - expect(sales.length).toEqual(4); - expect(sales[0].item).toBeDefined(); - expect(sales[1].item).toBeDefined(); - expect(sales[2].item).toBeDefined(); - expect(sales[3].item).toBeDefined(); - expect(sales[0].claim).toBeDefined(); + try { + const options = {transaction: tx}; + + const sales = await models.Ticket.getSales(16, options); + + expect(sales.length).toEqual(4); + expect(sales[0].item).toBeDefined(); + expect(sales[1].item).toBeDefined(); + expect(sales[2].item).toBeDefined(); + expect(sales[3].item).toBeDefined(); + expect(sales[0].claim).toBeDefined(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/ticket/back/methods/ticket/specs/getSalespersonMana.spec.js b/modules/ticket/back/methods/ticket/specs/getSalespersonMana.spec.js index 84e958dfab..6029ca4a78 100644 --- a/modules/ticket/back/methods/ticket/specs/getSalespersonMana.spec.js +++ b/modules/ticket/back/methods/ticket/specs/getSalespersonMana.spec.js @@ -1,15 +1,37 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('ticket getSalesPersonMana()', () => { it('should get the mana of a salesperson of a given ticket', async() => { - let mana = await app.models.Ticket.getSalesPersonMana(1); + const tx = await models.Ticket.beginTransaction({}); - expect(mana).toEqual(124); + try { + const options = {transaction: tx}; + + const mana = await models.Ticket.getSalesPersonMana(1, options); + + expect(mana).toEqual(124); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return 0 if the given ticket does not exist', async() => { - let mana = await app.models.Ticket.getSalesPersonMana(99); + const tx = await models.Ticket.beginTransaction({}); - expect(mana).toEqual(0); + try { + const options = {transaction: tx}; + + const mana = await models.Ticket.getSalesPersonMana(99, options); + + expect(mana).toEqual(0); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/ticket/back/methods/ticket/specs/getTotalVolume.spec.js b/modules/ticket/back/methods/ticket/specs/getTotalVolume.spec.js index 1901e2cb29..d11e830c51 100644 --- a/modules/ticket/back/methods/ticket/specs/getTotalVolume.spec.js +++ b/modules/ticket/back/methods/ticket/specs/getTotalVolume.spec.js @@ -1,13 +1,23 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('ticket getTotalVolume()', () => { it('should return the total volume of a ticket', async() => { - let ticketFk = 1; + const tx = await models.Ticket.beginTransaction({}); - let expectedResult = 1.568; + try { + const options = {transaction: tx}; - let result = await app.models.Ticket.getTotalVolume(ticketFk); + const ticketFk = 1; + const expectedResult = 1.568; - expect(result.totalVolume).toEqual(expectedResult); + const result = await models.Ticket.getTotalVolume(ticketFk, options); + + expect(result.totalVolume).toEqual(expectedResult); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/ticket/back/methods/ticket/specs/getVolume.spec.js b/modules/ticket/back/methods/ticket/specs/getVolume.spec.js index 6807246611..35134e4d05 100644 --- a/modules/ticket/back/methods/ticket/specs/getVolume.spec.js +++ b/modules/ticket/back/methods/ticket/specs/getVolume.spec.js @@ -1,11 +1,21 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('ticket getVolume()', () => { it('should call the getVolume method', async() => { - let ticketFk = 1; - await app.models.Ticket.getVolume(ticketFk) - .then(response => { - expect(response[0].volume).toEqual(1.09); - }); + const tx = await models.Ticket.beginTransaction({}); + + try { + const options = {transaction: tx}; + + const ticketId = 1; + const result = await models.Ticket.getVolume(ticketId, options); + + expect(result[0].volume).toEqual(1.09); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/ticket/back/methods/ticket/specs/isEditable.spec.js b/modules/ticket/back/methods/ticket/specs/isEditable.spec.js index 5a6bf7d191..adc2acdee5 100644 --- a/modules/ticket/back/methods/ticket/specs/isEditable.spec.js +++ b/modules/ticket/back/methods/ticket/specs/isEditable.spec.js @@ -1,8 +1,8 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('ticket isEditable()', () => { it('should return false if the given ticket does not exist', async() => { - const tx = await app.models.Ticket.beginTransaction({}); + const tx = await models.Ticket.beginTransaction({}); let result; try { @@ -11,7 +11,7 @@ describe('ticket isEditable()', () => { req: {accessToken: {userId: 9}} }; - result = await app.models.Ticket.isEditable(ctx, 9999, options); + result = await models.Ticket.isEditable(ctx, 9999, options); await tx.rollback(); } catch (e) { @@ -23,12 +23,12 @@ describe('ticket isEditable()', () => { }); it(`should return false if the given ticket isn't invoiced but isDeleted`, async() => { - const tx = await app.models.Ticket.beginTransaction({}); + const tx = await models.Ticket.beginTransaction({}); let result; try { const options = {transaction: tx}; - const deletedTicket = await app.models.Ticket.findOne({ + const deletedTicket = await models.Ticket.findOne({ where: { invoiceOut: null, isDeleted: true @@ -40,7 +40,7 @@ describe('ticket isEditable()', () => { req: {accessToken: {userId: 9}} }; - result = await app.models.Ticket.isEditable(ctx, deletedTicket.id, options); + result = await models.Ticket.isEditable(ctx, deletedTicket.id, options); await tx.rollback(); } catch (e) { @@ -52,7 +52,7 @@ describe('ticket isEditable()', () => { }); it('should return true if the given ticket is editable', async() => { - const tx = await app.models.Ticket.beginTransaction({}); + const tx = await models.Ticket.beginTransaction({}); let result; try { @@ -61,7 +61,7 @@ describe('ticket isEditable()', () => { req: {accessToken: {userId: 9}} }; - result = await app.models.Ticket.isEditable(ctx, 16, options); + result = await models.Ticket.isEditable(ctx, 16, options); await tx.rollback(); } catch (e) { @@ -73,7 +73,7 @@ describe('ticket isEditable()', () => { }); it('should not be able to edit a deleted or invoiced ticket even for salesAssistant', async() => { - const tx = await app.models.Ticket.beginTransaction({}); + const tx = await models.Ticket.beginTransaction({}); let result; try { @@ -82,7 +82,7 @@ describe('ticket isEditable()', () => { req: {accessToken: {userId: 21}} }; - result = await app.models.Ticket.isEditable(ctx, 19, options); + result = await models.Ticket.isEditable(ctx, 19, options); await tx.rollback(); } catch (e) { @@ -94,7 +94,7 @@ describe('ticket isEditable()', () => { }); it('should not be able to edit a deleted or invoiced ticket even for productionBoss', async() => { - const tx = await app.models.Ticket.beginTransaction({}); + const tx = await models.Ticket.beginTransaction({}); let result; try { @@ -103,7 +103,7 @@ describe('ticket isEditable()', () => { req: {accessToken: {userId: 50}} }; - result = await app.models.Ticket.isEditable(ctx, 19, options); + result = await models.Ticket.isEditable(ctx, 19, options); await tx.rollback(); } catch (e) { @@ -115,7 +115,7 @@ describe('ticket isEditable()', () => { }); it('should not be able to edit a deleted or invoiced ticket even for salesPerson', async() => { - const tx = await app.models.Ticket.beginTransaction({}); + const tx = await models.Ticket.beginTransaction({}); let result; try { @@ -124,7 +124,7 @@ describe('ticket isEditable()', () => { req: {accessToken: {userId: 18}} }; - result = await app.models.Ticket.isEditable(ctx, 19, options); + result = await models.Ticket.isEditable(ctx, 19, options); await tx.rollback(); } catch (e) { diff --git a/modules/ticket/back/methods/ticket/specs/isEmpty.spec.js b/modules/ticket/back/methods/ticket/specs/isEmpty.spec.js index df88182612..ffa71f523d 100644 --- a/modules/ticket/back/methods/ticket/specs/isEmpty.spec.js +++ b/modules/ticket/back/methods/ticket/specs/isEmpty.spec.js @@ -1,27 +1,71 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('ticket isEmpty()', () => { it('should return false if the ticket contains any packages', async() => { - let result = await app.models.Ticket.isEmpty(3); + const tx = await models.Ticket.beginTransaction({}); - expect(result).toBeFalsy(); + try { + const options = {transaction: tx}; + + const result = await models.Ticket.isEmpty(3, options); + + expect(result).toBeFalsy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return false if the ticket contains any services', async() => { - let result = await app.models.Ticket.isEmpty(8); + const tx = await models.Ticket.beginTransaction({}); - expect(result).toBeFalsy(); + try { + const options = {transaction: tx}; + + const result = await models.Ticket.isEmpty(8, options); + + expect(result).toBeFalsy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return false if the ticket contains any purchase request', async() => { - let result = await app.models.Ticket.isEmpty(11); + const tx = await models.Ticket.beginTransaction({}); - expect(result).toBeFalsy(); + try { + const options = {transaction: tx}; + + const result = await models.Ticket.isEmpty(11, options); + + expect(result).toBeFalsy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return false if the ticket contains any sale', async() => { - let result = await app.models.Ticket.isEmpty(4); + const tx = await models.Ticket.beginTransaction({}); - expect(result).toBeFalsy(); + try { + const options = {transaction: tx}; + + const result = await models.Ticket.isEmpty(4, options); + + expect(result).toBeFalsy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/ticket/back/methods/ticket/specs/isLocked.spec.js b/modules/ticket/back/methods/ticket/specs/isLocked.spec.js index 192c80f100..7d161ad82a 100644 --- a/modules/ticket/back/methods/ticket/specs/isLocked.spec.js +++ b/modules/ticket/back/methods/ticket/specs/isLocked.spec.js @@ -1,34 +1,67 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('ticket isLocked()', () => { it('should return true if the given ticket does not exist', async() => { - let result = await app.models.Ticket.isLocked(99999); + const tx = await models.Ticket.beginTransaction({}); - expect(result).toEqual(true); + try { + const options = {transaction: tx}; + + const result = await models.Ticket.isLocked(99999, options); + + expect(result).toEqual(true); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return true if the given ticket is invoiced', async() => { - let invoicedTicket = await app.models.Ticket.findOne({ - where: {invoiceOut: {neq: null}}, - fields: ['id'] - }); + const tx = await models.Ticket.beginTransaction({}); - let result = await app.models.Ticket.isLocked(invoicedTicket.id); + try { + const options = {transaction: tx}; - expect(result).toEqual(true); + const invoicedTicket = await models.Ticket.findOne({ + where: {invoiceOut: {neq: null}}, + fields: ['id'] + }, options); + + const result = await models.Ticket.isLocked(invoicedTicket.id, options); + + expect(result).toEqual(true); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it(`should return true if the given ticket isn't invoiced but deleted`, async() => { - let deletedTicket = await app.models.Ticket.findOne({ - where: { - invoiceOut: null, - isDeleted: true - }, - fields: ['id'] - }); + const tx = await models.Ticket.beginTransaction({}); - let result = await app.models.Ticket.isLocked(deletedTicket.id); + try { + const options = {transaction: tx}; - expect(result).toEqual(true); + const deletedTicket = await models.Ticket.findOne({ + where: { + invoiceOut: null, + isDeleted: true + }, + fields: ['id'] + }, options); + + const result = await models.Ticket.isLocked(deletedTicket.id, options); + + expect(result).toEqual(true); + + 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 32c769ca4c..36fc6732b3 100644 --- a/modules/ticket/back/methods/ticket/specs/makeInvoice.spec.js +++ b/modules/ticket/back/methods/ticket/specs/makeInvoice.spec.js @@ -1,18 +1,16 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('ticket makeInvoice()', () => { const userId = 19; + const ticketId = 11; + const clientId = 1102; const activeCtx = { accessToken: {userId: userId}, headers: {origin: 'http://localhost:5000'}, }; const ctx = {req: activeCtx}; - let invoice; - let ticketId = 11; - const okState = 3; - beforeAll(async done => { spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ active: activeCtx @@ -21,47 +19,94 @@ describe('ticket makeInvoice()', () => { done(); }); - afterAll(async done => { - try { - let ticket = await app.models.Ticket.findById(11); - await ticket.updateAttributes({refFk: null}); - - let ticketTrackings = await app.models.TicketTracking.find({ - where: { - ticketFk: ticketId, - stateFk: {neq: okState} - }, - order: 'id DESC' - }); - - for (let state of ticketTrackings) - await state.destroy(); - - let invoiceOut = await app.models.InvoiceOut.findById(invoice.invoiceFk); - await invoiceOut.destroy(); - } catch (error) { - console.error(error); - } - done(); - }); - - it('should invoice a ticket, then try again to fail', async() => { - const invoiceOutModel = app.models.InvoiceOut; + it('should throw an error when invoicing tickets from multiple clients', async() => { + const invoiceOutModel = models.InvoiceOut; spyOn(invoiceOutModel, 'createPdf'); - invoice = await app.models.Ticket.makeInvoice(ctx, ticketId); - - expect(invoice.invoiceFk).toBeDefined(); - expect(invoice.serial).toEqual('T'); + const tx = await models.Ticket.beginTransaction({}); let error; - await app.models.Ticket.makeInvoice(ctx, ticketId).catch(e => { - error = e; - }).finally(() => { - expect(error.message).toEqual(`This ticket can't be invoiced`); - }); + try { + const options = {transaction: tx}; + const otherClientTicketId = 16; + await models.Ticket.makeInvoice(ctx, [ticketId, otherClientTicketId], options); - expect(error).toBeDefined(); + await tx.rollback(); + } catch (e) { + error = e; + await tx.rollback(); + } + + expect(error.message).toEqual(`You can't invoice tickets from multiple clients`); + }); + + it(`should throw an error when invoicing a client without tax data checked`, async() => { + const invoiceOutModel = models.InvoiceOut; + spyOn(invoiceOutModel, 'createPdf'); + + const tx = await models.Ticket.beginTransaction({}); + + let error; + + try { + const options = {transaction: tx}; + + const client = await models.Client.findById(clientId, null, options); + await client.updateAttribute('isTaxDataChecked', false, options); + + await models.Ticket.makeInvoice(ctx, [ticketId], options); + + await tx.rollback(); + } catch (e) { + error = e; + await tx.rollback(); + } + + expect(error.message).toEqual(`This client can't be invoiced`); + }); + + it('should invoice a ticket, then try again to fail', async() => { + const invoiceOutModel = models.InvoiceOut; + spyOn(invoiceOutModel, 'createPdf'); + + const tx = await models.Ticket.beginTransaction({}); + + let error; + + try { + const options = {transaction: tx}; + + await models.Ticket.makeInvoice(ctx, [ticketId], options); + await models.Ticket.makeInvoice(ctx, [ticketId], options); + + await tx.rollback(); + } catch (e) { + error = e; + await tx.rollback(); + } + + expect(error.message).toEqual(`Some of the selected tickets are not billable`); + }); + + it('should success to invoice a ticket', async() => { + const invoiceOutModel = models.InvoiceOut; + spyOn(invoiceOutModel, 'createPdf'); + + const tx = await models.Ticket.beginTransaction({}); + + try { + const options = {transaction: tx}; + + const invoice = await models.Ticket.makeInvoice(ctx, [ticketId], options); + + expect(invoice.invoiceFk).toBeDefined(); + expect(invoice.serial).toEqual('T'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/ticket/back/methods/ticket/specs/new.spec.js b/modules/ticket/back/methods/ticket/specs/new.spec.js index 7ffcab68e5..fce7cdceb6 100644 --- a/modules/ticket/back/methods/ticket/specs/new.spec.js +++ b/modules/ticket/back/methods/ticket/specs/new.spec.js @@ -1,118 +1,119 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; let UserError = require('vn-loopback/util/user-error'); describe('ticket new()', () => { - let ticketIdsToDelete = []; - let today = new Date(); - let ctx = {req: {accessToken: {userId: 1}}}; - - afterAll(async done => { - for (id of ticketIdsToDelete) - await app.models.Ticket.destroyById(id); - - done(); - }); + const today = new Date(); + const ctx = {req: {accessToken: {userId: 1}}}; it('should throw an error if the client isnt frozen and isnt active', async() => { - let error; - let params = { - clientId: 106, - shipped: today, - landed: null, - warehouseId: 1, - companyId: 442, - addressId: 6 - }; + const tx = await models.Ticket.beginTransaction({}); - await app.models.Ticket.new(ctx, - params.clientId, - params.shipped, - params.landed, - params.warehouseId, - params.companyId, - params.addressId - ).catch(e => { + let error; + + try { + const options = {transaction: tx}; + + ctx.args = { + clientId: 1106, + shipped: today, + landed: null, + warehouseId: 1, + companyId: 442, + addressId: 6 + }; + + await models.Ticket.new(ctx, options); + + await tx.rollback(); + } catch (e) { error = e; - }); + await tx.rollback(); + } expect(error).toEqual(new UserError(`You can't create a ticket for a inactive client`)); }); it('should throw an error if the address doesnt exist', async() => { + const tx = await models.Ticket.beginTransaction({}); + let error; - let params = { - clientId: 104, - shipped: today, - landed: null, - warehouseId: 1, - companyId: 442, - addressId: 'invalid address' - }; - await app.models.Ticket.new(ctx, - params.clientId, - params.shipped, - params.landed, - params.warehouseId, - params.companyId, - params.addressId - ).catch(response => { - expect(response.message).toEqual(`This address doesn't exist`); - error = response; - }); + try { + const options = {transaction: tx}; - expect(error).toBeDefined(); + ctx.args = { + clientId: 1104, + shipped: today, + landed: null, + warehouseId: 1, + companyId: 442, + addressId: 'invalid address' + }; + + await models.Ticket.new(ctx, options); + + await tx.rollback(); + } catch (e) { + error = e; + await tx.rollback(); + } + + expect(error.message).toEqual(`This address doesn't exist`); }); it('should return the id of the created ticket', async() => { - let params = { - clientId: 104, - shipped: today, - landed: today, - warehouseId: 2, - companyId: 442, - addressId: 4, - agencyModeId: 1 - }; + const tx = await models.Ticket.beginTransaction({}); - const ticket = await app.models.Ticket.new(ctx, - params.clientId, - params.shipped, - params.landed, - params.warehouseId, - params.companyId, - params.addressId, - params.agencyModeId); + try { + const options = {transaction: tx}; - let newestTicketIdInFixtures = 21; + ctx.args = { + clientId: 1104, + shipped: today, + landed: today, + warehouseId: 2, + companyId: 442, + addressId: 4, + agencyModeId: 1 + }; - ticketIdsToDelete.push(ticket.id); + const ticket = await models.Ticket.new(ctx, options); - expect(ticket.id).toBeGreaterThan(newestTicketIdInFixtures); + const newestTicketIdInFixtures = 21; + + expect(ticket.id).toBeGreaterThan(newestTicketIdInFixtures); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the set a shipped when the agency is not especified', async() => { - let params = { - clientId: 104, - landed: today, - shipped: null, - warehouseId: 2, - companyId: 442, - addressId: 4, - agencyModeId: null - }; + const tx = await models.Ticket.beginTransaction({}); - const ticket = await app.models.Ticket.new(ctx, - params.clientId, - params.shipped, - params.landed, - params.warehouseId, - params.companyId, - params.addressId, - params.agencyModeId); + try { + const options = {transaction: tx}; - ticketIdsToDelete.push(ticket.id); + ctx.args = { + clientId: 1104, + landed: today, + shipped: null, + warehouseId: 2, + companyId: 442, + addressId: 4, + agencyModeId: null + }; - expect(ticket.shipped).toEqual(jasmine.any(Date)); + const ticket = await models.Ticket.new(ctx, options); + + expect(ticket.shipped).toEqual(jasmine.any(Date)); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/ticket/back/methods/ticket/specs/priceDifference.spec.js b/modules/ticket/back/methods/ticket/specs/priceDifference.spec.js index 062be6b226..fed899d779 100644 --- a/modules/ticket/back/methods/ticket/specs/priceDifference.spec.js +++ b/modules/ticket/back/methods/ticket/specs/priceDifference.spec.js @@ -1,38 +1,61 @@ -const app = require('vn-loopback/server/server'); -let UserError = require('vn-loopback/util/user-error'); +const models = require('vn-loopback/server/server').models; +const UserError = require('vn-loopback/util/user-error'); describe('sale priceDifference()', () => { it('should return ticket price differences', async() => { - let tomorrow = new Date(); - tomorrow.setDate(tomorrow.getDate() + 1); + const tx = await models.Ticket.beginTransaction({}); - const ticketId = 16; - const landed = tomorrow; - const addressId = 126; - const agencyModeId = 7; - const zoneId = 3; - const warehouseId = 1; + try { + const options = {transaction: tx}; - const httpCtx = {req: {accessToken: {userId: 106}}}; - let result = await app.models.Ticket.priceDifference(httpCtx, ticketId, landed, - addressId, agencyModeId, zoneId, warehouseId); + const tomorrow = new Date(); + tomorrow.setDate(tomorrow.getDate() + 1); - expect(result.totalUnitPrice).toEqual(result.totalNewPrice); - expect(result.totalDifference).toEqual(0); + const ctx = {req: {accessToken: {userId: 1106}}}; + ctx.args = { + id: 16, + landed: tomorrow, + addressId: 126, + agencyModeId: 7, + zoneId: 3, + warehouseId: 1 + }; + + const result = await models.Ticket.priceDifference(ctx, options); + + expect(result.totalUnitPrice).toEqual(result.totalNewPrice); + expect(result.totalDifference).toEqual(0); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return an error if the ticket is not editable', async() => { - const ticketId = 1; - const landed = new Date(); - const addressId = 121; - const zoneId = 3; - const warehouseId = 1; + const tx = await models.Ticket.beginTransaction({}); + let error; - const httpCtx = {req: {accessToken: {userId: 106}}}; - await app.models.Ticket.priceDifference(httpCtx, ticketId, landed, addressId, zoneId, warehouseId) - .catch(e => { - error = e; - }); + + try { + const options = {transaction: tx}; + + const ctx = {req: {accessToken: {userId: 1106}}}; + ctx.args = { + id: 1, + landed: new Date(), + addressId: 121, + zoneId: 3, + warehouseId: 1 + }; + await models.Ticket.priceDifference(ctx, options); + + await tx.rollback(); + } catch (e) { + error = e; + await tx.rollback(); + } expect(error).toEqual(new UserError(`The sales of this ticket can't be modified`)); }); diff --git a/modules/ticket/back/methods/ticket/specs/restore.spec.js b/modules/ticket/back/methods/ticket/specs/restore.spec.js index 52135fc542..bd976d1247 100644 --- a/modules/ticket/back/methods/ticket/specs/restore.spec.js +++ b/modules/ticket/back/methods/ticket/specs/restore.spec.js @@ -3,7 +3,7 @@ const LoopBackContext = require('loopback-context'); const models = app.models; describe('ticket restore()', () => { - const employeeUser = 110; + const employeeUser = 1110; const ticketId = 18; const activeCtx = { accessToken: {userId: employeeUser}, diff --git a/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js b/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js index 6bd2651697..7d200a72df 100644 --- a/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js +++ b/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js @@ -3,8 +3,8 @@ const LoopBackContext = require('loopback-context'); const models = app.models; describe('ticket setDeleted()', () => { - const userId = 106; - const employeeUser = 110; + const userId = 1106; + const employeeUser = 1110; const activeCtx = { accessToken: {userId: userId}, }; diff --git a/modules/ticket/back/methods/ticket/specs/summary.spec.js b/modules/ticket/back/methods/ticket/specs/summary.spec.js index 0402c0a569..7d29e8258f 100644 --- a/modules/ticket/back/methods/ticket/specs/summary.spec.js +++ b/modules/ticket/back/methods/ticket/specs/summary.spec.js @@ -17,12 +17,12 @@ describe('ticket summary()', () => { it('should return a summary object containing totalWithoutVat for 1 ticket', async() => { let result = await app.models.Ticket.summary(1); - expect(result.totalWithoutVat).toEqual(807.23); + expect(result.totalWithoutVat).toEqual(jasmine.any(Number)); }); it('should return a summary object containing total for 1 ticket', async() => { let result = await app.models.Ticket.summary(1); - expect(result.totalWithVat).toEqual(891.87); + expect(result.totalWithVat).toEqual(jasmine.any(Number)); }); }); diff --git a/modules/ticket/back/methods/ticket/specs/transferSales.spec.js b/modules/ticket/back/methods/ticket/specs/transferSales.spec.js index 3d62ccce98..5a37abef4e 100644 --- a/modules/ticket/back/methods/ticket/specs/transferSales.spec.js +++ b/modules/ticket/back/methods/ticket/specs/transferSales.spec.js @@ -2,7 +2,7 @@ const app = require('vn-loopback/server/server'); const LoopBackContext = require('loopback-context'); describe('sale transferSales()', () => { - const userId = 101; + const userId = 1101; const activeCtx = { accessToken: {userId: userId}, }; diff --git a/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js b/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js index 2e71842b4e..406a3f3ee2 100644 --- a/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js +++ b/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js @@ -35,7 +35,13 @@ describe('sale updateDiscount()', () => { }); it('should throw an error if no sales were selected', async() => { - let ctx = {req: {accessToken: {userId: 9}}}; + const ctx = { + req: { + accessToken: {userId: 9}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; let error; const ticketId = 11; const sales = []; @@ -51,7 +57,13 @@ describe('sale updateDiscount()', () => { }); it('should throw an error if no sales belong to different tickets', async() => { - let ctx = {req: {accessToken: {userId: 9}}}; + const ctx = { + req: { + accessToken: {userId: 9}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; let error; const ticketId = 11; const sales = [1, 14]; @@ -67,7 +79,13 @@ describe('sale updateDiscount()', () => { }); it('should throw an error if the ticket is invoiced already', async() => { - let ctx = {req: {accessToken: {userId: 9}}}; + const ctx = { + req: { + accessToken: {userId: 9}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; let error; const ticketId = 1; const sales = [1]; @@ -83,7 +101,13 @@ describe('sale updateDiscount()', () => { }); it('should update the discount if the salesPerson has mana', async() => { - let ctx = {req: {accessToken: {userId: 18}}}; + const ctx = { + req: { + accessToken: {userId: 18}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; const ticketId = 11; const sales = [originalSaleId]; const newDiscount = 100; @@ -105,7 +129,13 @@ describe('sale updateDiscount()', () => { }); it('should update the discount and add company discount component if the worker does not have mana', async() => { - let ctx = {req: {accessToken: {userId: 9}}}; + const ctx = { + req: { + accessToken: {userId: 9}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; const ticketId = 11; const sales = [originalSaleId]; const newDiscount = 100; diff --git a/modules/ticket/back/methods/ticket/specs/uploadFile.spec.js b/modules/ticket/back/methods/ticket/specs/uploadFile.spec.js index 78b935ab56..4ad6894112 100644 --- a/modules/ticket/back/methods/ticket/specs/uploadFile.spec.js +++ b/modules/ticket/back/methods/ticket/specs/uploadFile.spec.js @@ -3,7 +3,7 @@ const app = require('vn-loopback/server/server'); describe('Ticket uploadFile()', () => { it(`should return an error for a user without enough privileges`, async() => { let ticketId = 15; - let currentUserId = 101; + let currentUserId = 1101; let ticketTypeId = 14; let ctx = {req: {accessToken: {userId: currentUserId}}, args: {dmsTypeId: ticketTypeId}}; diff --git a/modules/ticket/back/methods/ticket/updateDiscount.js b/modules/ticket/back/methods/ticket/updateDiscount.js index 1bebaae8dc..c9424395d3 100644 --- a/modules/ticket/back/methods/ticket/updateDiscount.js +++ b/modules/ticket/back/methods/ticket/updateDiscount.js @@ -17,7 +17,8 @@ module.exports = Self => { description: 'The sales id', type: ['number'], required: true, - }, { + }, + { arg: 'newDiscount', description: 'The new discount', type: 'number', @@ -35,6 +36,7 @@ module.exports = Self => { }); Self.updateDiscount = async(ctx, id, salesIds, newDiscount) => { + const $t = ctx.req.__; // $translate const models = Self.app.models; const tx = await Self.beginTransaction({}); @@ -59,7 +61,7 @@ module.exports = Self => { } }; - let sales = await models.Sale.find(filter, options); + const sales = await models.Sale.find(filter, options); if (sales.length === 0) throw new UserError('Please select at least one sale'); @@ -94,8 +96,11 @@ module.exports = Self => { where: {code: componentCode}}, options); const componentId = discountComponent.id; - let promises = []; + const promises = []; + let changesMade = ''; + for (let sale of sales) { + const oldDiscount = sale.discount; const value = ((-sale.price * newDiscount) / 100); const newComponent = models.SaleComponent.upsert({ saleFk: sale.id, @@ -105,6 +110,7 @@ module.exports = Self => { const updatedSale = sale.updateAttribute('discount', newDiscount, options); promises.push(newComponent, updatedSale); + changesMade += `\r\n-${sale.itemFk}: ${sale.concept} (${sale.quantity}) ${oldDiscount}% ➔ *${newDiscount}%*`; } await Promise.all(promises); @@ -112,6 +118,32 @@ module.exports = Self => { const query = `call vn.manaSpellersRequery(?)`; await Self.rawSql(query, [userId], options); + const ticket = await models.Ticket.findById(id, { + include: { + relation: 'client', + scope: { + include: { + relation: 'salesPersonUser', + scope: { + fields: ['id', 'name'] + } + } + } + } + }, options); + + const salesPerson = ticket.client().salesPersonUser(); + if (salesPerson) { + const origin = ctx.req.headers.origin; + + const message = $t('Changed sale discount', { + ticketId: id, + ticketUrl: `${origin}/#!/ticket/${id}/sale`, + changes: changesMade + }); + await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); + } + await tx.commit(); } catch (error) { await tx.rollback(); diff --git a/modules/ticket/back/models/alert-level.json b/modules/ticket/back/models/alert-level.json index a94c011063..222e981089 100644 --- a/modules/ticket/back/models/alert-level.json +++ b/modules/ticket/back/models/alert-level.json @@ -9,13 +9,12 @@ }, "properties": { "code": { - "type": "String", + "type": "string" + }, + "id": { + "type": "number", "id": true, "description": "Identifier" - }, - "alertLevel": { - "type": "Number", - "id": true } }, "acls": [ diff --git a/modules/ticket/back/models/state.json b/modules/ticket/back/models/state.json index efa56abee7..9d4dd4f5d6 100644 --- a/modules/ticket/back/models/state.json +++ b/modules/ticket/back/models/state.json @@ -9,23 +9,23 @@ "properties": { "id": { "id": true, - "type": "Number", + "type": "number", "forceId": false }, "name": { - "type": "String", + "type": "string", "required": false }, "order": { - "type": "Number", + "type": "number", "required": false }, "alertLevel": { - "type": "Number", + "type": "number", "required": false }, "code": { - "type": "String", + "type": "string", "required": false } } diff --git a/modules/ticket/back/models/ticket-dms.js b/modules/ticket/back/models/ticket-dms.js index ddb338632e..9bceaae6eb 100644 --- a/modules/ticket/back/models/ticket-dms.js +++ b/modules/ticket/back/models/ticket-dms.js @@ -1,3 +1,11 @@ +const UserError = require('vn-loopback/util/user-error'); + module.exports = Self => { require('../methods/ticket-dms/removeFile')(Self); + + Self.rewriteDbError(function(err) { + if (err.code === 'ER_DUP_ENTRY') + return new UserError('This document already exists on this ticket'); + return err; + }); }; diff --git a/modules/ticket/back/models/ticket-dms.json b/modules/ticket/back/models/ticket-dms.json index b7b24dce00..8bcff254c6 100644 --- a/modules/ticket/back/models/ticket-dms.json +++ b/modules/ticket/back/models/ticket-dms.json @@ -12,7 +12,7 @@ }, "properties": { "dmsFk": { - "type": "Number", + "type": "number", "id": true, "required": true } diff --git a/modules/ticket/back/models/ticket-state.json b/modules/ticket/back/models/ticket-state.json index a7f0f8242d..a10938ef01 100644 --- a/modules/ticket/back/models/ticket-state.json +++ b/modules/ticket/back/models/ticket-state.json @@ -9,14 +9,14 @@ "properties": { "ticketFk": { "id": true, - "type": "Number", + "type": "number", "forceId": false }, "updated": { - "type": "Date" + "type": "date" }, "alertLevel": { - "type": "Number" + "type": "number" }, "code": { "type": "string" diff --git a/modules/ticket/back/models/ticket.js b/modules/ticket/back/models/ticket.js index 8159d254d2..b217eae4d6 100644 --- a/modules/ticket/back/models/ticket.js +++ b/modules/ticket/back/models/ticket.js @@ -2,7 +2,6 @@ const LoopBackContext = require('loopback-context'); module.exports = Self => { - require('../methods/ticket/changeWorker')(Self); require('../methods/ticket/getVolume')(Self); require('../methods/ticket/getTotalVolume')(Self); require('../methods/ticket/summary')(Self); diff --git a/modules/ticket/front/basic-data/step-one/index.html b/modules/ticket/front/basic-data/step-one/index.html index 24ec509a24..498630b87f 100644 --- a/modules/ticket/front/basic-data/step-one/index.html +++ b/modules/ticket/front/basic-data/step-one/index.html @@ -19,6 +19,9 @@ ng-model="$ctrl.clientId" initial-data="$ctrl.clientId" order="id"> + + #{{id}} - {{::name}} + { describe('ticket() setter', () => { it('should set ticket property and call clientAddressesList() method', () => { jest.spyOn(controller, 'clientAddressesList'); - controller.ticket = {id: 1, clientFk: 101}; + controller.ticket = {id: 1, clientFk: 1101}; - expect(controller.clientAddressesList).toHaveBeenCalledWith(101); + expect(controller.clientAddressesList).toHaveBeenCalledWith(1101); }); it(`should not call clientAddressesList() method as the ticket doesn't have an ID`, () => { @@ -38,19 +38,19 @@ describe('Ticket', () => { describe('clientId() getter', () => { it('should return the clientFk property', () => { - controller.ticket = {id: 1, clientFk: 102}; + controller.ticket = {id: 1, clientFk: 1102}; - expect(controller.clientId).toEqual(102); + expect(controller.clientId).toEqual(1102); }); }); describe('clientId() setter', () => { it('should set clientId property and call clientAddressesList() method ', () => { jest.spyOn(controller, 'clientAddressesList'); - controller.ticket = {id: 1, clientId: 101}; - controller.clientId = 102; + controller.ticket = {id: 1, clientId: 1101}; + controller.clientId = 1102; - expect(controller.clientAddressesList).toHaveBeenCalledWith(102); + expect(controller.clientAddressesList).toHaveBeenCalledWith(1102); }); }); @@ -222,7 +222,7 @@ describe('Ticket', () => { describe('clientAddressesList()', () => { it('should return a list of addresses from choosed client', async() => { - const clientId = 102; + const clientId = 1102; let filter = { include: [ { @@ -249,7 +249,7 @@ describe('Ticket', () => { describe('getClientDefaultAddress()', () => { it('should return the default address from choosed client', async() => { - const clientId = 102; + const clientId = 1102; $httpBackend.expect('GET', `Clients/${clientId}`).respond(200); controller.getClientDefaultAddress(clientId); diff --git a/modules/ticket/front/descriptor-menu/index.js b/modules/ticket/front/descriptor-menu/index.js index 17ed36ab57..5da9544e2b 100644 --- a/modules/ticket/front/descriptor-menu/index.js +++ b/modules/ticket/front/descriptor-menu/index.js @@ -217,7 +217,8 @@ class Controller extends Section { } makeInvoice() { - return this.$http.post(`Tickets/${this.id}/makeInvoice`) + const params = {ticketsIds: [this.id]}; + return this.$http.post(`Tickets/makeInvoice`, params) .then(() => this.reload()) .then(() => this.vnApp.showSuccess(this.$t('Ticket invoiced'))); } diff --git a/modules/ticket/front/descriptor-menu/index.spec.js b/modules/ticket/front/descriptor-menu/index.spec.js index 6a3009daf7..b102b1f445 100644 --- a/modules/ticket/front/descriptor-menu/index.spec.js +++ b/modules/ticket/front/descriptor-menu/index.spec.js @@ -7,14 +7,14 @@ describe('Ticket Component vnTicketDescriptorMenu', () => { const ticket = { id: 16, - clientFk: 101, + clientFk: 1101, invoiceOut: {id: 1}, client: { - id: 101, + id: 1101, email: 'client@email' }, address: { - id: 101, + id: 1101, mobile: 111111111, phone: 2222222222 }, @@ -139,7 +139,8 @@ describe('Ticket Component vnTicketDescriptorMenu', () => { jest.spyOn(controller, 'reload').mockReturnThis(); jest.spyOn(controller.vnApp, 'showSuccess'); - $httpBackend.expectPOST(`Tickets/${ticket.id}/makeInvoice`).respond(); + const expectedParams = {ticketsIds: [ticket.id]}; + $httpBackend.expectPOST(`Tickets/makeInvoice`, expectedParams).respond(); controller.makeInvoice(); $httpBackend.flush(); diff --git a/modules/ticket/front/descriptor/index.spec.js b/modules/ticket/front/descriptor/index.spec.js index 608808448c..292ab8d551 100644 --- a/modules/ticket/front/descriptor/index.spec.js +++ b/modules/ticket/front/descriptor/index.spec.js @@ -7,14 +7,14 @@ describe('Ticket Component vnTicketDescriptor', () => { const ticket = { id: 2, - clientFk: 101, + clientFk: 1101, invoiceOut: {id: 1}, client: { - id: 101, + id: 1101, email: 'client@email' }, address: { - id: 101, + id: 1101, mobile: 111111111, phone: 2222222222 }, diff --git a/modules/ticket/front/dms/create/index.spec.js b/modules/ticket/front/dms/create/index.spec.js index 15017daf95..981839cd49 100644 --- a/modules/ticket/front/dms/create/index.spec.js +++ b/modules/ticket/front/dms/create/index.spec.js @@ -17,7 +17,7 @@ describe('Ticket', () => { controller = $componentController('vnTicketDmsCreate', {$element}); controller._ticket = { id: 15, - client: {id: 101, name: 'Bruce wayne'}, + client: {id: 1101, name: 'Bruce wayne'}, warehouseFk: 1, companyFk: 1 }; diff --git a/modules/ticket/front/dms/edit/index.spec.js b/modules/ticket/front/dms/edit/index.spec.js index 15ab588f79..d755dc1504 100644 --- a/modules/ticket/front/dms/edit/index.spec.js +++ b/modules/ticket/front/dms/edit/index.spec.js @@ -36,7 +36,7 @@ describe('Ticket', () => { it('should perform a GET query and define the dms property on controller', () => { const dmsId = 1; const expectedResponse = { - reference: 101, + reference: 1101, warehouseFk: 1, companyFk: 442, dmsTypeFk: 14, @@ -50,7 +50,7 @@ describe('Ticket', () => { $httpBackend.flush(); expect(controller.dms).toBeDefined(); - expect(controller.dms.reference).toEqual(101); + expect(controller.dms.reference).toEqual(1101); expect(controller.dms.dmsTypeId).toEqual(14); }); }); diff --git a/modules/ticket/front/dms/index/index.html b/modules/ticket/front/dms/index/index.html index 203ceb6350..5e55ab366e 100644 --- a/modules/ticket/front/dms/index/index.html +++ b/modules/ticket/front/dms/index/index.html @@ -21,7 +21,7 @@ Original File Employee - Created + Created @@ -69,7 +69,7 @@ {{::document.dms.worker.user.name | dashIfEmpty}} - + {{::document.dms.created | date:'dd/MM/yyyy HH:mm'}} @@ -96,18 +96,48 @@
+
- - - - + - \ No newline at end of file + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/ticket/front/dms/index/index.js b/modules/ticket/front/dms/index/index.js index da6aa6b6fc..2ec7e03c03 100644 --- a/modules/ticket/front/dms/index/index.js +++ b/modules/ticket/front/dms/index/index.js @@ -55,6 +55,28 @@ class Controller extends Section { downloadFile(dmsId) { this.vnFile.download(`api/dms/${dmsId}/downloadFile`); } + + importDms() { + try { + if (!this.dmsId) + throw new Error(`The document indentifier can't be empty`); + + const data = { + ticketFk: this.$params.id, + dmsFk: this.dmsId + }; + + this.$http.post('ticketDms', data).then(() => { + this.vnApp.showSuccess(this.$t('Data saved!')); + this.dmsId = null; + this.$.model.refresh(); + }); + } catch (e) { + this.vnApp.showError(this.$t(e.message)); + return false; + } + return true; + } } Controller.$inject = ['$element', '$scope', 'vnFile']; diff --git a/modules/ticket/front/dms/locale/es.yml b/modules/ticket/front/dms/locale/es.yml index 998960a8ea..fe31838f80 100644 --- a/modules/ticket/front/dms/locale/es.yml +++ b/modules/ticket/front/dms/locale/es.yml @@ -6,4 +6,7 @@ FileDescription: Ticket id {{ticketId}} del cliente {{clientName}} id {{clientId Generate identifier for original file: Generar identificador para archivo original ContentTypesInfo: 'Tipos de archivo permitidos: {{allowedContentTypes}}' Are you sure you want to continue?: ¿Seguro que quieres continuar? -File management: Gestión documental \ No newline at end of file +File management: Gestión documental +Select document id: Introduzca id de gestion documental +Import from existing: Importar desde existente +The document indentifier can't be empty: El número de documento no puede estar vacío \ No newline at end of file diff --git a/modules/ticket/front/index/index.html b/modules/ticket/front/index/index.html index 79774c647d..63b0b049d1 100644 --- a/modules/ticket/front/index/index.html +++ b/modules/ticket/front/index/index.html @@ -166,6 +166,15 @@ vn-tooltip="Payment on account..." tooltip-position="left"> + + - \ No newline at end of file + + + + + \ No newline at end of file diff --git a/modules/ticket/front/index/index.js b/modules/ticket/front/index/index.js index 9dc3d81b82..2df4de0a50 100644 --- a/modules/ticket/front/index/index.js +++ b/modules/ticket/front/index/index.js @@ -8,6 +8,7 @@ export default class Controller extends Section { super($element, $); this.vnReport = vnReport; } + setDelivered() { const checkedTickets = this.checked; let ids = []; @@ -74,6 +75,14 @@ export default class Controller extends Section { return this.checked.length; } + get confirmationMessage() { + if (!this.$.model) return 0; + + return this.$t(`Are you sure to invoice tickets`, { + ticketsAmount: this.totalChecked + }); + } + onMoreOpen() { let options = this.moreOptions.filter(o => o.always || this.isChecked); this.$.moreButton.data = options; @@ -159,6 +168,13 @@ export default class Controller extends Section { } return {}; } + + makeInvoice() { + const ticketsIds = this.checked.map(ticket => ticket.id); + return this.$http.post(`Tickets/makeInvoice`, {ticketsIds}) + .then(() => this.$.model.refresh()) + .then(() => this.vnApp.showSuccess(this.$t('Ticket invoiced'))); + } } Controller.$inject = ['$element', '$scope', 'vnReport']; diff --git a/modules/ticket/front/index/locale/en.yml b/modules/ticket/front/index/locale/en.yml new file mode 100644 index 0000000000..6b411b4928 --- /dev/null +++ b/modules/ticket/front/index/locale/en.yml @@ -0,0 +1 @@ +Are you sure to invoice tickets: Are you sure to invoice {{ticketsAmount}} tickets? \ No newline at end of file diff --git a/modules/ticket/front/index/locale/es.yml b/modules/ticket/front/index/locale/es.yml index 9ff8d15684..eac0084f6c 100644 --- a/modules/ticket/front/index/locale/es.yml +++ b/modules/ticket/front/index/locale/es.yml @@ -11,4 +11,9 @@ Remove filter: Quitar filtro por selección Remove all filters: Eliminar todos los filtros Copy value: Copiar valor No verified data: Sin datos comprobados -Component lack: Faltan componentes \ No newline at end of file +Component lack: Faltan componentes +Quick invoice: Factura rápida +Multiple invoice: Factura múltiple +Make invoice...: Crear factura... +Invoice selected tickets: Facturar tickets seleccionados +Are you sure to invoice tickets: ¿Seguro que quieres facturar {{ticketsAmount}} tickets? \ No newline at end of file diff --git a/modules/ticket/front/sale/index.html b/modules/ticket/front/sale/index.html index dec0627c2a..f0fc3aaf35 100644 --- a/modules/ticket/front/sale/index.html +++ b/modules/ticket/front/sale/index.html @@ -59,6 +59,7 @@ + Visible Available Id Quantity @@ -112,6 +113,13 @@ zoom-image="{{::$root.imagePath('catalog', '1600x900', sale.itemFk)}}" on-error-src/> + + + {{::sale.visible}} + + this.edit.mana = res.data); + .then(res => { + this.edit.mana = res.data; + this.$.$applyAsync(() => { + this.$.editDiscount.relocate(); + this.$.editPricePopover.relocate(); + }); + }); } /** diff --git a/modules/ticket/front/sale/index.spec.js b/modules/ticket/front/sale/index.spec.js index f49dc74520..cee1fe5b40 100644 --- a/modules/ticket/front/sale/index.spec.js +++ b/modules/ticket/front/sale/index.spec.js @@ -14,7 +14,7 @@ describe('Ticket', () => { beforeEach(inject(($componentController, $rootScope, _$state_, _$httpBackend_) => { const ticket = { id: 1, - clientFk: 101, + clientFk: 1101, shipped: 1, created: new Date(), client: {salesPersonFk: 1}, @@ -42,6 +42,8 @@ describe('Ticket', () => { $scope.sms = {open: () => {}}; $scope.ticket = ticket; $scope.model = crudModel; + $scope.editDiscount = {relocate: () => {}}; + $scope.editPricePopover = {relocate: () => {}}; $httpBackend = _$httpBackend_; Object.defineProperties($state.params, { id: { @@ -279,7 +281,7 @@ describe('Ticket', () => { firstSale.checked = true; const expectedResponse = [firstSale]; - $httpBackend.expect('GET', `clients/101/lastActiveTickets?ticketId=1`).respond(expectedResponse); + $httpBackend.expect('GET', `clients/1101/lastActiveTickets?ticketId=1`).respond(expectedResponse); controller.setTransferParams(); $httpBackend.flush(); @@ -677,5 +679,21 @@ describe('Ticket', () => { expect(controller.$.model.refresh).toHaveBeenCalledWith(); }); }); + + describe('itemSearchFunc()', () => { + it('should return the filter by id property for an input of a number', () => { + const itemId = 1; + const result = controller.itemSearchFunc(itemId); + + expect(result).toEqual({id: itemId}); + }); + + it('should return the filter by bank property for an input of an string', () => { + const itemName = 'Bow'; + const result = controller.itemSearchFunc(itemName); + + expect(result).toEqual({name: {like: '%' + itemName + '%'}}); + }); + }); }); }); diff --git a/modules/ticket/front/search-panel/index.html b/modules/ticket/front/search-panel/index.html index d0b77b9dea..79dfabb582 100644 --- a/modules/ticket/front/search-panel/index.html +++ b/modules/ticket/front/search-panel/index.html @@ -110,6 +110,11 @@ ng-model="filter.provinceFk" url="Provinces"> + + { describe('onResponse()', () => { it('should perform a POST query and show a success snackbar', () => { - let params = {ticketId: 11, destinationFk: 101, destination: 111111111, message: 'My SMS'}; - controller.sms = {ticketId: 11, destinationFk: 101, destination: 111111111, message: 'My SMS'}; + let params = {ticketId: 11, destinationFk: 1101, destination: 111111111, message: 'My SMS'}; + controller.sms = {ticketId: 11, destinationFk: 1101, destination: 111111111, message: 'My SMS'}; jest.spyOn(controller.vnApp, 'showMessage'); $httpBackend.expect('POST', `Tickets/11/sendSms`, params).respond(200, params); @@ -34,7 +34,7 @@ describe('Ticket', () => { }); it('should call onResponse without the destination and show an error snackbar', () => { - controller.sms = {destinationFk: 101, message: 'My SMS'}; + controller.sms = {destinationFk: 1101, message: 'My SMS'}; jest.spyOn(controller.vnApp, 'showError'); @@ -44,7 +44,7 @@ describe('Ticket', () => { }); it('should call onResponse without the message and show an error snackbar', () => { - controller.sms = {destinationFk: 101, destination: 222222222}; + controller.sms = {destinationFk: 1101, destination: 222222222}; jest.spyOn(controller.vnApp, 'showError'); diff --git a/modules/ticket/front/summary/index.html b/modules/ticket/front/summary/index.html index 8dd43eac47..f353626621 100644 --- a/modules/ticket/front/summary/index.html +++ b/modules/ticket/front/summary/index.html @@ -120,6 +120,7 @@ Item + Visible Available Quantity Description @@ -132,6 +133,12 @@ + + + + + + + {{::sale.visible}} + + { describe('onSubmit()', () => { it('should POST the data, call updateOriginalData, reload, showSuccess and go functions', () => { - controller.params = {stateFk: 22, workerFk: 101}; + controller.params = {stateFk: 22, workerFk: 1101}; jest.spyOn(controller.card, 'reload'); jest.spyOn(controller.$.watcher, 'updateOriginalData'); jest.spyOn(controller.vnApp, 'showSuccess'); diff --git a/modules/ticket/front/tracking/index/index.html b/modules/ticket/front/tracking/index/index.html index 7cb9431ab4..12c4778c99 100644 --- a/modules/ticket/front/tracking/index/index.html +++ b/modules/ticket/front/tracking/index/index.html @@ -28,7 +28,7 @@ {{::tracking.worker.user.name || 'System' | translate}} - {{::tracking.created | date:'dd/MM/yyyy HH:mm'}} + {{::tracking.created | date:'dd/MM/yyyy HH:mm'}} diff --git a/modules/ticket/front/volume/index.spec.js b/modules/ticket/front/volume/index.spec.js index 8ffb1dfc1b..5f6f433fb0 100644 --- a/modules/ticket/front/volume/index.spec.js +++ b/modules/ticket/front/volume/index.spec.js @@ -18,7 +18,7 @@ describe('ticket', () => { }; }}; $state = _$state_; - $state.params.id = 101; + $state.params.id = 1101; const $element = angular.element(''); controller = $componentController('vnTicketVolume', {$element, $scope}); })); diff --git a/modules/travel/back/methods/thermograph/createThermograph.js b/modules/travel/back/methods/thermograph/createThermograph.js index bfca208fe7..137f32ac40 100644 --- a/modules/travel/back/methods/thermograph/createThermograph.js +++ b/modules/travel/back/methods/thermograph/createThermograph.js @@ -4,27 +4,30 @@ module.exports = Self => { accessType: 'WRITE', accepts: [{ arg: 'thermographId', - type: 'String', + type: 'string', description: 'The thermograph id', required: true - }, { + }, + { arg: 'model', - type: 'String', + type: 'string', description: 'The thermograph model', required: true - }, { - arg: 'temperature', - type: 'String', + }, + { + arg: 'temperatureFk', + type: 'string', description: 'The thermograph temperature', required: true - }, { + }, + { arg: 'warehouseId', - type: 'Number', + type: 'number', description: 'The warehouse id', required: true }], returns: { - type: 'Object', + type: 'object', root: true }, http: { @@ -33,27 +36,35 @@ module.exports = Self => { } }); - Self.createThermograph = async(thermographId, model, temperature, warehouseId) => { + Self.createThermograph = async(thermographId, model, temperatureFk, warehouseId, options) => { const models = Self.app.models; - const tx = await Self.beginTransaction({}); + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } try { - const options = {transaction: tx}; const thermograph = await models.Thermograph.create({ id: thermographId, model: model - }, options); + }, myOptions); await Self.rawSql(` - INSERT INTO travelThermograph(thermographFk, warehouseFk, temperature, created) - VALUES (?, ?,?, NOW()) - `, [thermograph.id, warehouseId, temperature], options); + INSERT INTO travelThermograph(thermographFk, warehouseFk, temperatureFk, created) + VALUES (?, ?, ?, NOW()) + `, [thermograph.id, warehouseId, temperatureFk], myOptions); - await tx.commit(); + if (tx) await tx.commit(); return thermograph; } catch (err) { - await tx.rollback(); + if (tx) await tx.rollback(); throw err; } }; diff --git a/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js b/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js index a3fc98aa6d..32014e303c 100644 --- a/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js +++ b/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js @@ -1,47 +1,51 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Termograph createThermograph()', () => { - const models = app.models; const thermographId = '99999-1'; const model = 'DISPOSABLE'; - const temperature = 'COOL'; + const temperatureFk = 'COOL'; const warehouseId = 1; - let createdThermograph; - afterAll(async done => { - let travelThermograpToDelete = await models.TravelThermograph.findOne({where: {thermographFk: createdThermograph.id}}); - let thermograpToDelete = await models.Thermograph.findById(createdThermograph.id); + it(`should create a thermograph which is saved in both thermograph and travelThermograph`, async() => { + const tx = await models.Thermograph.beginTransaction({}); - await travelThermograpToDelete.destroy(); - await thermograpToDelete.destroy(); + try { + const options = {transaction: tx}; - done(); + const createdThermograph = await models.Thermograph.createThermograph(thermographId, model, temperatureFk, warehouseId, options); + + expect(createdThermograph.id).toEqual(thermographId); + expect(createdThermograph.model).toEqual(model); + + const createdTravelThermograpth = await models.TravelThermograph.findOne({where: {thermographFk: thermographId}}, options); + + expect(createdTravelThermograpth.warehouseFk).toEqual(warehouseId); + expect(createdTravelThermograpth.temperatureFk).toEqual(temperatureFk); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); - it(`should be able to create just once a thermograph which is saved in both thermograph and travelThermograph`, async() => { - let createdTravelThermograpth = await models.TravelThermograph.findOne({where: {thermographFk: thermographId}}); - - expect(createdTravelThermograpth).toBeNull(); - - createdThermograph = await models.Thermograph.createThermograph(thermographId, model, temperature, warehouseId); - - expect(createdThermograph.id).toEqual(thermographId); - expect(createdThermograph.model).toEqual(model); - - createdTravelThermograpth = await models.TravelThermograph.findOne({where: {thermographFk: thermographId}}); - - expect(createdTravelThermograpth.warehouseFk).toEqual(warehouseId); - expect(createdTravelThermograpth.temperature).toEqual(temperature); + it(`should throw an error when trying to created repeated thermograph`, async() => { + const tx = await models.Thermograph.beginTransaction({}); let error; try { - await models.Thermograph.createThermograph(thermographId, model, temperature, warehouseId); + const options = {transaction: tx}; + + await models.Thermograph.createThermograph(thermographId, model, temperatureFk, warehouseId, options); + await models.Thermograph.createThermograph(thermographId, model, temperatureFk, warehouseId, options); + + await tx.rollback(); } catch (e) { + await tx.rollback(); error = e; } - expect(error).toBeDefined(); expect(error.message).toBe('This thermograph id already exists'); }); }); diff --git a/modules/travel/back/methods/travel-thermograph/getThermographTemperatures.js b/modules/travel/back/methods/travel-thermograph/getThermographTemperatures.js deleted file mode 100644 index 1d510b5137..0000000000 --- a/modules/travel/back/methods/travel-thermograph/getThermographTemperatures.js +++ /dev/null @@ -1,18 +0,0 @@ -module.exports = Self => { - Self.remoteMethod('getThermographTemperatures', { - description: 'Gets the thermograph temperatures', - accessType: 'READ', - returns: { - type: ['String'], - root: true - }, - http: { - path: `/getThermographTemperatures`, - verb: 'GET' - } - }); - - Self.getThermographTemperatures = async() => { - return Self.getEnumValues('temperature'); - }; -}; diff --git a/modules/travel/back/methods/travel/cloneWithEntries.js b/modules/travel/back/methods/travel/cloneWithEntries.js index ef385f1e05..393194f060 100644 --- a/modules/travel/back/methods/travel/cloneWithEntries.js +++ b/modules/travel/back/methods/travel/cloneWithEntries.js @@ -14,7 +14,7 @@ module.exports = Self => { http: {source: 'path'} }], returns: { - type: 'Object', + type: 'object', description: 'The new cloned travel id', root: true, }, @@ -48,46 +48,51 @@ module.exports = Self => { let stmts = []; let stmt; - try { - stmt = new ParameterizedSQL( - `CALL travel_cloneWithEntries(?, ?, ?, ?, @vTravelFk)`, [ - id, started, ended, travel.ref]); + stmt = new ParameterizedSQL( + `CALL travel_cloneWithEntries(?, ?, ?, ?, ?, ?, ?, @vTravelFk)`, [ + id, + started, + ended, + travel.warehouseOutFk, + travel.warehouseInFk, + travel.ref, + travel.agencyFk + ] + ); + stmts.push(stmt); + const newTravelIndex = stmts.push('SELECT @vTravelFk AS id') - 1; - stmts.push(stmt); - const index = stmts.push('SELECT @vTravelFk AS id') - 1; + const sql = ParameterizedSQL.join(stmts, ';'); + const result = await conn.executeStmt(sql); + const [lastInsert] = result[newTravelIndex]; - const sql = ParameterizedSQL.join(stmts, ';'); - const result = await conn.executeStmt(sql); - const [lastInsert] = result[index]; - const newTravel = await Self.findById(lastInsert.id, { - fields: [ - 'id', - 'shipped', - 'landed', - 'warehouseInFk', - 'warehouseOutFk', - 'agencyFk', - 'ref' - ] - }); + if (!lastInsert.id) + throw new UserError('Unable to clone this travel'); - const oldProperties = await loggable.translateValues(Self, travel); - const newProperties = await loggable.translateValues(Self, newTravel); - await models.TravelLog.create({ - originFk: newTravel.id, - userFk: userId, - action: 'insert', - changedModel: 'Travel', - changedModelId: newTravel.id, - oldInstance: oldProperties, - newInstance: newProperties - }); + const newTravel = await Self.findById(lastInsert.id, { + fields: [ + 'id', + 'shipped', + 'landed', + 'warehouseInFk', + 'warehouseOutFk', + 'agencyFk', + 'ref' + ] + }); - return newTravel.id; - } catch (error) { - if (error.code === 'ER_DUP_ENTRY') - throw new UserError('A travel with this data already exists'); - throw error; - } + const oldProperties = await loggable.translateValues(Self, travel); + const newProperties = await loggable.translateValues(Self, newTravel); + await models.TravelLog.create({ + originFk: newTravel.id, + userFk: userId, + action: 'insert', + changedModel: 'Travel', + changedModelId: newTravel.id, + oldInstance: oldProperties, + newInstance: newProperties + }); + + return newTravel.id; }; }; diff --git a/modules/travel/back/methods/travel/createThermograph.js b/modules/travel/back/methods/travel/createThermograph.js index 974b679238..aac3a22b98 100644 --- a/modules/travel/back/methods/travel/createThermograph.js +++ b/modules/travel/back/methods/travel/createThermograph.js @@ -6,44 +6,51 @@ module.exports = Self => { accessType: 'WRITE', accepts: [{ arg: 'id', - type: 'Number', + type: 'number', description: 'The travel id', http: {source: 'path'} - }, { + }, + { arg: 'thermographId', - type: 'String', + type: 'string', description: 'The thermograph id', required: true - }, { + }, + { arg: 'state', - type: 'String', + type: 'string', required: true - }, { + }, + { arg: 'warehouseId', - type: 'Number', + type: 'number', description: 'The warehouse id', required: true - }, { + }, + { arg: 'companyId', - type: 'Number', + type: 'number', description: 'The company id', required: true - }, { + }, + { arg: 'dmsTypeId', - type: 'Number', + type: 'number', description: 'The dms type id', required: true - }, { + }, + { arg: 'reference', - type: 'String', + type: 'string', required: true - }, { + }, + { arg: 'description', - type: 'String', + type: 'string', required: true }], returns: { - type: 'Object', + type: 'object', root: true }, http: { @@ -52,36 +59,44 @@ module.exports = Self => { } }); - Self.createThermograph = async(ctx, id, thermographId, state) => { + Self.createThermograph = async(ctx, id, thermographId, state, options) => { const models = Self.app.models; - const tx = await Self.beginTransaction({}); + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } try { - const options = {transaction: tx}; const travelThermograph = await models.TravelThermograph.findOne({ where: { thermographFk: thermographId, travelFk: null } - }, options); + }, myOptions); if (!travelThermograph) throw new UserError('No valid travel thermograph found'); - const uploadedFiles = await models.Dms.uploadFile(ctx, options); + const uploadedFiles = await models.Dms.uploadFile(ctx, myOptions); const firstDms = uploadedFiles[0]; await travelThermograph.updateAttributes({ dmsFk: firstDms.id, travelFk: id, result: state - }, options); + }, myOptions); - await tx.commit(); + if (tx) await tx.commit(); return travelThermograph; } catch (err) { - await tx.rollback(); + if (tx) await tx.rollback(); throw err; } }; diff --git a/modules/travel/back/methods/travel/specs/cloneWithEntries.spec.js b/modules/travel/back/methods/travel/specs/cloneWithEntries.spec.js index ab7d3aa1d9..1990072f6a 100644 --- a/modules/travel/back/methods/travel/specs/cloneWithEntries.spec.js +++ b/modules/travel/back/methods/travel/specs/cloneWithEntries.spec.js @@ -4,7 +4,7 @@ const app = require('vn-loopback/server/server'); xdescribe('Travel cloneWithEntries()', () => { const models = app.models; const travelId = 5; - const currentUserId = 102; + const currentUserId = 1102; const ctx = {req: {accessToken: {userId: currentUserId}}}; let travelBefore; let newTravelId; diff --git a/modules/travel/back/methods/travel/specs/createThermograph.spec.js b/modules/travel/back/methods/travel/specs/createThermograph.spec.js index b85dcca044..742e2dc181 100644 --- a/modules/travel/back/methods/travel/specs/createThermograph.spec.js +++ b/modules/travel/back/methods/travel/specs/createThermograph.spec.js @@ -1,50 +1,50 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Travel createThermograph()', () => { - const models = app.models; const travelId = 3; - const currentUserId = 102; + const currentUserId = 1102; const thermographId = '138350-0'; const ctx = {req: {accessToken: {userId: currentUserId}}, args: {dmsTypeId: 1}}; - let travelThermographBefore; - - afterAll(async done => { - await app.models.TravelThermograph.rawSql(` - UPDATE travelThermograph - SET travelFk = NULL, dmsFk = NULL - WHERE id = ?`, [travelThermographBefore.id]); - - done(); - }); it(`should set the travelFk and dmsFk properties to the travel thermograph`, async() => { - spyOn(app.models.Dms, 'uploadFile').and.returnValue([{id: 5}]); + const tx = await models.Travel.beginTransaction({}); - travelThermographBefore = await models.TravelThermograph.findOne({ - where: { - thermographFk: thermographId, - travelFk: null - } - }); + try { + const options = {transaction: tx}; - await models.Travel.createThermograph(ctx, travelId, thermographId); + spyOn(models.Dms, 'uploadFile').and.returnValue([{id: 5}]); - const travelThermographAfter = await models.TravelThermograph.findOne({ - where: { - thermographFk: thermographId, - travelFk: travelId - } - }); + travelThermographBefore = await models.TravelThermograph.findOne({ + where: { + thermographFk: thermographId, + travelFk: null + } + }, options); - expect(app.models.Dms.uploadFile).toHaveBeenCalledWith(ctx, jasmine.any(Object)); + await models.Travel.createThermograph(ctx, travelId, thermographId, options); - expect(travelThermographBefore).toBeDefined(); - expect(travelThermographBefore.thermographFk).toEqual(thermographId); - expect(travelThermographBefore.travelFk).toBeNull(); - expect(travelThermographAfter).toBeDefined(); + const travelThermographAfter = await models.TravelThermograph.findOne({ + where: { + thermographFk: thermographId, + travelFk: travelId + } + }, options); - expect(travelThermographAfter.thermographFk).toEqual(thermographId); - expect(travelThermographAfter.travelFk).toEqual(travelId); - expect(travelThermographAfter.dmsFk).toEqual(5); + expect(models.Dms.uploadFile).toHaveBeenCalledWith(ctx, jasmine.any(Object)); + + expect(travelThermographBefore).toBeDefined(); + expect(travelThermographBefore.thermographFk).toEqual(thermographId); + expect(travelThermographBefore.travelFk).toBeNull(); + expect(travelThermographAfter).toBeDefined(); + + expect(travelThermographAfter.thermographFk).toEqual(thermographId); + expect(travelThermographAfter.travelFk).toEqual(travelId); + expect(travelThermographAfter.dmsFk).toEqual(5); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/travel/back/methods/travel/specs/deleteThermograph.spec.js b/modules/travel/back/methods/travel/specs/deleteThermograph.spec.js index 843fa046c8..215dd9a357 100644 --- a/modules/travel/back/methods/travel/specs/deleteThermograph.spec.js +++ b/modules/travel/back/methods/travel/specs/deleteThermograph.spec.js @@ -3,7 +3,7 @@ const app = require('vn-loopback/server/server'); describe('Travel deleteThermograph()', () => { const models = app.models; const travelId = 1; - const currentUserId = 102; + const currentUserId = 1102; const thermographId = 'TZ1905012010'; const travelThermographId = 4; const dmsId = 5; diff --git a/modules/travel/back/model-config.json b/modules/travel/back/model-config.json index b06d00f06f..34321ba784 100644 --- a/modules/travel/back/model-config.json +++ b/modules/travel/back/model-config.json @@ -13,5 +13,8 @@ }, "TravelThermograph": { "dataSource": "vn" + }, + "Temperature": { + "dataSource": "vn" } } diff --git a/modules/travel/back/models/temperature.json b/modules/travel/back/models/temperature.json new file mode 100644 index 0000000000..575b5f8bef --- /dev/null +++ b/modules/travel/back/models/temperature.json @@ -0,0 +1,30 @@ +{ + "name": "Temperature", + "base": "VnModel", + "options": { + "mysql": { + "table": "temperature" + } + }, + "properties": { + "code": { + "type": "string", + "id": true, + "description": "Identifier", + "required": true + }, + "name": { + "type": "string", + "required": true + }, + "description": { + "type": "string" + } + }, + "acls": [{ + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }] +} diff --git a/modules/travel/back/models/travel-thermograph.js b/modules/travel/back/models/travel-thermograph.js deleted file mode 100644 index 91aa4de699..0000000000 --- a/modules/travel/back/models/travel-thermograph.js +++ /dev/null @@ -1,4 +0,0 @@ -module.exports = Self => { - require('../methods/travel-thermograph/getThermographTemperatures')(Self); -}; - diff --git a/modules/travel/back/models/travel-thermograph.json b/modules/travel/back/models/travel-thermograph.json index 70ee0de07e..1e6dd19050 100644 --- a/modules/travel/back/models/travel-thermograph.json +++ b/modules/travel/back/models/travel-thermograph.json @@ -13,22 +13,25 @@ }, "properties": { "id": { - "type": "Number", + "type": "number", "description": "Identifier", "id": true }, "created": { - "type": "Date" + "type": "date" }, "temperature": { - "type": "String", + "type": "string" + }, + "temperatureFk": { + "type": "string", "required": true }, "result": { - "type": "String" + "type": "string" }, "warehouseFk": { - "type": "Number", + "type": "number", "required": true } }, diff --git a/modules/travel/front/thermograph/create/index.html b/modules/travel/front/thermograph/create/index.html index f73938f5bc..41709e1fbc 100644 --- a/modules/travel/front/thermograph/create/index.html +++ b/modules/travel/front/thermograph/create/index.html @@ -122,8 +122,9 @@ + url="Temperatures" + data="Temperatures" + auto-load="true"> + ng-model="$ctrl.newThermograph.temperatureFk" + data='Temperatures' + show-field="name" + value-field="code"> diff --git a/modules/travel/front/thermograph/create/index.js b/modules/travel/front/thermograph/create/index.js index 666393350c..b6d78fc50e 100644 --- a/modules/travel/front/thermograph/create/index.js +++ b/modules/travel/front/thermograph/create/index.js @@ -63,12 +63,11 @@ class Controller extends Section { this.newThermograph = { thermographId: this.thermographId, warehouseId: this.warehouseId, - temperature: defaultTemperature, + temperatureFk: defaultTemperature, model: defaultModel }; this.$.modelsModel.refresh(); - this.$.temperaturesModel.refresh(); this.$.newThermographDialog.show(); } diff --git a/modules/worker/back/methods/calendar/specs/absences.spec.js b/modules/worker/back/methods/calendar/specs/absences.spec.js index 1b95bfdb68..cfe7379c3f 100644 --- a/modules/worker/back/methods/calendar/specs/absences.spec.js +++ b/modules/worker/back/methods/calendar/specs/absences.spec.js @@ -2,8 +2,8 @@ const app = require('vn-loopback/server/server'); describe('Worker absences()', () => { it('should get the absence calendar for a full year contract', async() => { - const ctx = {req: {accessToken: {userId: 106}}}; - const businessId = 106; + const ctx = {req: {accessToken: {userId: 1106}}}; + const businessId = 1106; const now = new Date(); const year = now.getFullYear(); @@ -18,7 +18,7 @@ describe('Worker absences()', () => { }); it('should get the absence calendar for a permanent contract', async() => { - const businessId = 106; + const businessId = 1106; const ctx = {req: {accessToken: {userId: 9}}}; const now = new Date(); @@ -50,8 +50,8 @@ describe('Worker absences()', () => { }); it('should give the same holidays as worked days since the holidays amount matches the amount of days in a year', async() => { - const businessId = 106; - const userId = 106; + const businessId = 1106; + const userId = 1106; const today = new Date(); // getting how many days in a year diff --git a/modules/worker/back/methods/worker-dms/specs/downloadFile.spec.js b/modules/worker/back/methods/worker-dms/specs/downloadFile.spec.js index 27ed204add..ac8e4539f2 100644 --- a/modules/worker/back/methods/worker-dms/specs/downloadFile.spec.js +++ b/modules/worker/back/methods/worker-dms/specs/downloadFile.spec.js @@ -4,7 +4,7 @@ describe('worker-dms downloadFile()', () => { let dmsId = 4; it('should return a response for an employee with text content-type', async() => { - let workerId = 106; + let workerId = 1106; let ctx = {req: {accessToken: {userId: workerId}}}; const result = await app.models.WorkerDms.downloadFile(ctx, dmsId); diff --git a/modules/worker/back/methods/worker-dms/specs/removeFile.spec.js b/modules/worker/back/methods/worker-dms/specs/removeFile.spec.js index 7039d4f3e2..3efd09464a 100644 --- a/modules/worker/back/methods/worker-dms/specs/removeFile.spec.js +++ b/modules/worker/back/methods/worker-dms/specs/removeFile.spec.js @@ -3,7 +3,7 @@ const app = require('vn-loopback/server/server'); describe('WorkerDms removeFile()', () => { const workerDmsFk = 1; it(`should return an error for a user without enough privileges`, async() => { - let clientId = 101; + let clientId = 1101; let ctx = {req: {accessToken: {userId: clientId}}}; let error; diff --git a/modules/worker/back/methods/worker-time-control/specs/filter.spec.js b/modules/worker/back/methods/worker-time-control/specs/filter.spec.js index 913dfb3553..7fe681ec11 100644 --- a/modules/worker/back/methods/worker-time-control/specs/filter.spec.js +++ b/modules/worker/back/methods/worker-time-control/specs/filter.spec.js @@ -2,7 +2,7 @@ const app = require('vn-loopback/server/server'); describe('workerTimeControl filter()', () => { it('should return 1 result filtering by id', async() => { - let ctx = {req: {accessToken: {userId: 106}}, args: {workerFk: 106}}; + let ctx = {req: {accessToken: {userId: 1106}}, args: {workerFk: 1106}}; const firstHour = new Date(); firstHour.setHours(7, 0, 0, 0); const lastHour = new Date(); @@ -20,7 +20,7 @@ describe('workerTimeControl filter()', () => { }); it('should return a privilege error for a non subordinate worker', async() => { - let ctx = {req: {accessToken: {userId: 107}}, args: {workerFk: 106}}; + let ctx = {req: {accessToken: {userId: 1107}}, args: {workerFk: 1106}}; const firstHour = new Date(); firstHour.setHours(7, 0, 0, 0); const lastHour = new Date(); diff --git a/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js b/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js index a50182f1b7..5829653cce 100644 --- a/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js +++ b/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js @@ -6,7 +6,7 @@ describe('workerTimeControl add/delete timeEntry()', () => { const HHRRId = 37; const teamBossId = 13; const employeeId = 1; - const salesPersonId = 106; + const salesPersonId = 1106; const salesBossId = 19; let activeCtx = { accessToken: {userId: 50}, diff --git a/modules/worker/back/methods/worker/specs/activeWithInheritedRole.spec.js b/modules/worker/back/methods/worker/specs/activeWithInheritedRole.spec.js index c44fb72f97..411cb8e577 100644 --- a/modules/worker/back/methods/worker/specs/activeWithInheritedRole.spec.js +++ b/modules/worker/back/methods/worker/specs/activeWithInheritedRole.spec.js @@ -1,6 +1,11 @@ const app = require('vn-loopback/server/server'); describe('Worker activeWithInheritedRole', () => { + let allRolesCount; + beforeAll(async() => { + allRolesCount = await app.models.Role.count(); + }); + it('should return the workers with an inherited role of salesPerson', async() => { const filter = {where: {role: 'salesPerson'}}; const result = await app.models.Worker.activeWithInheritedRole(filter); @@ -10,7 +15,8 @@ describe('Worker activeWithInheritedRole', () => { const isSalesPerson = await app.models.Account.hasRole(worker.id, 'salesPerson'); - expect(result.length).toEqual(19); + expect(result.length).toBeGreaterThan(1); + expect(result.length).toBeLessThan(allRolesCount); expect(isSalesPerson).toBe(true); }); @@ -23,7 +29,8 @@ describe('Worker activeWithInheritedRole', () => { const isBuyer = await app.models.Account.hasRole(worker.id, 'buyer'); - expect(result.length).toEqual(17); + expect(result.length).toBeGreaterThan(1); + expect(result.length).toBeLessThan(allRolesCount); expect(isBuyer).toBe(true); }); }); diff --git a/modules/worker/back/methods/worker/specs/deleteAbsence.spec.js b/modules/worker/back/methods/worker/specs/deleteAbsence.spec.js index 16036eac61..a105669cf2 100644 --- a/modules/worker/back/methods/worker/specs/deleteAbsence.spec.js +++ b/modules/worker/back/methods/worker/specs/deleteAbsence.spec.js @@ -5,7 +5,7 @@ describe('Worker deleteAbsence()', () => { const businessId = 18; const workerId = 18; const activeCtx = { - accessToken: {userId: 106}, + accessToken: {userId: 1106}, headers: {origin: 'http://localhost'} }; const ctx = {req: activeCtx}; @@ -20,7 +20,7 @@ describe('Worker deleteAbsence()', () => { }); it('should return an error for a user without enough privileges', async() => { - activeCtx.accessToken.userId = 106; + activeCtx.accessToken.userId = 1106; const tx = await app.models.Calendar.beginTransaction({}); try { diff --git a/modules/worker/back/methods/worker/specs/getWorkedHours.spec.js b/modules/worker/back/methods/worker/specs/getWorkedHours.spec.js index 148b8467e3..c06ff85028 100644 --- a/modules/worker/back/methods/worker/specs/getWorkedHours.spec.js +++ b/modules/worker/back/methods/worker/specs/getWorkedHours.spec.js @@ -2,7 +2,7 @@ const app = require('vn-loopback/server/server'); describe('Worker getWorkedHours()', () => { it(`should return the expected hours and the worked hours of a given date`, async() => { - const workerID = 106; + const workerID = 1106; let started = new Date(); started.setHours(0, 0, 0, 0); diff --git a/modules/worker/back/methods/worker/specs/holidays.spec.js b/modules/worker/back/methods/worker/specs/holidays.spec.js index 6f588147cb..317bc8f0f1 100644 --- a/modules/worker/back/methods/worker/specs/holidays.spec.js +++ b/modules/worker/back/methods/worker/specs/holidays.spec.js @@ -2,8 +2,8 @@ const app = require('vn-loopback/server/server'); const LoopBackContext = require('loopback-context'); describe('Worker holidays()', () => { - const businessId = 106; - const workerId = 106; + const businessId = 1106; + const workerId = 1106; const activeCtx = { accessToken: {userId: workerId}, headers: {origin: 'http://localhost'} @@ -16,7 +16,7 @@ describe('Worker holidays()', () => { }); }); - it('should get the absence calendar for a full year contract', async() => { + it('should now get the absence calendar for a full year contract', async() => { const now = new Date(); const year = now.getFullYear(); diff --git a/modules/worker/back/methods/worker/specs/isSubordinate.spec.js b/modules/worker/back/methods/worker/specs/isSubordinate.spec.js index 53a620fcc4..ea6738f8b9 100644 --- a/modules/worker/back/methods/worker/specs/isSubordinate.spec.js +++ b/modules/worker/back/methods/worker/specs/isSubordinate.spec.js @@ -3,7 +3,7 @@ const app = require('vn-loopback/server/server'); describe('worker isSubordinate()', () => { it('should return truthy if a worker is a subordinate', async() => { let ctx = {req: {accessToken: {userId: 19}}}; - let workerFk = 106; + let workerFk = 1106; let result = await app.models.Worker.isSubordinate(ctx, workerFk); expect(result).toBeTruthy(); @@ -11,15 +11,15 @@ describe('worker isSubordinate()', () => { it('should return truthy for an hr person', async() => { let ctx = {req: {accessToken: {userId: 37}}}; - let workerFk = 106; + let workerFk = 1106; let result = await app.models.Worker.isSubordinate(ctx, workerFk); expect(result).toBeTruthy(); }); it('should return truthy if the current user is himself', async() => { - let ctx = {req: {accessToken: {userId: 106}}}; - let workerFk = 106; + let ctx = {req: {accessToken: {userId: 1106}}}; + let workerFk = 1106; let result = await app.models.Worker.isSubordinate(ctx, workerFk); expect(result).toBeTruthy(); diff --git a/modules/worker/back/methods/worker/specs/mySubordinates.spec.js b/modules/worker/back/methods/worker/specs/mySubordinates.spec.js index 5a458a1bc6..7eb118d9c2 100644 --- a/modules/worker/back/methods/worker/specs/mySubordinates.spec.js +++ b/modules/worker/back/methods/worker/specs/mySubordinates.spec.js @@ -9,9 +9,9 @@ describe('worker mySubordinates()', () => { }); it('should return an array of one subordinate', async() => { - let ctx = {req: {accessToken: {userId: 106}}}; + const workerFk = 1106; + let ctx = {req: {accessToken: {userId: workerFk}}}; let result = await app.models.Worker.mySubordinates(ctx); - const workerFk = 106; expect(result.length).toEqual(1); expect(result[0].workerFk).toEqual(workerFk); diff --git a/modules/worker/back/methods/worker/specs/updateAbsence.spec.js b/modules/worker/back/methods/worker/specs/updateAbsence.spec.js index 2ff8e64e1e..6339b3163a 100644 --- a/modules/worker/back/methods/worker/specs/updateAbsence.spec.js +++ b/modules/worker/back/methods/worker/specs/updateAbsence.spec.js @@ -2,10 +2,10 @@ const app = require('vn-loopback/server/server'); const LoopBackContext = require('loopback-context'); describe('Worker updateAbsence()', () => { - const workerId = 106; - const businessId = 106; + const workerId = 1106; + const businessId = 1106; const activeCtx = { - accessToken: {userId: 106}, + accessToken: {userId: 1106}, headers: {origin: 'http://localhost'} }; const ctx = {req: activeCtx}; @@ -30,7 +30,7 @@ describe('Worker updateAbsence()', () => { }); it('should return an error for a user without enough privileges', async() => { - activeCtx.accessToken.userId = 106; + activeCtx.accessToken.userId = 1106; const expectedAbsenceTypeId = 2; let error; diff --git a/modules/worker/back/methods/worker/specs/uploadFile.spec.js b/modules/worker/back/methods/worker/specs/uploadFile.spec.js index 26a50252d9..7a929cd2ba 100644 --- a/modules/worker/back/methods/worker/specs/uploadFile.spec.js +++ b/modules/worker/back/methods/worker/specs/uploadFile.spec.js @@ -2,8 +2,8 @@ const app = require('vn-loopback/server/server'); describe('Worker uploadFile()', () => { it(`should return an error for a user without enough privileges`, async() => { - let workerId = 106; - let currentUserId = 102; + let workerId = 1106; + let currentUserId = 1102; let hhrrDataId = 3; let ctx = {req: {accessToken: {userId: currentUserId}}, args: {dmsTypeId: hhrrDataId}}; diff --git a/modules/worker/back/models/worker-time-control-mail.json b/modules/worker/back/models/worker-time-control-mail.json index 81ca235d76..7f8522757c 100644 --- a/modules/worker/back/models/worker-time-control-mail.json +++ b/modules/worker/back/models/worker-time-control-mail.json @@ -35,7 +35,7 @@ { "accessType": "READ", "principalType": "ROLE", - "principalId": "$everyone", + "principalId": "employee", "permission": "ALLOW" } ] diff --git a/modules/worker/front/calendar/index.html b/modules/worker/front/calendar/index.html index 42d3639529..ce8bd6275b 100644 --- a/modules/worker/front/calendar/index.html +++ b/modules/worker/front/calendar/index.html @@ -78,6 +78,11 @@ Festive + + + + Current day +

diff --git a/modules/worker/front/calendar/index.spec.js b/modules/worker/front/calendar/index.spec.js index 141bf6653b..e8f9b3130b 100644 --- a/modules/worker/front/calendar/index.spec.js +++ b/modules/worker/front/calendar/index.spec.js @@ -18,8 +18,8 @@ describe('Worker', () => { controller = $componentController('vnWorkerCalendar', {$element, $scope}); controller.isSubordinate = true; controller.absenceType = {id: 1, name: 'Holiday', code: 'holiday', rgb: 'red'}; - controller.$params.id = 106; - controller._worker = {id: 106}; + controller.$params.id = 1106; + controller._worker = {id: 1106}; })); describe('year() getter', () => { @@ -45,7 +45,7 @@ describe('Worker', () => { it(`should set the contract id and then call to the refresh method`, () => { jest.spyOn(controller, 'refresh').mockReturnValue(Promise.resolve()); - controller.businessId = 106; + controller.businessId = 1106; expect(controller.refresh).toHaveBeenCalledWith(); }); @@ -74,7 +74,7 @@ describe('Worker', () => { let yesterday = new Date(today.getTime()); yesterday.setDate(yesterday.getDate() - 1); - controller.worker = {id: 107}; + controller.worker = {id: 1107}; expect(controller.getIsSubordinate).toHaveBeenCalledWith(); expect(controller.getActiveContract).toHaveBeenCalledWith(); @@ -83,7 +83,7 @@ describe('Worker', () => { describe('getIsSubordinate()', () => { it(`should return whether the worker is a subordinate`, () => { - $httpBackend.expect('GET', `Workers/106/isSubordinate`).respond(true); + $httpBackend.expect('GET', `Workers/1106/isSubordinate`).respond(true); controller.getIsSubordinate(); $httpBackend.flush(); @@ -95,11 +95,11 @@ describe('Worker', () => { it(`should return the current contract and then set the businessId property`, () => { jest.spyOn(controller, 'refresh').mockReturnValue(Promise.resolve()); - $httpBackend.expect('GET', `Workers/106/activeContract`).respond({businessFk: 106}); + $httpBackend.expect('GET', `Workers/1106/activeContract`).respond({businessFk: 1106}); controller.getActiveContract(); $httpBackend.flush(); - expect(controller.businessId).toEqual(106); + expect(controller.businessId).toEqual(1106); }); }); @@ -109,7 +109,7 @@ describe('Worker', () => { const year = today.getFullYear(); const serializedParams = $httpParamSerializer({year}); - $httpBackend.expect('GET', `Workers/106/holidays?${serializedParams}`).respond({totalHolidays: 28}); + $httpBackend.expect('GET', `Workers/1106/holidays?${serializedParams}`).respond({totalHolidays: 28}); controller.getContractHolidays(); $httpBackend.flush(); @@ -240,7 +240,7 @@ describe('Worker', () => { const calendarElement = {}; const expectedResponse = {id: 10}; - $httpBackend.expect('POST', `Workers/106/createAbsence`).respond(200, expectedResponse); + $httpBackend.expect('POST', `Workers/1106/createAbsence`).respond(200, expectedResponse); controller.create(calendarElement, dated); $httpBackend.flush(); @@ -268,7 +268,7 @@ describe('Worker', () => { controller.absenceType = newAbsenceType; const expectedParams = {absenceId: 10, absenceTypeId: 2}; - $httpBackend.expect('PATCH', `Workers/106/updateAbsence`, expectedParams).respond(200); + $httpBackend.expect('PATCH', `Workers/1106/updateAbsence`, expectedParams).respond(200); controller.edit(calendarElement, event); $httpBackend.flush(); @@ -295,7 +295,7 @@ describe('Worker', () => { controller.events[selectedDay.getTime()] = expectedEvent; const serializedParams = $httpParamSerializer(expectedParams); - $httpBackend.expect('DELETE', `Workers/106/deleteAbsence?${serializedParams}`).respond(200); + $httpBackend.expect('DELETE', `Workers/1106/deleteAbsence?${serializedParams}`).respond(200); controller.delete(calendarElement, selectedDay, expectedEvent); $httpBackend.flush(); diff --git a/modules/worker/front/calendar/locale/es.yml b/modules/worker/front/calendar/locale/es.yml index 1ff12358ce..464ad97505 100644 --- a/modules/worker/front/calendar/locale/es.yml +++ b/modules/worker/front/calendar/locale/es.yml @@ -7,4 +7,5 @@ of: de days: días Choose an absence type from the right menu: Elige un tipo de ausencia desde el menú de la derecha To start adding absences, click an absence type from the right menu and then on the day you want to add an absence: Para empezar a añadir ausencias, haz clic en un tipo de ausencia desde el menu de la derecha y después en el día que quieres añadir la ausencia -You can just add absences within the current year: Solo puedes añadir ausencias dentro del año actual \ No newline at end of file +You can just add absences within the current year: Solo puedes añadir ausencias dentro del año actual +Current day: Día actual \ No newline at end of file diff --git a/modules/worker/front/calendar/style.scss b/modules/worker/front/calendar/style.scss index b778a68b5f..a028c8c304 100644 --- a/modules/worker/front/calendar/style.scss +++ b/modules/worker/front/calendar/style.scss @@ -41,12 +41,20 @@ vn-worker-calendar { border-color: rgba(0, 0, 0, 0.3); border-bottom: 1px solid rgba(0, 0, 0, 0.3); } - - .festive { - background-color:white; - border: 2px solid $color-alert; + + vn-avatar.festive, + vn-avatar.today { + background-color: $color-font-dark; width: 24px; min-width: 24px; height: 24px } + + vn-avatar.festive { + border: 2px solid $color-alert + } + + vn-avatar.today { + border: 2px solid $color-font-link + } } diff --git a/modules/worker/front/descriptor/index.html b/modules/worker/front/descriptor/index.html index ad0b9e5c37..036b70eab2 100644 --- a/modules/worker/front/descriptor/index.html +++ b/modules/worker/front/descriptor/index.html @@ -46,6 +46,8 @@
diff --git a/modules/worker/front/dms/create/index.spec.js b/modules/worker/front/dms/create/index.spec.js index 07a66b9dc6..b1c803854d 100644 --- a/modules/worker/front/dms/create/index.spec.js +++ b/modules/worker/front/dms/create/index.spec.js @@ -16,7 +16,7 @@ describe('Client', () => { $httpParamSerializer = _$httpParamSerializer_; $element = $compile(``)($rootScope); controller = $element.controller('vnWorkerDmsCreate'); - controller._worker = {id: 101, name: 'Bruce wayne'}; + controller._worker = {id: 1101, name: 'Bruce wayne'}; })); describe('worker() setter', () => { @@ -46,7 +46,7 @@ describe('Client', () => { $httpBackend.flush(); expect(controller.dms).toBeDefined(); - expect(controller.dms.reference).toEqual(101); + expect(controller.dms.reference).toEqual(1101); expect(controller.dms.dmsTypeId).toEqual(12); }); }); diff --git a/modules/worker/front/dms/edit/index.spec.js b/modules/worker/front/dms/edit/index.spec.js index 44abc6d640..0b69f2894f 100644 --- a/modules/worker/front/dms/edit/index.spec.js +++ b/modules/worker/front/dms/edit/index.spec.js @@ -14,7 +14,7 @@ describe('Worker', () => { $httpBackend = _$httpBackend_; $element = angular.element(` { jest.spyOn(controller, 'getAllowedContentTypes'); controller._worker = undefined; controller.worker = { - id: 106 + id: 1106 }; expect(controller.setDefaultParams).toHaveBeenCalledWith(); @@ -37,7 +37,7 @@ describe('Worker', () => { it('should perform a GET query and define the dms property on controller', () => { const dmsId = 4; const expectedResponse = { - reference: 101, + reference: 1101, warehouseFk: 1, companyFk: 442, dmsTypeFk: 3, @@ -51,7 +51,7 @@ describe('Worker', () => { $httpBackend.flush(); expect(controller.dms).toBeDefined(); - expect(controller.dms.reference).toEqual(101); + expect(controller.dms.reference).toEqual(1101); expect(controller.dms.dmsTypeId).toEqual(3); }); }); diff --git a/modules/worker/front/dms/index/index.html b/modules/worker/front/dms/index/index.html index 6ad1cffd88..1404336a2a 100644 --- a/modules/worker/front/dms/index/index.html +++ b/modules/worker/front/dms/index/index.html @@ -20,7 +20,7 @@ Description Original File - Created + Created @@ -57,7 +57,7 @@ {{::document.file}} - + {{::document.created | date:'dd/MM/yyyy HH:mm'}} diff --git a/modules/zone/back/methods/agency/getShipped.js b/modules/zone/back/methods/agency/getShipped.js index a0cc643385..2889a2557e 100644 --- a/modules/zone/back/methods/agency/getShipped.js +++ b/modules/zone/back/methods/agency/getShipped.js @@ -35,7 +35,7 @@ module.exports = Self => { }); Self.getShipped = async(landed, addressFk, agencyModeFk, warehouseFk, options) => { - let myOptions = {}; + const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/zone/back/methods/agency/specs/getAgenciesWithWarehouse.spec.js b/modules/zone/back/methods/agency/specs/getAgenciesWithWarehouse.spec.js index a547c7b45a..bc7aa1ed95 100644 --- a/modules/zone/back/methods/agency/specs/getAgenciesWithWarehouse.spec.js +++ b/modules/zone/back/methods/agency/specs/getAgenciesWithWarehouse.spec.js @@ -8,7 +8,8 @@ describe('Agency getAgenciesWithWarehouse()', () => { try { const options = {transaction: tx}; - const agencies = await app.models.Agency.getAgenciesWithWarehouse(101, today, 1, options); + const addressId = 101; + const agencies = await app.models.Agency.getAgenciesWithWarehouse(addressId, today, 1, options); expect(agencies.length).toEqual(3); expect(agencies[0].agencyMode).toEqual('inhouse pickup'); @@ -28,7 +29,8 @@ describe('Agency getAgenciesWithWarehouse()', () => { try { const options = {transaction: tx}; - const agencies = await app.models.Agency.getAgenciesWithWarehouse(101, null, 1, options); + const addressId = 101; + const agencies = await app.models.Agency.getAgenciesWithWarehouse(addressId, null, 1, options); expect(agencies.length).toEqual(0); diff --git a/modules/zone/back/methods/zone/deleteZone.js b/modules/zone/back/methods/zone/deleteZone.js index 05ffcda543..fb228bcf42 100644 --- a/modules/zone/back/methods/zone/deleteZone.js +++ b/modules/zone/back/methods/zone/deleteZone.js @@ -26,7 +26,7 @@ module.exports = Self => { today.setHours(0, 0, 0, 0); let tx; - let myOptions = {}; + const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); @@ -68,7 +68,7 @@ module.exports = Self => { }, myOptions)); } } - await Promise.all(promises, myOptions); + await Promise.all(promises); await models.Zone.destroyById(id, myOptions); if (tx) await tx.commit(); diff --git a/modules/zone/back/methods/zone/getUpcomingDeliveries.js b/modules/zone/back/methods/zone/getUpcomingDeliveries.js index 8b092b47b9..6aceb694b4 100644 --- a/modules/zone/back/methods/zone/getUpcomingDeliveries.js +++ b/modules/zone/back/methods/zone/getUpcomingDeliveries.js @@ -21,6 +21,8 @@ module.exports = Self => { const [zones] = await Self.rawSql('CALL vn.zone_upcomingDeliveries()', null, myOptions); + if (!zones.length) return; + const details = []; for (let zone of zones) { diff --git a/modules/zone/back/methods/zone/specs/getUpcomingDeliveries.spec.js b/modules/zone/back/methods/zone/specs/getUpcomingDeliveries.spec.js index d0e8988379..acef079f60 100644 --- a/modules/zone/back/methods/zone/specs/getUpcomingDeliveries.spec.js +++ b/modules/zone/back/methods/zone/specs/getUpcomingDeliveries.spec.js @@ -1,12 +1,12 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('zone getUpcomingDeliveries()', () => { it('should check returns data', async() => { - const tx = await app.models.Zone.beginTransaction({}); + const tx = await models.Zone.beginTransaction({}); try { const options = {transaction: tx}; - let result = await app.models.Zone.getUpcomingDeliveries(options); + let result = await models.Zone.getUpcomingDeliveries(options); const firstResultLines = result[0].lines; const secondResultLines = result[1].lines; diff --git a/modules/zone/back/models/zone.json b/modules/zone/back/models/zone.json index bafef0a952..403a353590 100644 --- a/modules/zone/back/models/zone.json +++ b/modules/zone/back/models/zone.json @@ -62,6 +62,11 @@ "type": "hasMany", "model": "ZoneWarehouse", "foreignKey": "zoneFk" + }, + "closures": { + "type": "hasMany", + "model": "ZoneClosure", + "foreignKey": "zoneFk" } } } \ No newline at end of file diff --git a/modules/zone/front/delivery-days/index.html b/modules/zone/front/delivery-days/index.html index 61c73c9d68..f01f4ec3f0 100644 --- a/modules/zone/front/delivery-days/index.html +++ b/modules/zone/front/delivery-days/index.html @@ -1,28 +1,32 @@
+ on-selection="$ctrl.onSelection($event, $events, $days)">
-
+ + ng-model="$ctrl.deliveryMethodFk" + on-change="$ctrl.agencyModeFk = null" + tabindex="-1"> + on-change="$ctrl.agencyModeFk = null" + class="vn-mb-sm" + tabindex="-1"> diff --git a/modules/zone/front/delivery-days/index.js b/modules/zone/front/delivery-days/index.js index 408c77be28..12b1c57b17 100644 --- a/modules/zone/front/delivery-days/index.js +++ b/modules/zone/front/delivery-days/index.js @@ -4,20 +4,44 @@ import './style.scss'; class Controller extends Section { $onInit() { - this.$.params = {}; + this.setParams(); } $postLink() { this.deliveryMethodFk = 'delivery'; } - onSubmit() { + + setParams() { + const hasParams = this.$params.deliveryMethodFk || this.$params.geoFk || this.$params.agencyModeFk; + if (hasParams) { + if (this.$params.deliveryMethodFk) + this.deliveryMethodFk = this.$params.deliveryMethodFk; + + if (this.$params.geoFk) + this.geoFk = this.$params.geoFk; + + if (this.$params.agencyModeFk) + this.agencyModeFk = this.$params.agencyModeFk; + + this.fetchData(); + } + } + + fetchData() { + const params = { + deliveryMethodFk: this.deliveryMethodFk, + geoFk: this.geoFk, + agencyModeFk: this.agencyModeFk + }; this.$.data = null; - this.$http.get(`Zones/getEvents`, {params: this.$.params}) + this.$http.get(`Zones/getEvents`, {params}) .then(res => { let data = res.data; this.$.data = data; if (!data.events.length) this.vnApp.showMessage(this.$t('No service for the specified zone')); + + this.$state.go(this.$state.current.name, params); }); } @@ -27,36 +51,54 @@ class Controller extends Section { set deliveryMethodFk(value) { this._deliveryMethodFk = value; - this.$.params.agencyModeFk = null; + let filter; - if (value === 'pickUp') { + + if (value === 'pickUp') filter = {where: {code: 'PICKUP'}}; - this.$.agencymode.focus(); - } else + else filter = {where: {code: {inq: ['DELIVERY', 'AGENCY']}}}; this.$http.get(`DeliveryMethods`, {filter}).then(res => { - let deliveryMethods = res.data.map(deliveryMethod => deliveryMethod.id); + const deliveryMethods = res.data.map(deliveryMethod => deliveryMethod.id); this.agencyFilter = {deliveryMethodFk: {inq: deliveryMethods}}; }); } - onSelection($event, $events) { + onSelection($event, $events, $days) { if (!$events.length) return; - const zones = []; + const day = $days[0]; + const zonesIds = []; for (let event of $events) - zones.push(event.zoneFk); + zonesIds.push(event.zoneFk); this.$.zoneEvents.show($event.target); const zoneModel = this.$.zoneModel; zoneModel.applyFilter({ - include: { - relation: 'agencyMode', - scope: {fields: ['name']} - }, + include: [ + { + relation: 'agencyMode', + scope: {fields: ['name']} + }, + { + relation: 'events', + scope: { + where: {dated: day} + } + }, + ], where: { - id: {inq: zones} + id: {inq: zonesIds} + } + }).then(() => { + const data = zoneModel.data; + for (let row of data) { + const [event] = row.events; + if (event && event.hour) + row.hour = event.hour; + if (event && event.price) + row.price = event.price; } }); } diff --git a/modules/zone/front/delivery-days/index.spec.js b/modules/zone/front/delivery-days/index.spec.js index c39b342965..c896021ed6 100644 --- a/modules/zone/front/delivery-days/index.spec.js +++ b/modules/zone/front/delivery-days/index.spec.js @@ -19,46 +19,67 @@ describe('Zone Component vnZoneDeliveryDays', () => { })); describe('deliveryMethodFk() setter', () => { - it(`should set the deliveryMethodFk property and check just agencymode focus`, () => { - controller.$.agencymode = {focus: jasmine.createSpy('focus')}; - + it('should set the deliveryMethodFk property as pickup and then perform a query that sets the filter', () => { + $httpBackend.expect('GET', 'DeliveryMethods').respond([{id: 999}]); controller.deliveryMethodFk = 'pickUp'; - - expect(controller.$.agencymode.focus).toHaveBeenCalledWith(); - }); - - it(`should set the deliveryMethodFk property, call method http and sets the agencyfilter`, () => { - $httpBackend.when('GET', 'DeliveryMethods').respond([{id: 'id'}]); - - controller.deliveryMethodFk = 'no pickUp'; $httpBackend.flush(); - expect(controller.agencyFilter).toEqual({deliveryMethodFk: {inq: ['id']}}); + expect(controller.agencyFilter).toEqual({deliveryMethodFk: {inq: [999]}}); }); }); - describe('onSubmit()', () => { - it('should make an HTTP GET query and then call the showMessage() method', () => { - jest.spyOn(controller.vnApp, 'showMessage'); + describe('setParams()', () => { + it('should do nothing when no params are received', () => { + controller.setParams(); - const expectedData = {events: []}; - $httpBackend.when('GET', 'Zones/getEvents').respond({events: []}); - controller.onSubmit(); - $httpBackend.flush(); - - expect(controller.$.data).toBeDefined(); - expect(controller.$.data).toEqual(expectedData); - expect(controller.vnApp.showMessage).toHaveBeenCalledWith('No service for the specified zone'); + expect(controller.deliveryMethodFk).toBeUndefined(); + expect(controller.geoFk).toBeUndefined(); + expect(controller.agencyModeFk).toBeUndefined(); }); - it('should make an HTTP GET query and then set the data property', () => { - const expectedData = {events: [{zoneFk: 1}]}; - $httpBackend.when('GET', 'Zones/getEvents').respond({events: [{zoneFk: 1}]}); - controller.onSubmit(); + it('should set the controller properties when the params are provided', () => { + controller.$params = { + deliveryMethodFk: 3, + geoFk: 2, + agencyModeFk: 1 + }; + controller.setParams(); + + expect(controller.deliveryMethodFk).toEqual(controller.$params.deliveryMethodFk); + expect(controller.geoFk).toEqual(controller.$params.geoFk); + expect(controller.agencyModeFk).toEqual(controller.$params.agencyModeFk); + }); + }); + + describe('fetchData()', () => { + it('should make an HTTP GET query and then call the showMessage() method', () => { + jest.spyOn(controller.vnApp, 'showMessage'); + jest.spyOn(controller.$state, 'go'); + + controller.agencyModeFk = 1; + controller.deliveryMethodFk = 2; + controller.geoFk = 3; + controller.$state.current.name = 'myState'; + + const expectedData = {events: []}; + + const url = 'Zones/getEvents?agencyModeFk=1&deliveryMethodFk=2&geoFk=3'; + + $httpBackend.when('GET', 'DeliveryMethods').respond([]); + $httpBackend.expect('GET', url).respond({events: []}); + controller.fetchData(); $httpBackend.flush(); - expect(controller.$.data).toBeDefined(); expect(controller.$.data).toEqual(expectedData); + expect(controller.vnApp.showMessage).toHaveBeenCalledWith('No service for the specified zone'); + expect(controller.$state.go).toHaveBeenCalledWith( + controller.$state.current.name, + { + agencyModeFk: 1, + deliveryMethodFk: 2, + geoFk: 3 + } + ); }); }); @@ -78,7 +99,11 @@ describe('Zone Component vnZoneDeliveryDays', () => { it('should call the show() method and then call the applyFilter() method with the expected ids', () => { const zoneModel = controller.$.zoneModel; jest.spyOn(controller.$.zoneEvents, 'show'); - jest.spyOn(zoneModel, 'applyFilter'); + jest.spyOn(zoneModel, 'applyFilter').mockReturnValue(new Promise(resolve => { + zoneModel.data = [ + {id: 1, events: [{price: 25}]} + ]; + })); const event = new Event('click'); const target = document.createElement('div'); @@ -88,12 +113,22 @@ describe('Zone Component vnZoneDeliveryDays', () => { {zoneFk: 2}, {zoneFk: 8} ]; - controller.onSelection(event, events); + + const day = new Date(); + controller.onSelection(event, events, [day]); const expectedFilter = { - include: { - relation: 'agencyMode', - scope: {fields: ['name']} - }, + include: [ + { + relation: 'agencyMode', + scope: {fields: ['name']} + }, + { + relation: 'events', + scope: { + where: {dated: day} + } + } + ], where: { id: {inq: [1, 2, 8]} } diff --git a/modules/zone/front/location/index.html b/modules/zone/front/location/index.html index 20755f916a..a9e9261a8d 100644 --- a/modules/zone/front/location/index.html +++ b/modules/zone/front/location/index.html @@ -1,7 +1,7 @@ + filter="$ctrl.filter"> { const data = this.$.model.data; diff --git a/modules/zone/front/routes.json b/modules/zone/front/routes.json index a0692cc3d3..e08f973147 100644 --- a/modules/zone/front/routes.json +++ b/modules/zone/front/routes.json @@ -28,33 +28,39 @@ "abstract": true, "component": "vn-zone", "description": "Zones" - }, { + }, + { "url": "/index?q", "state": "zone.index", "component": "vn-zone-index", "description": "Zones" - }, { - "url": "/delivery-days?q", + }, + { + "url": "/delivery-days?q&deliveryMethodFk&geoFk&agencyModeFk", "state": "zone.deliveryDays", "component": "vn-zone-delivery-days", "description": "Delivery days" - }, { + }, + { "url": "/upcoming-deliveries", "state": "zone.upcomingDeliveries", "component": "vn-upcoming-deliveries", "description": "Upcoming deliveries" - }, { + }, + { "url": "/create", "state": "zone.create", "component": "vn-zone-create", "description": "New zone" - }, { + }, + { "url": "/:id", "state": "zone.card", "component": "vn-zone-card", "abstract": true, "description": "Detail" - }, { + }, + { "url": "/summary", "state": "zone.card.summary", "component": "vn-zone-summary", @@ -62,7 +68,8 @@ "params": { "zone": "$ctrl.zone" } - }, { + }, + { "url": "/basic-data", "state": "zone.card.basicData", "component": "vn-zone-basic-data", @@ -70,17 +77,20 @@ "params": { "zone": "$ctrl.zone" } - }, { + }, + { "url": "/warehouses", "state": "zone.card.warehouses", "component": "vn-zone-warehouses", "description": "Warehouses" - }, { + }, + { "url": "/events", "state": "zone.card.events", "component": "vn-zone-events", "description": "Calendar" - }, { + }, + { "url": "/location?q", "state": "zone.card.location", "component": "vn-zone-location", @@ -88,7 +98,8 @@ "params": { "zone": "$ctrl.zone" } - }, { + }, + { "url" : "/log", "state": "zone.card.log", "component": "vn-zone-log", diff --git a/print/common/css/layout.css b/print/common/css/layout.css index c709191bbb..57c5db9e32 100644 --- a/print/common/css/layout.css +++ b/print/common/css/layout.css @@ -132,6 +132,16 @@ width: 8em } +.field.wide-rectangle { + white-space: nowrap +} + +.field.wide-rectangle span { + display: inline-block; + height: 2em; + width: 100%; +} + .pull-left { float: left !important } diff --git a/print/core/components/email-footer/locale/en.yml b/print/core/components/email-footer/locale/en.yml index ccc0832e8d..d18bfe3153 100644 --- a/print/core/components/email-footer/locale/en.yml +++ b/print/core/components/email-footer/locale/en.yml @@ -1,7 +1,7 @@ buttons: webAcccess: Visit our website info: Help us to improve -fiscalAddress: VERDNATURA LEVANTE SL, B97367486 Avda. Espioca, 100, 46460 Silla +fiscalAddress: VERDNATURA LEVANTE SL, B97367486 C/ Fenollar, 2. 46680 ALGEMESI · www.verdnatura.es · clientes@verdnatura.es disclaimer: '- NOTICE - This message is private and confidential, and should be used exclusively by the person receiving it. If you have received this message by mistake, diff --git a/print/core/components/email-footer/locale/fr.yml b/print/core/components/email-footer/locale/fr.yml index d93f9769e7..70d4381e6b 100644 --- a/print/core/components/email-footer/locale/fr.yml +++ b/print/core/components/email-footer/locale/fr.yml @@ -1,7 +1,7 @@ buttons: webAcccess: Visitez notre site web info: Aidez-nous à améliorer -fiscalAddress: VERDNATURA LEVANTE SL, B97367486 Avda. Espioca, 100, 46460 Silla +fiscalAddress: VERDNATURA LEVANTE SL, B97367486 C/ Fenollar, 2. 46680 ALGEMESI · www.verdnatura.es · clientes@verdnatura.es disclaimer: "- AVIS - Ce message est privé et confidentiel et doit être utilisé exclusivement par le destinataire. Si vous avez reçu ce message par erreur, diff --git a/print/core/components/email-footer/locale/pt.yml b/print/core/components/email-footer/locale/pt.yml index d7267dbaf9..b8161dd198 100644 --- a/print/core/components/email-footer/locale/pt.yml +++ b/print/core/components/email-footer/locale/pt.yml @@ -1,7 +1,7 @@ buttons: webAcccess: Visite o nosso site info: Ajude-nos a melhorar -fiscalAddress: VERDNATURA LEVANTE SL, B97367486 Avda. Espioca, 100, 46460 Silla +fiscalAddress: VERDNATURA LEVANTE SL, B97367486 C/ Fenollar, 2. 46680 ALGEMESI · www.verdnatura.es · clientes@verdnatura.es disclaimer: '- AVISO - Esta mensagem é privada e confidencial e deve ser usada exclusivamente pela pessoa que a recebe. Se você recebeu esta mensagem por engano, notifique o remetente e diff --git a/print/core/mixins/db-helper.js b/print/core/mixins/db-helper.js index 791766775f..38eb50a1d8 100644 --- a/print/core/mixins/db-helper.js +++ b/print/core/mixins/db-helper.js @@ -89,8 +89,7 @@ const dbHelper = { const absolutePath = path.join(__dirname, '../', this.path, 'sql', queryName); return db.getSqlFromDef(absolutePath); }, - }, - props: ['tplPath'] + } }; Vue.mixin(dbHelper); diff --git a/print/core/smtp.js b/print/core/smtp.js index c42a080f55..5fb5c4a2ce 100644 --- a/print/core/smtp.js +++ b/print/core/smtp.js @@ -25,7 +25,7 @@ module.exports = { throw err; }).finally(async() => { await db.rawSql(` - INSERT INTO vn.mail (sender, replyTo, sent, subject, body, status) + INSERT INTO vn.mail (receiver, replyTo, sent, subject, body, status) VALUES (?, ?, 1, ?, ?, ?)`, [ options.to, options.replyTo, diff --git a/print/methods/closure.js b/print/methods/closure.js index 85b4861581..daa2d5e7c5 100644 --- a/print/methods/closure.js +++ b/print/methods/closure.js @@ -21,7 +21,7 @@ module.exports = app => { JOIN ticket t ON t.id = e.ticketFk JOIN warehouse wh ON wh.id = t.warehouseFk AND wh.hasComission JOIN ticketState ts ON ts.ticketFk = t.id - JOIN alertLevel al ON al.alertLevel = ts.alertLevel + JOIN alertLevel al ON al.id = ts.alertLevel WHERE al.code = 'PACKED' AND DATE(t.shipped) BETWEEN DATE_ADD(?, INTERVAL -2 DAY) AND util.dayEnd(?) @@ -33,7 +33,7 @@ module.exports = app => { await db.rawSql(` UPDATE ticket t JOIN ticketState ts ON t.id = ts.ticketFk - JOIN alertLevel al ON al.alertLevel = ts.alertLevel + JOIN alertLevel al ON al.id = ts.alertLevel JOIN agencyMode am ON am.id = t.agencyModeFk JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk JOIN zone z ON z.id = t.zoneFk @@ -64,7 +64,7 @@ module.exports = app => { FROM expedition e JOIN ticket t ON t.id = e.ticketFk JOIN ticketState ts ON ts.ticketFk = t.id - JOIN alertLevel al ON al.alertLevel = ts.alertLevel + JOIN alertLevel al ON al.id = ts.alertLevel WHERE al.code = 'PACKED' AND t.id = ? AND t.refFk IS NULL @@ -100,7 +100,7 @@ module.exports = app => { FROM expedition e JOIN ticket t ON t.id = e.ticketFk JOIN ticketState ts ON ts.ticketFk = t.id - JOIN alertLevel al ON al.alertLevel = ts.alertLevel + JOIN alertLevel al ON al.id = ts.alertLevel WHERE al.code = 'PACKED' AND t.agencyModeFk IN(?) AND t.warehouseFk = ? @@ -137,14 +137,30 @@ module.exports = app => { FROM expedition e JOIN ticket t ON t.id = e.ticketFk JOIN ticketState ts ON ts.ticketFk = t.id - JOIN alertLevel al ON al.alertLevel = ts.alertLevel + JOIN alertLevel al ON al.id = ts.alertLevel WHERE al.code = 'PACKED' AND t.routeFk = ? AND t.refFk IS NULL GROUP BY e.ticketFk`, [reqArgs.routeId]); const ticketIds = tickets.map(ticket => ticket.id); - await closeAll(ticketIds, reqArgs); + + // Send route report to the agency + const agencyMail = await db.findValue(` + SELECT am.reportMail + FROM route r + JOIN agencyMode am ON am.id = r.agencyModeFk + WHERE r.id = ?`, [reqArgs.routeId]); + + if (agencyMail) { + const args = Object.assign({ + routeId: reqArgs.routeId, + recipient: agencyMail + }, reqArgs); + + const email = new Email('driver-route', args); + await email.send(); + } } catch (error) { next(error); } @@ -172,7 +188,7 @@ module.exports = app => { for (const ticket of tickets) { try { - await db.rawSql(`CALL vn.ticket_close(?)`, [ticket.id]); + await db.rawSql(`CALL vn.ticket_closeByTicket(?)`, [ticket.id]); const hasToInvoice = ticket.hasToInvoice && ticket.hasDailyInvoice; if (!ticket.salesPersonFk || !ticket.isToBeMailed || hasToInvoice) continue; diff --git a/print/package-lock.json b/print/package-lock.json deleted file mode 100644 index ef841a01e9..0000000000 --- a/print/package-lock.json +++ /dev/null @@ -1,1671 +0,0 @@ -{ - "name": "vn-print", - "version": "2.0.0", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "@types/mime-types": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/@types/mime-types/-/mime-types-2.1.0.tgz", - "integrity": "sha1-nKUs2jY/aZxpRmwqbM2q2RPqenM=" - }, - "agent-base": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-5.1.1.tgz", - "integrity": "sha512-TMeqbNl2fMW0nMjTEPOwe3J/PRFP4vqeoNuQMG0HlMrtm5QxKqdvAkZ1pRBQ/ulIyDD5Yq0nJ7YbdD8ey0TO3g==" - }, - "ajv": { - "version": "6.12.6", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", - "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", - "requires": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - } - }, - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "requires": { - "sprintf-js": "~1.0.2" - } - }, - "asn1": { - "version": "0.2.4", - "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.4.tgz", - "integrity": "sha512-jxwzQpLQjSmWXgwaCZE9Nz+glAG01yF1QnWgbhGwHI5A6FRIEY6IVqtHhIepHqI7/kyEyQEagBC5mBEFlIYvdg==", - "requires": { - "safer-buffer": "~2.1.0" - } - }, - "assert-plus": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", - "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=" - }, - "async": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/async/-/async-3.2.0.tgz", - "integrity": "sha512-TR2mEZFVOj2pLStYxLht7TyfuRzaydfpxr3k9RpHIzMgw7A64dzsdqCxH1WJyQdoe8T10nDXd9wnEigmiuHIZw==" - }, - "async-limiter": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.1.tgz", - "integrity": "sha512-csOlWGAcRFJaI6m+F2WKdnMKr4HhdhFVBk0H/QbJFMCr+uO2kwohwXQPxw/9OCxp05r5ghVBFSyioixx3gfkNQ==" - }, - "asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=" - }, - "aws-sign2": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", - "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=" - }, - "aws4": { - "version": "1.11.0", - "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.11.0.tgz", - "integrity": "sha512-xh1Rl34h6Fi1DC2WWKfxUTVqRsNnr6LsKz2+hfwDxQJWmrx8+c7ylaqBMcHfl1U1r2dsifOvKX3LQuLNZ+XSvA==" - }, - "balanced-match": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", - "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" - }, - "base64-js": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", - "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==" - }, - "bcrypt-pbkdf": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", - "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", - "requires": { - "tweetnacl": "^0.14.3" - } - }, - "boolbase": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", - "integrity": "sha1-aN/1++YMUes3cl6p4+0xDcwed24=" - }, - "brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", - "requires": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "buffer": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", - "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", - "requires": { - "base64-js": "^1.3.1", - "ieee754": "^1.1.13" - } - }, - "buffer-alloc": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/buffer-alloc/-/buffer-alloc-1.2.0.tgz", - "integrity": "sha512-CFsHQgjtW1UChdXgbyJGtnm+O/uLQeZdtbDo8mfUgYXCHSM1wgrVxXm6bSyrUuErEb+4sYVGCzASBRot7zyrow==", - "requires": { - "buffer-alloc-unsafe": "^1.1.0", - "buffer-fill": "^1.0.0" - } - }, - "buffer-alloc-unsafe": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/buffer-alloc-unsafe/-/buffer-alloc-unsafe-1.1.0.tgz", - "integrity": "sha512-TEM2iMIEQdJ2yjPJoSIsldnleVaAk1oW3DBVUykyOLsEsFmEc9kn+SFFPz+gl54KQNxlDnAwCXosOS9Okx2xAg==" - }, - "buffer-crc32": { - "version": "0.2.13", - "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", - "integrity": "sha1-DTM+PwDqxQqhRUq9MO+MKl2ackI=" - }, - "buffer-fill": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/buffer-fill/-/buffer-fill-1.0.0.tgz", - "integrity": "sha1-+PeLdniYiO858gXNY39o5wISKyw=" - }, - "buffer-from": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", - "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==" - }, - "camelcase": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", - "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==" - }, - "caseless": { - "version": "0.12.0", - "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", - "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "cheerio": { - "version": "0.22.0", - "resolved": "https://registry.npmjs.org/cheerio/-/cheerio-0.22.0.tgz", - "integrity": "sha1-qbqoYKP5tZWmuBsahocxIe06Jp4=", - "requires": { - "css-select": "~1.2.0", - "dom-serializer": "~0.1.0", - "entities": "~1.1.1", - "htmlparser2": "^3.9.1", - "lodash.assignin": "^4.0.9", - "lodash.bind": "^4.1.4", - "lodash.defaults": "^4.0.1", - "lodash.filter": "^4.4.0", - "lodash.flatten": "^4.2.0", - "lodash.foreach": "^4.3.0", - "lodash.map": "^4.4.0", - "lodash.merge": "^4.4.0", - "lodash.pick": "^4.2.1", - "lodash.reduce": "^4.4.0", - "lodash.reject": "^4.4.0", - "lodash.some": "^4.4.0" - } - }, - "cliui": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-5.0.0.tgz", - "integrity": "sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==", - "requires": { - "string-width": "^3.1.0", - "strip-ansi": "^5.2.0", - "wrap-ansi": "^5.1.0" - }, - "dependencies": { - "ansi-regex": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", - "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" - }, - "strip-ansi": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", - "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", - "requires": { - "ansi-regex": "^4.1.0" - } - } - } - }, - "color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "requires": { - "color-name": "1.1.3" - } - }, - "color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" - }, - "combined-stream": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", - "requires": { - "delayed-stream": "~1.0.0" - } - }, - "commander": { - "version": "2.20.3", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", - "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==" - }, - "concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" - }, - "concat-stream": { - "version": "1.6.2", - "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", - "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", - "requires": { - "buffer-from": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^2.2.2", - "typedarray": "^0.0.6" - }, - "dependencies": { - "isarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", - "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" - }, - "readable-stream": { - "version": "2.3.7", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", - "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", - "requires": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.3", - "isarray": "~1.0.0", - "process-nextick-args": "~2.0.0", - "safe-buffer": "~5.1.1", - "string_decoder": "~1.1.1", - "util-deprecate": "~1.0.1" - } - }, - "safe-buffer": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" - }, - "string_decoder": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", - "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", - "requires": { - "safe-buffer": "~5.1.0" - } - } - } - }, - "core-util-is": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", - "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" - }, - "cross-spawn": { - "version": "6.0.5", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", - "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", - "requires": { - "nice-try": "^1.0.4", - "path-key": "^2.0.1", - "semver": "^5.5.0", - "shebang-command": "^1.2.0", - "which": "^1.2.9" - } - }, - "css-select": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/css-select/-/css-select-1.2.0.tgz", - "integrity": "sha1-KzoRBTnFNV8c2NMUYj6HCxIeyFg=", - "requires": { - "boolbase": "~1.0.0", - "css-what": "2.1", - "domutils": "1.5.1", - "nth-check": "~1.0.1" - } - }, - "css-what": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/css-what/-/css-what-2.1.3.tgz", - "integrity": "sha512-a+EPoD+uZiNfh+5fxw2nO9QwFa6nJe2Or35fGY6Ipw1R3R4AGz1d1TEZrCegvw2YTmZ0jXirGYlzxxpYSHwpEg==" - }, - "dashdash": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", - "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", - "requires": { - "assert-plus": "^1.0.0" - } - }, - "datauri": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/datauri/-/datauri-2.0.0.tgz", - "integrity": "sha512-zS2HSf9pI5XPlNZgIqJg/wCJpecgU/HA6E/uv2EfaWnW1EiTGLfy/EexTIsC9c99yoCOTXlqeeWk4FkCSuO3/g==", - "requires": { - "image-size": "^0.7.3", - "mimer": "^1.0.0" - } - }, - "debug": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz", - "integrity": "sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==", - "requires": { - "ms": "2.1.2" - } - }, - "decamelize": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", - "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=" - }, - "deep-extend": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", - "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==" - }, - "delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=" - }, - "denque": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/denque/-/denque-1.5.0.tgz", - "integrity": "sha512-CYiCSgIF1p6EUByQPlGkKnP1M9g0ZV3qMIrqMqZqdwazygIA/YP2vrbcyl1h/WppKJTdl1F85cXIle+394iDAQ==" - }, - "dijkstrajs": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.1.tgz", - "integrity": "sha1-082BIh4+pAdCz83lVtTpnpjdxxs=" - }, - "dom-serializer": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-0.1.1.tgz", - "integrity": "sha512-l0IU0pPzLWSHBcieZbpOKgkIn3ts3vAh7ZuFyXNwJxJXk/c4Gwj9xaTJwIDVQCXawWD0qb3IzMGH5rglQaO0XA==", - "requires": { - "domelementtype": "^1.3.0", - "entities": "^1.1.1" - } - }, - "domelementtype": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.3.1.tgz", - "integrity": "sha512-BSKB+TSpMpFI/HOxCNr1O8aMOTZ8hT3pM3GQ0w/mWRmkhEDSFJkkyzz4XQsBV44BChwGkrDfMyjVD0eA2aFV3w==" - }, - "domhandler": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-2.4.2.tgz", - "integrity": "sha512-JiK04h0Ht5u/80fdLMCEmV4zkNh2BcoMFBmZ/91WtYZ8qVXSKjiw7fXMgFPnHcSZgOo3XdinHvmnDUeMf5R4wA==", - "requires": { - "domelementtype": "1" - } - }, - "domutils": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/domutils/-/domutils-1.5.1.tgz", - "integrity": "sha1-3NhIiib1Y9YQeeSMn3t+Mjc2gs8=", - "requires": { - "dom-serializer": "0", - "domelementtype": "1" - } - }, - "ecc-jsbn": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", - "integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=", - "requires": { - "jsbn": "~0.1.0", - "safer-buffer": "^2.1.0" - } - }, - "emoji-regex": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", - "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==" - }, - "entities": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/entities/-/entities-1.1.2.tgz", - "integrity": "sha512-f2LZMYl1Fzu7YSBKg+RoROelpOaNrcGmE9AZubeDfrCEia483oW4MI4VyFd5VNHIgQ/7qm1I0wUHK1eJnn2y2w==" - }, - "escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" - }, - "esprima": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==" - }, - "extend": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", - "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" - }, - "extract-zip": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-1.7.0.tgz", - "integrity": "sha512-xoh5G1W/PB0/27lXgMQyIhP5DSY/LhoCsOyZgb+6iMmRtCwVBo55uKaMoEYrDCKQhWvqEip5ZPKAc6eFNyf/MA==", - "requires": { - "concat-stream": "^1.6.2", - "debug": "^2.6.9", - "mkdirp": "^0.5.4", - "yauzl": "^2.10.0" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "requires": { - "ms": "2.0.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" - } - } - }, - "extsprintf": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", - "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=" - }, - "fast-deep-equal": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" - }, - "fast-json-stable-stringify": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==" - }, - "fd-slicer": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz", - "integrity": "sha1-JcfInLH5B3+IkbvmHY85Dq4lbx4=", - "requires": { - "pend": "~1.2.0" - } - }, - "find-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", - "requires": { - "locate-path": "^3.0.0" - } - }, - "forever-agent": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", - "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=" - }, - "form-data": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz", - "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", - "requires": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.6", - "mime-types": "^2.1.12" - } - }, - "fs-extra": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-7.0.1.tgz", - "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==", - "requires": { - "graceful-fs": "^4.1.2", - "jsonfile": "^4.0.0", - "universalify": "^0.1.0" - } - }, - "fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" - }, - "function-bind": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", - "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" - }, - "generate-function": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", - "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==", - "requires": { - "is-property": "^1.0.2" - } - }, - "get-caller-file": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==" - }, - "getpass": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", - "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", - "requires": { - "assert-plus": "^1.0.0" - } - }, - "glob": { - "version": "7.1.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", - "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.0.4", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - }, - "graceful-fs": { - "version": "4.2.6", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.6.tgz", - "integrity": "sha512-nTnJ528pbqxYanhpDYsi4Rd8MAeaBA67+RZ10CM1m3bTAVFEDcd5AuA4a6W5YkGZ1iNXHzZz8T6TBKLeBuNriQ==" - }, - "har-schema": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", - "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=" - }, - "har-validator": { - "version": "5.1.5", - "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.5.tgz", - "integrity": "sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==", - "requires": { - "ajv": "^6.12.3", - "har-schema": "^2.0.0" - } - }, - "has": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", - "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", - "requires": { - "function-bind": "^1.1.1" - } - }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" - }, - "hash-sum": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/hash-sum/-/hash-sum-1.0.2.tgz", - "integrity": "sha1-M7QHd3VMZDJXPBIMw4CLvRDUfwQ=" - }, - "he": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", - "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==" - }, - "htmlparser2": { - "version": "3.10.1", - "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-3.10.1.tgz", - "integrity": "sha512-IgieNijUMbkDovyoKObU1DUhm1iwNYE/fuifEoEHfd1oZKZDaONBSkal7Y01shxsM49R4XaMdGez3WnF9UfiCQ==", - "requires": { - "domelementtype": "^1.3.1", - "domhandler": "^2.3.0", - "domutils": "^1.5.1", - "entities": "^1.1.1", - "inherits": "^2.0.1", - "readable-stream": "^3.1.1" - } - }, - "http-signature": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", - "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=", - "requires": { - "assert-plus": "^1.0.0", - "jsprim": "^1.2.2", - "sshpk": "^1.7.0" - } - }, - "https-proxy-agent": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-4.0.0.tgz", - "integrity": "sha512-zoDhWrkR3of1l9QAL8/scJZyLu8j/gBkcwcaQOZh7Gyh/+uJQzGVETdgT30akuwkpL8HTRfssqI3BZuV18teDg==", - "requires": { - "agent-base": "5", - "debug": "4" - } - }, - "iconv-lite": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.5.2.tgz", - "integrity": "sha512-kERHXvpSaB4aU3eANwidg79K8FlrN77m8G9V+0vOR3HYaRifrlwMEpT7ZBJqLSEIHnEgJTHcWK82wwLwwKwtag==", - "requires": { - "safer-buffer": ">= 2.1.2 < 3" - } - }, - "ieee754": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", - "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==" - }, - "image-size": { - "version": "0.7.5", - "resolved": "https://registry.npmjs.org/image-size/-/image-size-0.7.5.tgz", - "integrity": "sha512-Hiyv+mXHfFEP7LzUL/llg9RwFxxY+o9N3JVLIeG5E7iFIFAalxvRU9UZthBdYDEVnzHMgjnKJPPpay5BWf1g9g==" - }, - "inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", - "requires": { - "once": "^1.3.0", - "wrappy": "1" - } - }, - "inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" - }, - "intl": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/intl/-/intl-1.2.5.tgz", - "integrity": "sha1-giRKIZDE5Bn4Nx9ao02qNCDiq94=" - }, - "is-core-module": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.2.0.tgz", - "integrity": "sha512-XRAfAdyyY5F5cOXn7hYQDqh2Xmii+DEfIcQGxK/uNwMHhIkPWO0g8msXcbzLe+MpGoR951MlqM/2iIlU4vKDdQ==", - "requires": { - "has": "^1.0.3" - } - }, - "is-fullwidth-code-point": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", - "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=" - }, - "is-property": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", - "integrity": "sha1-V/4cTkhHTt1lsJkR8msc1Ald2oQ=" - }, - "is-typedarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", - "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=" - }, - "isarray": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", - "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==" - }, - "isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=" - }, - "isstream": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", - "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=" - }, - "js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", - "requires": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" - } - }, - "jsbn": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", - "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=" - }, - "json-schema": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", - "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=" - }, - "json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==" - }, - "json-stringify-safe": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", - "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=" - }, - "jsonfile": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", - "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", - "requires": { - "graceful-fs": "^4.1.6" - } - }, - "jsprim": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz", - "integrity": "sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=", - "requires": { - "assert-plus": "1.0.0", - "extsprintf": "1.3.0", - "json-schema": "0.2.3", - "verror": "1.10.0" - } - }, - "juice": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/juice/-/juice-5.2.0.tgz", - "integrity": "sha512-0l6GZmT3efexyaaay3SchKT5kG311N59TEFP5lfvEy0nz9SNqjx311plJ3b4jze7arsmDsiHQLh/xnAuk0HFTQ==", - "requires": { - "cheerio": "^0.22.0", - "commander": "^2.15.1", - "cross-spawn": "^6.0.5", - "deep-extend": "^0.6.0", - "mensch": "^0.3.3", - "slick": "^1.12.2", - "web-resource-inliner": "^4.3.1" - } - }, - "locate-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", - "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", - "requires": { - "p-locate": "^3.0.0", - "path-exists": "^3.0.0" - } - }, - "lodash._reinterpolate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lodash._reinterpolate/-/lodash._reinterpolate-3.0.0.tgz", - "integrity": "sha1-DM8tiRZq8Ds2Y8eWU4t1rG4RTZ0=" - }, - "lodash.assignin": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/lodash.assignin/-/lodash.assignin-4.2.0.tgz", - "integrity": "sha1-uo31+4QesKPoBEIysOJjqNxqKKI=" - }, - "lodash.bind": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/lodash.bind/-/lodash.bind-4.2.1.tgz", - "integrity": "sha1-euMBfpOWIqwxt9fX3LGzTbFpDTU=" - }, - "lodash.defaults": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz", - "integrity": "sha1-0JF4cW/+pN3p5ft7N/bwgCJ0WAw=" - }, - "lodash.filter": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/lodash.filter/-/lodash.filter-4.6.0.tgz", - "integrity": "sha1-ZosdSYFgOuHMWm+nYBQ+SAtMSs4=" - }, - "lodash.flatten": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/lodash.flatten/-/lodash.flatten-4.4.0.tgz", - "integrity": "sha1-8xwiIlqWMtK7+OSt2+8kCqdlph8=" - }, - "lodash.foreach": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/lodash.foreach/-/lodash.foreach-4.5.0.tgz", - "integrity": "sha1-Gmo16s5AEoDH8G3d7DUWWrJ+PlM=" - }, - "lodash.map": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/lodash.map/-/lodash.map-4.6.0.tgz", - "integrity": "sha1-dx7Hg540c9nEzeKLGTlMNWL09tM=" - }, - "lodash.merge": { - "version": "4.6.2", - "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", - "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==" - }, - "lodash.pick": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/lodash.pick/-/lodash.pick-4.4.0.tgz", - "integrity": "sha1-UvBWEP/53tQiYRRB7R/BI6AwAbM=" - }, - "lodash.reduce": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/lodash.reduce/-/lodash.reduce-4.6.0.tgz", - "integrity": "sha1-8atrg5KZrUj3hKu/R2WW8DuRTTs=" - }, - "lodash.reject": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/lodash.reject/-/lodash.reject-4.6.0.tgz", - "integrity": "sha1-gNZJLcFHCGS79YNTO2UfQqn1JBU=" - }, - "lodash.some": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/lodash.some/-/lodash.some-4.6.0.tgz", - "integrity": "sha1-G7nzFO9ri63tE7VJFpsqlF62jk0=" - }, - "lodash.template": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/lodash.template/-/lodash.template-4.5.0.tgz", - "integrity": "sha512-84vYFxIkmidUiFxidA/KjjH9pAycqW+h980j7Fuz5qxRtO9pgB7MDFTdys1N7A5mcucRiDyEq4fusljItR1T/A==", - "requires": { - "lodash._reinterpolate": "^3.0.0", - "lodash.templatesettings": "^4.0.0" - } - }, - "lodash.templatesettings": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/lodash.templatesettings/-/lodash.templatesettings-4.2.0.tgz", - "integrity": "sha512-stgLz+i3Aa9mZgnjr/O+v9ruKZsPsndy7qPZOchbqk2cnTU1ZaldKK+v7m54WoKIyxiuMZTKT2H81F8BeAc3ZQ==", - "requires": { - "lodash._reinterpolate": "^3.0.0" - } - }, - "lodash.unescape": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/lodash.unescape/-/lodash.unescape-4.0.1.tgz", - "integrity": "sha1-vyJJiGzlFM2hEvrpIYzcBlIR/Jw=" - }, - "lodash.uniq": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/lodash.uniq/-/lodash.uniq-4.5.0.tgz", - "integrity": "sha1-0CJTc662Uq3BvILklFM5qEJ1R3M=" - }, - "long": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz", - "integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==" - }, - "lru-cache": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", - "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", - "requires": { - "yallist": "^3.0.2" - } - }, - "mensch": { - "version": "0.3.4", - "resolved": "https://registry.npmjs.org/mensch/-/mensch-0.3.4.tgz", - "integrity": "sha512-IAeFvcOnV9V0Yk+bFhYR07O3yNina9ANIN5MoXBKYJ/RLYPurd2d0yw14MDhpr9/momp0WofT1bPUh3hkzdi/g==" - }, - "mime": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/mime/-/mime-2.5.2.tgz", - "integrity": "sha512-tqkh47FzKeCPD2PUiPB6pkbMzsCasjxAfC62/Wap5qrUWcb+sFasXUC5I3gYM5iBM8v/Qpn4UK0x+j0iHyFPDg==" - }, - "mime-db": { - "version": "1.46.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.46.0.tgz", - "integrity": "sha512-svXaP8UQRZ5K7or+ZmfNhg2xX3yKDMUzqadsSqi4NCH/KomcH75MAMYAGVlvXn4+b/xOPhS3I2uHKRUzvjY7BQ==" - }, - "mime-types": { - "version": "2.1.29", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.29.tgz", - "integrity": "sha512-Y/jMt/S5sR9OaqteJtslsFZKWOIIqMACsJSiHghlCAyhf7jfVYjKBmLiX8OgpWeW+fjJ2b+Az69aPFPkUOY6xQ==", - "requires": { - "mime-db": "1.46.0" - } - }, - "mimer": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/mimer/-/mimer-1.1.0.tgz", - "integrity": "sha512-y9dVfy2uiycQvDNiAYW6zp49ZhFlXDMr5wfdOiMbdzGM/0N5LNR6HTUn3un+WUQcM0koaw8FMTG1bt5EnHJdvQ==" - }, - "minimatch": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", - "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", - "requires": { - "brace-expansion": "^1.1.7" - } - }, - "minimist": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", - "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==" - }, - "mkdirp": { - "version": "0.5.5", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz", - "integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==", - "requires": { - "minimist": "^1.2.5" - } - }, - "ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" - }, - "mysql2": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-1.7.0.tgz", - "integrity": "sha512-xTWWQPjP5rcrceZQ7CSTKR/4XIDeH/cRkNH/uzvVGQ7W5c7EJ0dXeJUusk7OKhIoHj7uFKUxDVSCfLIl+jluog==", - "requires": { - "denque": "^1.4.1", - "generate-function": "^2.3.1", - "iconv-lite": "^0.5.0", - "long": "^4.0.0", - "lru-cache": "^5.1.1", - "named-placeholders": "^1.1.2", - "seq-queue": "^0.0.5", - "sqlstring": "^2.3.1" - } - }, - "named-placeholders": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.2.tgz", - "integrity": "sha512-wiFWqxoLL3PGVReSZpjLVxyJ1bRqe+KKJVbr4hGs1KWfTZTQyezHFBbuKj9hsizHyGV2ne7EMjHdxEGAybD5SA==", - "requires": { - "lru-cache": "^4.1.3" - }, - "dependencies": { - "lru-cache": { - "version": "4.1.5", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz", - "integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==", - "requires": { - "pseudomap": "^1.0.2", - "yallist": "^2.1.2" - } - }, - "yallist": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", - "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=" - } - } - }, - "nice-try": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", - "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==" - }, - "nodemailer": { - "version": "4.7.0", - "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-4.7.0.tgz", - "integrity": "sha512-IludxDypFpYw4xpzKdMAozBSkzKHmNBvGanUREjJItgJ2NYcK/s8+PggVhj7c2yGFQykKsnnmv1+Aqo0ZfjHmw==" - }, - "nth-check": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-1.0.2.tgz", - "integrity": "sha512-WeBOdju8SnzPN5vTUJYxYUxLeXpCaVP5i5e0LF8fg7WORF2Wd7wFX/pk0tYZk7s8T+J7VLy0Da6J1+wCT0AtHg==", - "requires": { - "boolbase": "~1.0.0" - } - }, - "oauth-sign": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", - "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==" - }, - "once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", - "requires": { - "wrappy": "1" - } - }, - "p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "requires": { - "p-try": "^2.0.0" - } - }, - "p-locate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", - "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", - "requires": { - "p-limit": "^2.0.0" - } - }, - "p-try": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==" - }, - "path-exists": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", - "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=" - }, - "path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" - }, - "path-key": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", - "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=" - }, - "path-parse": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz", - "integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==" - }, - "pend": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", - "integrity": "sha1-elfrVQpng/kRUzH89GY9XI4AelA=" - }, - "performance-now": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", - "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=" - }, - "pngjs": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-3.4.0.tgz", - "integrity": "sha512-NCrCHhWmnQklfH4MtJMRjZ2a8c80qXeMlQMv2uVp9ISJMTt562SbGd6n2oq0PaPgKm7Z6pL9E2UlLIhC+SHL3w==" - }, - "process-nextick-args": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", - "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==" - }, - "progress": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", - "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==" - }, - "proxy-from-env": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", - "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" - }, - "pseudomap": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", - "integrity": "sha1-8FKijacOYYkX7wqKw0wa5aaChrM=" - }, - "psl": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/psl/-/psl-1.8.0.tgz", - "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==" - }, - "punycode": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", - "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==" - }, - "puppeteer": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/puppeteer/-/puppeteer-2.1.1.tgz", - "integrity": "sha512-LWzaDVQkk1EPiuYeTOj+CZRIjda4k2s5w4MK4xoH2+kgWV/SDlkYHmxatDdtYrciHUKSXTsGgPgPP8ILVdBsxg==", - "requires": { - "@types/mime-types": "^2.1.0", - "debug": "^4.1.0", - "extract-zip": "^1.6.6", - "https-proxy-agent": "^4.0.0", - "mime": "^2.0.3", - "mime-types": "^2.1.25", - "progress": "^2.0.1", - "proxy-from-env": "^1.0.0", - "rimraf": "^2.6.1", - "ws": "^6.1.0" - } - }, - "qrcode": { - "version": "1.4.4", - "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.4.4.tgz", - "integrity": "sha512-oLzEC5+NKFou9P0bMj5+v6Z40evexeE29Z9cummZXZ9QXyMr3lphkURzxjXgPJC5azpxcshoDWV1xE46z+/c3Q==", - "requires": { - "buffer": "^5.4.3", - "buffer-alloc": "^1.2.0", - "buffer-from": "^1.1.1", - "dijkstrajs": "^1.0.1", - "isarray": "^2.0.1", - "pngjs": "^3.3.0", - "yargs": "^13.2.4" - } - }, - "qs": { - "version": "6.5.2", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz", - "integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==" - }, - "randombytes": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", - "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", - "requires": { - "safe-buffer": "^5.1.0" - } - }, - "readable-stream": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", - "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", - "requires": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - } - }, - "request": { - "version": "2.88.2", - "resolved": "https://registry.npmjs.org/request/-/request-2.88.2.tgz", - "integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==", - "requires": { - "aws-sign2": "~0.7.0", - "aws4": "^1.8.0", - "caseless": "~0.12.0", - "combined-stream": "~1.0.6", - "extend": "~3.0.2", - "forever-agent": "~0.6.1", - "form-data": "~2.3.2", - "har-validator": "~5.1.3", - "http-signature": "~1.2.0", - "is-typedarray": "~1.0.0", - "isstream": "~0.1.2", - "json-stringify-safe": "~5.0.1", - "mime-types": "~2.1.19", - "oauth-sign": "~0.9.0", - "performance-now": "^2.1.0", - "qs": "~6.5.2", - "safe-buffer": "^5.1.2", - "tough-cookie": "~2.5.0", - "tunnel-agent": "^0.6.0", - "uuid": "^3.3.2" - } - }, - "require-directory": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", - "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=" - }, - "require-main-filename": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", - "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" - }, - "resolve": { - "version": "1.20.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz", - "integrity": "sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==", - "requires": { - "is-core-module": "^2.2.0", - "path-parse": "^1.0.6" - } - }, - "rimraf": { - "version": "2.7.1", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", - "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", - "requires": { - "glob": "^7.1.3" - } - }, - "safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==" - }, - "safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" - }, - "semver": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", - "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" - }, - "seq-queue": { - "version": "0.0.5", - "resolved": "https://registry.npmjs.org/seq-queue/-/seq-queue-0.0.5.tgz", - "integrity": "sha1-1WgS4cAXpuTnw+Ojeh2m143TyT4=" - }, - "serialize-javascript": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-3.1.0.tgz", - "integrity": "sha512-JIJT1DGiWmIKhzRsG91aS6Ze4sFUrYbltlkg2onR5OrnNM02Kl/hnY/T4FN2omvyeBbQmMJv+K4cPOpGzOTFBg==", - "requires": { - "randombytes": "^2.1.0" - } - }, - "set-blocking": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", - "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=" - }, - "shebang-command": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", - "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", - "requires": { - "shebang-regex": "^1.0.0" - } - }, - "shebang-regex": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", - "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=" - }, - "slick": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/slick/-/slick-1.12.2.tgz", - "integrity": "sha1-vQSN23TefRymkV+qSldXCzVQwtc=" - }, - "source-map": { - "version": "0.5.6", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.6.tgz", - "integrity": "sha1-dc449SvwczxafwwRjYEzSiu19BI=" - }, - "sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=" - }, - "sqlstring": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.2.tgz", - "integrity": "sha512-vF4ZbYdKS8OnoJAWBmMxCQDkiEBkGQYU7UZPtL8flbDRSNkhaXvRJ279ZtI6M+zDaQovVU4tuRgzK5fVhvFAhg==" - }, - "sshpk": { - "version": "1.16.1", - "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.16.1.tgz", - "integrity": "sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg==", - "requires": { - "asn1": "~0.2.3", - "assert-plus": "^1.0.0", - "bcrypt-pbkdf": "^1.0.0", - "dashdash": "^1.12.0", - "ecc-jsbn": "~0.1.1", - "getpass": "^0.1.1", - "jsbn": "~0.1.0", - "safer-buffer": "^2.0.2", - "tweetnacl": "~0.14.0" - } - }, - "strftime": { - "version": "0.10.0", - "resolved": "https://registry.npmjs.org/strftime/-/strftime-0.10.0.tgz", - "integrity": "sha1-s/D6QZKVICpaKJ9ta+n0kJphcZM=" - }, - "string-width": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", - "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", - "requires": { - "emoji-regex": "^7.0.1", - "is-fullwidth-code-point": "^2.0.0", - "strip-ansi": "^5.1.0" - }, - "dependencies": { - "ansi-regex": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", - "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" - }, - "strip-ansi": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", - "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", - "requires": { - "ansi-regex": "^4.1.0" - } - } - } - }, - "string_decoder": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", - "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", - "requires": { - "safe-buffer": "~5.2.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - }, - "tough-cookie": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz", - "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==", - "requires": { - "psl": "^1.1.28", - "punycode": "^2.1.1" - } - }, - "tunnel-agent": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", - "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", - "requires": { - "safe-buffer": "^5.0.1" - } - }, - "tweetnacl": { - "version": "0.14.5", - "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", - "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=" - }, - "typedarray": { - "version": "0.0.6", - "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", - "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=" - }, - "universalify": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", - "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==" - }, - "uri-js": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", - "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", - "requires": { - "punycode": "^2.1.0" - } - }, - "util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" - }, - "uuid": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz", - "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==" - }, - "valid-data-url": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/valid-data-url/-/valid-data-url-2.0.0.tgz", - "integrity": "sha512-dyCZnv3aCey7yfTgIqdZanKl7xWAEEKCbgmR7SKqyK6QT/Z07ROactrgD1eA37C69ODRj7rNOjzKWVPh0EUjBA==" - }, - "verror": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", - "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", - "requires": { - "assert-plus": "^1.0.0", - "core-util-is": "1.0.2", - "extsprintf": "^1.2.0" - } - }, - "vue": { - "version": "2.6.12", - "resolved": "https://registry.npmjs.org/vue/-/vue-2.6.12.tgz", - "integrity": "sha512-uhmLFETqPPNyuLLbsKz6ioJ4q7AZHzD8ZVFNATNyICSZouqP2Sz0rotWQC8UNBF6VGSCs5abnKJoStA6JbCbfg==" - }, - "vue-i18n": { - "version": "8.24.1", - "resolved": "https://registry.npmjs.org/vue-i18n/-/vue-i18n-8.24.1.tgz", - "integrity": "sha512-iqM+npjvI9SGOAYkw1Od/y4O74gpvn5WOHeb3K125TmDJssvR62tDMMLIasPmKNbePZ1BMZ6d5jOBsrB/cK8Lw==" - }, - "vue-server-renderer": { - "version": "2.6.12", - "resolved": "https://registry.npmjs.org/vue-server-renderer/-/vue-server-renderer-2.6.12.tgz", - "integrity": "sha512-3LODaOsnQx7iMFTBLjki8xSyOxhCtbZ+nQie0wWY4iOVeEtTg1a3YQAjd82WvKxrWHHTshjvLb7OXMc2/dYuxw==", - "requires": { - "chalk": "^1.1.3", - "hash-sum": "^1.0.2", - "he": "^1.1.0", - "lodash.template": "^4.5.0", - "lodash.uniq": "^4.5.0", - "resolve": "^1.2.0", - "serialize-javascript": "^3.1.0", - "source-map": "0.5.6" - } - }, - "web-resource-inliner": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/web-resource-inliner/-/web-resource-inliner-4.3.4.tgz", - "integrity": "sha512-agVAgRhOOi4GVlvKK34oM23tDgH8390HfLnZY2HZl8OFBwKNvUJkH7t89AT2iluQP8w9VHAAKX6Z8EN7/9tqKA==", - "requires": { - "async": "^3.1.0", - "chalk": "^2.4.2", - "datauri": "^2.0.0", - "htmlparser2": "^4.0.0", - "lodash.unescape": "^4.0.1", - "request": "^2.88.0", - "safer-buffer": "^2.1.2", - "valid-data-url": "^2.0.0", - "xtend": "^4.0.2" - }, - "dependencies": { - "ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "requires": { - "color-convert": "^1.9.0" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "dom-serializer": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-1.2.0.tgz", - "integrity": "sha512-n6kZFH/KlCrqs/1GHMOd5i2fd/beQHuehKdWvNNffbGHTr/almdhuVvTVFb3V7fglz+nC50fFusu3lY33h12pA==", - "requires": { - "domelementtype": "^2.0.1", - "domhandler": "^4.0.0", - "entities": "^2.0.0" - }, - "dependencies": { - "domhandler": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-4.0.0.tgz", - "integrity": "sha512-KPTbnGQ1JeEMQyO1iYXoagsI6so/C96HZiFyByU3T6iAzpXn8EGEvct6unm1ZGoed8ByO2oirxgwxBmqKF9haA==", - "requires": { - "domelementtype": "^2.1.0" - } - } - } - }, - "domelementtype": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.1.0.tgz", - "integrity": "sha512-LsTgx/L5VpD+Q8lmsXSHW2WpA+eBlZ9HPf3erD1IoPF00/3JKHZ3BknUVA2QGDNu69ZNmyFmCWBSO45XjYKC5w==" - }, - "domhandler": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-3.3.0.tgz", - "integrity": "sha512-J1C5rIANUbuYK+FuFL98650rihynUOEzRLxW+90bKZRWB6A1X1Tf82GxR1qAWLyfNPRvjqfip3Q5tdYlmAa9lA==", - "requires": { - "domelementtype": "^2.0.1" - } - }, - "domutils": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/domutils/-/domutils-2.5.0.tgz", - "integrity": "sha512-Ho16rzNMOFk2fPwChGh3D2D9OEHAfG19HgmRR2l+WLSsIstNsAYBzePH412bL0y5T44ejABIVfTHQ8nqi/tBCg==", - "requires": { - "dom-serializer": "^1.0.1", - "domelementtype": "^2.0.1", - "domhandler": "^4.0.0" - }, - "dependencies": { - "domhandler": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-4.0.0.tgz", - "integrity": "sha512-KPTbnGQ1JeEMQyO1iYXoagsI6so/C96HZiFyByU3T6iAzpXn8EGEvct6unm1ZGoed8ByO2oirxgwxBmqKF9haA==", - "requires": { - "domelementtype": "^2.1.0" - } - } - } - }, - "entities": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz", - "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==" - }, - "htmlparser2": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-4.1.0.tgz", - "integrity": "sha512-4zDq1a1zhE4gQso/c5LP1OtrhYTncXNSpvJYtWJBtXAETPlMfi3IFNjGuQbYLuVY4ZR0QMqRVvo4Pdy9KLyP8Q==", - "requires": { - "domelementtype": "^2.0.1", - "domhandler": "^3.0.0", - "domutils": "^2.0.0", - "entities": "^2.0.0" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, - "which": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", - "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", - "requires": { - "isexe": "^2.0.0" - } - }, - "which-module": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", - "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=" - }, - "wrap-ansi": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz", - "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", - "requires": { - "ansi-styles": "^3.2.0", - "string-width": "^3.0.0", - "strip-ansi": "^5.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", - "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" - }, - "ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "requires": { - "color-convert": "^1.9.0" - } - }, - "strip-ansi": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", - "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", - "requires": { - "ansi-regex": "^4.1.0" - } - } - } - }, - "wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" - }, - "ws": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/ws/-/ws-6.2.1.tgz", - "integrity": "sha512-GIyAXC2cB7LjvpgMt9EKS2ldqr0MTrORaleiOno6TweZ6r3TKtoFQWay/2PceJ3RuBasOHzXNn5Lrw1X0bEjqA==", - "requires": { - "async-limiter": "~1.0.0" - } - }, - "xtend": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", - "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==" - }, - "y18n": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.1.tgz", - "integrity": "sha512-wNcy4NvjMYL8gogWWYAO7ZFWFfHcbdbE57tZO8e4cbpj8tfUcwrwqSl3ad8HxpYWCdXcJUCeKKZS62Av1affwQ==" - }, - "yallist": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", - "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==" - }, - "yargs": { - "version": "13.3.2", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.3.2.tgz", - "integrity": "sha512-AX3Zw5iPruN5ie6xGRIDgqkT+ZhnRlZMLMHAs8tg7nRruy2Nb+i5o9bwghAogtM08q1dpr2LVoS8KSTMYpWXUw==", - "requires": { - "cliui": "^5.0.0", - "find-up": "^3.0.0", - "get-caller-file": "^2.0.1", - "require-directory": "^2.1.1", - "require-main-filename": "^2.0.0", - "set-blocking": "^2.0.0", - "string-width": "^3.0.0", - "which-module": "^2.0.0", - "y18n": "^4.0.0", - "yargs-parser": "^13.1.2" - } - }, - "yargs-parser": { - "version": "13.1.2", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-13.1.2.tgz", - "integrity": "sha512-3lbsNRf/j+A4QuSZfDRA7HRSfWrzO0YjqTJd5kjAq37Zep1CEgaYmrH9Q3GwPiB9cHyd1Y1UwggGhJGoxipbzg==", - "requires": { - "camelcase": "^5.0.0", - "decamelize": "^1.2.0" - } - }, - "yauzl": { - "version": "2.10.0", - "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz", - "integrity": "sha1-x+sXyT4RLLEIb6bY5R+wZnt5pfk=", - "requires": { - "buffer-crc32": "~0.2.3", - "fd-slicer": "~1.1.0" - } - } - } -} diff --git a/print/package.json b/print/package.json index cefa14d8e1..09ef2b1c89 100755 --- a/print/package.json +++ b/print/package.json @@ -16,6 +16,7 @@ "fs-extra": "^7.0.1", "intl": "^1.2.5", "js-yaml": "^3.13.1", + "jsonexport": "^3.2.0", "juice": "^5.2.0", "mysql2": "^1.7.0", "nodemailer": "^4.7.0", diff --git a/print/templates/email/claim-pickup-order/locale/es.yml b/print/templates/email/claim-pickup-order/locale/es.yml index 1d49b2b2b4..fe08fb0a8a 100644 --- a/print/templates/email/claim-pickup-order/locale/es.yml +++ b/print/templates/email/claim-pickup-order/locale/es.yml @@ -2,22 +2,4 @@ subject: Orden de recogida title: Orden de recogida description: dear: Estimado cliente - instructions: Aqui tienes tu orden de recogida. -sections: - howToBuy: - title: Cómo hacer un pedido - description: 'Para realizar un pedido en nuestra web, debes configurarlo indicando:' - requeriments: - - Si quieres recibir el pedido (por agencia o por nuestro propio reparto) o si - lo prefieres recoger en alguno de nuestros almacenes. - - La fecha en la que quieres recibir el pedido (se preparará el día anterior). - - La dirección de entrega o el almacén donde quieres recoger el pedido. - stock: En nuestra web y aplicaciones puedes visualizar el stock disponible de - flor cortada, verdes, plantas, complementos y artificial. Ten en cuenta que - dicho stock puede variar en función de la fecha seleccionada al configurar el - pedido. Es importante CONFIRMAR los pedidos para que la mercancía quede reservada. - delivery: El reparto se realiza de lunes a sábado según la zona en la que te encuentres. - Por regla general, los pedidos que se entregan por agencia, deben estar confirmados - y pagados antes de las 17h del día en que se preparan (el día anterior a recibirlos), - aunque esto puede variar si el pedido se envía a través de nuestro reparto y - según la zona. + instructions: Aqui tienes tu orden de recogida. \ No newline at end of file diff --git a/print/templates/email/client-debt-statement/assets/css/import.js b/print/templates/email/client-debt-statement/assets/css/import.js new file mode 100644 index 0000000000..b44d6bd371 --- /dev/null +++ b/print/templates/email/client-debt-statement/assets/css/import.js @@ -0,0 +1,8 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/email.css`]) + .mergeStyles(); diff --git a/print/templates/email/client-debt-statement/attachments.json b/print/templates/email/client-debt-statement/attachments.json new file mode 100644 index 0000000000..9cc4911e66 --- /dev/null +++ b/print/templates/email/client-debt-statement/attachments.json @@ -0,0 +1,6 @@ +[ + { + "filename": "client-debt-statement.pdf", + "component": "client-debt-statement" + } +] \ No newline at end of file diff --git a/print/templates/email/client-debt-statement/client-debt-statement.html b/print/templates/email/client-debt-statement/client-debt-statement.html new file mode 100644 index 0000000000..e63eba7f77 --- /dev/null +++ b/print/templates/email/client-debt-statement/client-debt-statement.html @@ -0,0 +1,55 @@ + + + + + + {{ $t('subject') }} + + + + + + + + +
+ +
+
+
+ +
+
+ +
+
+ +
+
+

{{ $t('title') }}

+

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

+
+
+ +
+
+ + +
+
+ +
+
+ +
+
+ +
+
+
+
+ + \ No newline at end of file diff --git a/print/templates/email/client-debt-statement/client-debt-statement.js b/print/templates/email/client-debt-statement/client-debt-statement.js new file mode 100755 index 0000000000..c32e689430 --- /dev/null +++ b/print/templates/email/client-debt-statement/client-debt-statement.js @@ -0,0 +1,25 @@ +const Component = require(`${appPath}/core/component`); +const emailHeader = new Component('email-header'); +const emailFooter = new Component('email-footer'); +const attachment = new Component('attachment'); +const attachments = require('./attachments.json'); + +module.exports = { + name: 'client-debt-statement', + components: { + 'email-header': emailHeader.build(), + 'email-footer': emailFooter.build(), + 'attachment': attachment.build() + }, + data() { + return {attachments}; + }, + props: { + recipientId: { + required: true + }, + from: { + required: true + } + } +}; diff --git a/print/templates/email/client-debt-statement/locale/es.yml b/print/templates/email/client-debt-statement/locale/es.yml new file mode 100644 index 0000000000..754e8e92c3 --- /dev/null +++ b/print/templates/email/client-debt-statement/locale/es.yml @@ -0,0 +1,4 @@ +subject: Extracto de tu balance +title: Extracto de tu balance +description: + instructions: Adjuntamos el extracto de tu balance. \ No newline at end of file diff --git a/print/templates/email/credit-request/assets/css/import.js b/print/templates/email/credit-request/assets/css/import.js new file mode 100644 index 0000000000..b44d6bd371 --- /dev/null +++ b/print/templates/email/credit-request/assets/css/import.js @@ -0,0 +1,8 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/email.css`]) + .mergeStyles(); diff --git a/print/templates/email/credit-request/attachments.json b/print/templates/email/credit-request/attachments.json new file mode 100644 index 0000000000..12b10df4c7 --- /dev/null +++ b/print/templates/email/credit-request/attachments.json @@ -0,0 +1,6 @@ +[ + { + "filename": "credit-request.pdf", + "component": "credit-request" + } +] \ No newline at end of file diff --git a/print/templates/email/credit-request/credit-request.html b/print/templates/email/credit-request/credit-request.html new file mode 100644 index 0000000000..e63eba7f77 --- /dev/null +++ b/print/templates/email/credit-request/credit-request.html @@ -0,0 +1,55 @@ + + + + + + {{ $t('subject') }} + + + + + + + + +
+ +
+
+
+ +
+
+ +
+
+ +
+
+

{{ $t('title') }}

+

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

+
+
+ +
+
+ + +
+
+ +
+
+ +
+
+ +
+
+
+
+ + \ No newline at end of file diff --git a/print/templates/email/credit-request/credit-request.js b/print/templates/email/credit-request/credit-request.js new file mode 100755 index 0000000000..69463f43ab --- /dev/null +++ b/print/templates/email/credit-request/credit-request.js @@ -0,0 +1,17 @@ +const Component = require(`${appPath}/core/component`); +const emailHeader = new Component('email-header'); +const emailFooter = new Component('email-footer'); +const attachment = new Component('attachment'); +const attachments = require('./attachments.json'); + +module.exports = { + name: 'credit-request', + components: { + 'email-header': emailHeader.build(), + 'email-footer': emailFooter.build(), + 'attachment': attachment.build() + }, + data() { + return {attachments}; + }, +}; diff --git a/print/templates/email/credit-request/locale/es.yml b/print/templates/email/credit-request/locale/es.yml new file mode 100644 index 0000000000..aa6e63dcbd --- /dev/null +++ b/print/templates/email/credit-request/locale/es.yml @@ -0,0 +1,4 @@ +subject: Solicitud de crédito +title: Solicitud de crédito +description: + instructions: Adjuntamos el formulario para solicitud de crédito. \ No newline at end of file diff --git a/print/templates/email/delivery-note-link/locale/pt.yml b/print/templates/email/delivery-note-link/locale/pt.yml index cff3ea52bc..1aab4b6d8a 100644 --- a/print/templates/email/delivery-note-link/locale/pt.yml +++ b/print/templates/email/delivery-note-link/locale/pt.yml @@ -1,5 +1,5 @@ -subject: Vossa nota de entrega -title: Vossa nota de entrega +subject: Sua nota de entrega +title: Sua nota de entrega dear: Estimado cliente description: Já está disponível sua nota de entrega correspondente a encomenda numero {0}.
Para ver-lo faça um clique
neste link. diff --git a/print/templates/email/delivery-note/locale/pt.yml b/print/templates/email/delivery-note/locale/pt.yml index 818a4de4c0..0418fe7a50 100644 --- a/print/templates/email/delivery-note/locale/pt.yml +++ b/print/templates/email/delivery-note/locale/pt.yml @@ -1,5 +1,5 @@ -subject: Vossa nota de entrega -title: Vossa nota de entrega +subject: Sua nota de entrega +title: Sua nota de entrega dear: Estimado cliente description: Já está disponível sua nota de entrega correspondente a encomenda {0}.
Podes descarregar-la fazendo um clique no arquivo anexado ao e-mail. diff --git a/print/templates/email/invoice/assets/css/import.js b/print/templates/email/invoice/assets/css/import.js new file mode 100644 index 0000000000..b44d6bd371 --- /dev/null +++ b/print/templates/email/invoice/assets/css/import.js @@ -0,0 +1,8 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/email.css`]) + .mergeStyles(); diff --git a/print/templates/email/invoice/attachments.json b/print/templates/email/invoice/attachments.json new file mode 100644 index 0000000000..1abbea18a9 --- /dev/null +++ b/print/templates/email/invoice/attachments.json @@ -0,0 +1,6 @@ +[ + { + "filename": "invoice.pdf", + "component": "invoice" + } +] \ No newline at end of file diff --git a/print/templates/email/invoice/invoice.html b/print/templates/email/invoice/invoice.html new file mode 100644 index 0000000000..66bad472a2 --- /dev/null +++ b/print/templates/email/invoice/invoice.html @@ -0,0 +1,49 @@ + + + + + + {{ $t('subject') }} + + + + + + + + +
+ +
+
+
+ +
+
+ +
+
+ +
+
+

{{ $t('title') }}

+

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

+

+

+

+

+
+
+ +
+
+ +
+
+ +
+
+
+
+ + \ No newline at end of file diff --git a/print/templates/email/invoice/invoice.js b/print/templates/email/invoice/invoice.js new file mode 100755 index 0000000000..b8d3b8282f --- /dev/null +++ b/print/templates/email/invoice/invoice.js @@ -0,0 +1,25 @@ +const Component = require(`${appPath}/core/component`); +const emailHeader = new Component('email-header'); +const emailFooter = new Component('email-footer'); + +module.exports = { + name: 'invoice', + async serverPrefetch() { + this.invoice = await this.fetchInvoice(this.invoiceId); + }, + methods: { + fetchInvoice(invoiceId) { + return this.findOneFromDef('invoice', [invoiceId]); + }, + }, + components: { + 'email-header': emailHeader.build(), + 'email-footer': emailFooter.build() + }, + props: { + invoiceId: { + type: String, + required: true + } + } +}; diff --git a/print/templates/email/invoice/locale/en.yml b/print/templates/email/invoice/locale/en.yml new file mode 100644 index 0000000000..bf1287cae5 --- /dev/null +++ b/print/templates/email/invoice/locale/en.yml @@ -0,0 +1,9 @@ +subject: Your invoice +title: Your invoice +dear: Dear client +description: The invoice {0} from the order {1} is now available.
+ You can download it by clicking on the attachment of this email. +poll: If you wish, you can answer our satisfaction survey to + help us provide better service. Your opinion is very important for us! +help: Any questions that arise, do not hesitate to consult it, we are here to assist you! +conclusion: Thanks for your attention! diff --git a/print/templates/email/invoice/locale/es.yml b/print/templates/email/invoice/locale/es.yml new file mode 100644 index 0000000000..0147d15ac3 --- /dev/null +++ b/print/templates/email/invoice/locale/es.yml @@ -0,0 +1,10 @@ +subject: Tu factura +title: Tu factura +dear: Estimado cliente +description: Ya está disponible la factura {0} correspondiente al pedido {1}.
+ Puedes descargarla haciendo clic en el adjunto de este correo. +poll: Si lo deseas, puedes responder a nuestra encuesta de satisfacción para + ayudarnos a prestar un mejor servicio. ¡Tu opinión es muy importante para nosotros! +help: Cualquier duda que te surja, no dudes en consultarla, ¡estamos para + atenderte! +conclusion: ¡Gracias por tu atención! diff --git a/print/templates/email/invoice/locale/fr.yml b/print/templates/email/invoice/locale/fr.yml new file mode 100644 index 0000000000..9efbdf5a03 --- /dev/null +++ b/print/templates/email/invoice/locale/fr.yml @@ -0,0 +1,9 @@ +subject: Votre facture +title: Votre facture +dear: Cher client, +description: Le facture {0} correspondant à la commande {1} est maintenant disponible.
+ Vous pouvez le télécharger en cliquant sur la pièce jointe dans cet email. +poll: Si vous le souhaitez, vous pouvez répondre à notre questionaire de satisfaction + pour nous aider à améliorer notre service. Votre avis est très important pour nous! +help: N'hésitez pas nous envoyer toute doute ou question, nous sommes là pour vous aider! +conclusion: Merci pour votre attention! diff --git a/print/templates/email/invoice/locale/pt.yml b/print/templates/email/invoice/locale/pt.yml new file mode 100644 index 0000000000..4d779cd3d8 --- /dev/null +++ b/print/templates/email/invoice/locale/pt.yml @@ -0,0 +1,9 @@ +subject: Sua fatura +title: Sua fatura +dear: Estimado cliente +description: Já está disponível sua fatura {0} correspondente a encomenda {1}.
+ Podes descarregar-la fazendo um clique no arquivo anexado ao e-mail. +poll: Si o deseja, podes responder nosso questionário de satiscação para ajudar-nos a prestar-vos um melhor serviço. Tua opinião é muito importante para nós! +help: Cualquer dúvida que surja, no hesites em consultar-la, Estamos aqui para + atender-te! +conclusion: Obrigado por tua atenção! \ No newline at end of file diff --git a/print/templates/email/invoice/sql/invoice.sql b/print/templates/email/invoice/sql/invoice.sql new file mode 100644 index 0000000000..195621a36d --- /dev/null +++ b/print/templates/email/invoice/sql/invoice.sql @@ -0,0 +1,7 @@ +SELECT + io.ref, + t.id AS ticketFk +FROM invoiceOut io + JOIN ticket t ON t.refFk = io.ref + JOIN client c ON c.id = io.clientFk +WHERE io.id = ? \ No newline at end of file diff --git a/print/templates/email/osticket-report/sql/tickets.sql b/print/templates/email/osticket-report/sql/tickets.sql index bc118a65f1..4056298e1a 100644 --- a/print/templates/email/osticket-report/sql/tickets.sql +++ b/print/templates/email/osticket-report/sql/tickets.sql @@ -19,8 +19,9 @@ SELECT * FROM ( AND ote.type = 'M' LEFT JOIN ost_thread_entry oter ON oth.id = oter.thread_id AND oter.type = 'R' - WHERE ots.state = 'closed' - AND closed BETWEEN ? AND ? + WHERE ot.ticket_pid = NULL + AND ots.state = 'closed' + AND otc.closed BETWEEN ? AND ? ORDER BY oter.created DESC ) ot GROUP BY ot.ticket_id ORDER BY ot.assigned \ No newline at end of file diff --git a/print/templates/reports/client-debt-statement/assets/css/import.js b/print/templates/reports/client-debt-statement/assets/css/import.js new file mode 100644 index 0000000000..fd8796c2bf --- /dev/null +++ b/print/templates/reports/client-debt-statement/assets/css/import.js @@ -0,0 +1,9 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/report.css`, + `${__dirname}/style.css`]) + .mergeStyles(); diff --git a/print/templates/reports/client-debt-statement/assets/css/style.css b/print/templates/reports/client-debt-statement/assets/css/style.css new file mode 100644 index 0000000000..e621f3e235 --- /dev/null +++ b/print/templates/reports/client-debt-statement/assets/css/style.css @@ -0,0 +1,3 @@ +table.column-oriented { + margin-top: 50px !important +} \ No newline at end of file diff --git a/print/templates/reports/client-debt-statement/client-debt-statement.html b/print/templates/reports/client-debt-statement/client-debt-statement.html new file mode 100644 index 0000000000..88bf15bdbd --- /dev/null +++ b/print/templates/reports/client-debt-statement/client-debt-statement.html @@ -0,0 +1,95 @@ + + + + + + + + + +
+ + + +
+
+
+
+
+

{{$t('title')}}

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

{{client.socialName}}

+
+ {{client.street}} +
+
+ {{client.postcode}}, {{client.city}} ({{client.province}}) +
+
+ {{client.country}} +
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
{{$t('date')}}{{$t('concept')}}{{$t('invoiced')}}{{$t('payed')}}{{$t('balance')}}
{{sale.issued | date('%d-%m-%Y')}}{{sale.ref}}{{sale.debtOut}}{{sale.debtIn}}{{getBalance(sale)}}
+ Total + {{getTotalDebtOut() | currency('EUR', $i18n.locale)}} + {{getTotalDebtIn() | currency('EUR', $i18n.locale)}}{{totalBalance | currency('EUR', $i18n.locale)}}
+
+
+ + + +
+ + \ No newline at end of file diff --git a/print/templates/reports/client-debt-statement/client-debt-statement.js b/print/templates/reports/client-debt-statement/client-debt-statement.js new file mode 100755 index 0000000000..09b99590b4 --- /dev/null +++ b/print/templates/reports/client-debt-statement/client-debt-statement.js @@ -0,0 +1,78 @@ +const Component = require(`${appPath}/core/component`); +const reportHeader = new Component('report-header'); +const reportFooter = new Component('report-footer'); + +module.exports = { + name: 'client-debt-statement', + async serverPrefetch() { + this.client = await this.fetchClient(this.recipientId); + this.sales = await this.fetchSales(this.recipientId, this.from); + + if (!this.client) + throw new Error('Something went wrong'); + }, + computed: { + dated: function() { + const filters = this.$options.filters; + + return filters.date(new Date(), '%d-%m-%Y'); + } + }, + data() { + return {totalBalance: 0.00}; + }, + methods: { + fetchClient(clientId) { + return this.findOneFromDef('client', [clientId]); + }, + fetchSales(clientId, from) { + return this.rawSqlFromDef('sales', [ + from, + clientId, + from, + clientId, + from, + clientId, + from, + clientId, + from, + clientId + ]); + }, + getBalance(sale) { + if (sale.debtOut) + this.totalBalance += parseFloat(sale.debtOut); + + if (sale.debtIn) + this.totalBalance -= parseFloat(sale.debtIn); + + return parseFloat(this.totalBalance.toFixed(2)); + }, + getTotalDebtOut() { + let debtOut = 0.00; + for (let sale of this.sales) + debtOut += sale.debtOut ? parseFloat(sale.debtOut) : 0; + + return debtOut.toFixed(2); + }, + getTotalDebtIn() { + let debtIn = 0.00; + for (let sale of this.sales) + debtIn += sale.debtIn ? parseFloat(sale.debtIn) : 0; + + return debtIn.toFixed(2); + }, + }, + components: { + 'report-header': reportHeader.build(), + 'report-footer': reportFooter.build() + }, + props: { + recipientId: { + required: true + }, + from: { + required: true + } + } +}; diff --git a/print/templates/reports/client-debt-statement/locale/es.yml b/print/templates/reports/client-debt-statement/locale/es.yml new file mode 100644 index 0000000000..ccdce7b5bc --- /dev/null +++ b/print/templates/reports/client-debt-statement/locale/es.yml @@ -0,0 +1,9 @@ +title: Extracto +clientId: Cliente +clientData: Datos del cliente +date: Fecha +concept: Concepto +invoiced: Facturado +payed: Pagado +balance: Saldo +client: Cliente {0} \ No newline at end of file diff --git a/print/templates/reports/client-debt-statement/locale/fr.yml b/print/templates/reports/client-debt-statement/locale/fr.yml new file mode 100644 index 0000000000..12534f9ff2 --- /dev/null +++ b/print/templates/reports/client-debt-statement/locale/fr.yml @@ -0,0 +1,9 @@ +title: Relevé de compte +clientId: Client +clientData: Données client +date: Date +concept: Objet +invoiced: Facturé +payed: Payé +balance: Solde +client: Client {0} \ No newline at end of file diff --git a/print/templates/reports/client-debt-statement/sql/client.sql b/print/templates/reports/client-debt-statement/sql/client.sql new file mode 100644 index 0000000000..d675cf168d --- /dev/null +++ b/print/templates/reports/client-debt-statement/sql/client.sql @@ -0,0 +1,13 @@ +SELECT + c.id, + c.socialName, + c.street, + c.postcode, + c.city, + c.fi, + p.name AS province, + ct.country +FROM client c + JOIN country ct ON ct.id = c.countryFk + LEFT JOIN province p ON p.id = c.provinceFk +WHERE c.id = ? \ No newline at end of file diff --git a/print/templates/reports/client-debt-statement/sql/sales.sql b/print/templates/reports/client-debt-statement/sql/sales.sql new file mode 100644 index 0000000000..7a9124da5d --- /dev/null +++ b/print/templates/reports/client-debt-statement/sql/sales.sql @@ -0,0 +1,53 @@ +SELECT + issued, + CAST(debtOut AS DECIMAL(10,2)) debtOut, + CAST(debtIn AS DECIMAL(10,2)) debtIn, + ref, + companyFk, + priority +FROM ( + SELECT + ? AS issued, + SUM(amountUnpaid) AS debtOut, + NULL AS debtIn, + 'Saldo Anterior' AS ref, + companyFk, + 0 as priority + FROM ( + SELECT SUM(amount) AS amountUnpaid, companyFk, 0 + FROM invoiceOut io + WHERE io.clientFk = ? + AND io.issued < ? + GROUP BY io.companyFk + UNION ALL + SELECT SUM(-1 * amountPaid), companyFk, 0 + FROM receipt + WHERE clientFk = ? + AND payed < ? + GROUP BY companyFk) AS transactions + GROUP BY companyFk + UNION ALL + SELECT + issued, + amount as debtOut, + NULL AS debtIn, + ref, + companyFk, + 1 + FROM invoiceOut + WHERE clientFk = ? + AND issued >= ? + UNION ALL + SELECT + r.payed, + NULL as debtOut, + r.amountPaid, + r.invoiceFk, + r.companyFk, + 0 + FROM receipt r + WHERE r.clientFk = ? + AND r.payed >= ?) t + INNER JOIN `client` c ON c.id = ? +HAVING debtOut <> 0 OR debtIn <> 0 +ORDER BY issued, priority DESC, debtIn; \ No newline at end of file diff --git a/print/templates/reports/credit-request/assets/css/import.js b/print/templates/reports/credit-request/assets/css/import.js new file mode 100644 index 0000000000..fd8796c2bf --- /dev/null +++ b/print/templates/reports/credit-request/assets/css/import.js @@ -0,0 +1,9 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/report.css`, + `${__dirname}/style.css`]) + .mergeStyles(); diff --git a/print/templates/reports/credit-request/assets/css/style.css b/print/templates/reports/credit-request/assets/css/style.css new file mode 100644 index 0000000000..90bbfd1038 --- /dev/null +++ b/print/templates/reports/credit-request/assets/css/style.css @@ -0,0 +1,52 @@ +.wide { + width: 900px !important +} + +.content { + position: absolute; + margin-top: -200px; + height: 400px; + top: 50% +} + +p { + font-size: 1.2em; + margin: 0 +} + +td > span { + width: 100%; + margin-bottom: 15px +} + +.green-background { + color: white; + background-color: #8dba25; + height: 2em; + line-height: 2em; + padding-left: 0.5em; +} + +.info-panel td, .info-panel th { + padding: 1em 1em; +} + +.info-panel { + margin-bottom: 5em; +} + +table { + width: 100%; +} + +th { + width: 30%; +} + +td { + width: 20%; +} + +.field { + float: none +} \ No newline at end of file diff --git a/print/templates/reports/credit-request/credit-request.html b/print/templates/reports/credit-request/credit-request.html new file mode 100644 index 0000000000..975115eef8 --- /dev/null +++ b/print/templates/reports/credit-request/credit-request.html @@ -0,0 +1,190 @@ + + + + + + + + + +
+ + + + +
+
+

{{$t('fields.title')}}

+
+
+ + + + + + + + + +
{{$t('fields.date')}}: +
+ +
+
+ + +
+
+
+
+

{{$t('fields.companyInfo')}}

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
{{$t('fields.companyName')}}: +
+ +
+
{{$t('fields.businessType')}}: +
+ +
+
{{$t('fields.antiquity')}}: +
+ +
+
{{$t('fields.surface')}}: +
+ +
+
{{$t('fields.numberOfEmployees')}}: +
+ +
+
{{$t('fields.owner')}}: +
+ +
+
{{$t('fields.phone')}}: +
+ +
+
{{$t('fields.payer')}}: +
+ +
+
{{$t('fields.phone')}}: +
+ +
+
+
+
+
+
+ + +
+
+
+
+

{{$t('fields.economicInfo')}}

+
+
+ + + + + + + + + + + + + + + +
{{$t('fields.previousSalesVolume')}}: +
+ +
+
{{$t('fields.forecastedSalesVolume')}}: +
+ +
+
{{$t('fields.forecastedPurchases')}}: +
+ +
+
+
+
+
+
+ + +
+
+
+ + + + + + + + + +
{{$t('fields.personFilling')}}: +
+ +
+
{{$t('fields.phone')}}: +
+ +
+
+
+
+
+ + + +
+ + \ No newline at end of file diff --git a/print/templates/reports/credit-request/credit-request.js b/print/templates/reports/credit-request/credit-request.js new file mode 100755 index 0000000000..d041064932 --- /dev/null +++ b/print/templates/reports/credit-request/credit-request.js @@ -0,0 +1,20 @@ +const Component = require(`${appPath}/core/component`); +const reportHeader = new Component('report-header'); +const reportFooter = new Component('report-footer'); + +const rptCreditRequest = { + name: 'credit-request', + computed: { + dated: function() { + const filters = this.$options.filters; + + return filters.date(new Date(), '%d-%m-%Y'); + } + }, + components: { + 'report-header': reportHeader.build(), + 'report-footer': reportFooter.build() + } +}; + +module.exports = rptCreditRequest; diff --git a/print/templates/reports/credit-request/locale/es.yml b/print/templates/reports/credit-request/locale/es.yml new file mode 100644 index 0000000000..e4e9739a57 --- /dev/null +++ b/print/templates/reports/credit-request/locale/es.yml @@ -0,0 +1,17 @@ +fields: + title: Solicitud de crédito + date: Fecha + companyName: Nombre de la empresa + businessType: Tipo de negocio + antiquity: Antigüedad + surface: Superficie (m²) + numberOfEmployees: Número de empleados + owner: Contacto propietario o Administrador + phone: Teléfono + payer: Contacto responsable de pagos + previousSalesVolume: Previsión ventas ejercicio anterior + forecastedSalesVolume: Previsión ventas para el presente año + forecastedPurchases: Previsión de compras a Verdnatura + personFilling: Persona que rellena el formulario + companyInfo: Información general sobre la empresa + economicInfo: Información económica \ 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 771f1fd0cc..36d9abde14 100644 --- a/print/templates/reports/delivery-note/delivery-note.html +++ b/print/templates/reports/delivery-note/delivery-note.html @@ -118,20 +118,20 @@ -
+
-

{{$t('services')}}

+

{{$t('services.title')}}

- - - + + + - - + + @@ -148,25 +148,26 @@
{{$t('quantity')}}{{$t('concept')}}{{$t('price')}}{{$t('services.theader.quantity')}}{{$t('services.theader.concept')}}{{$t('services.theader.price')}} {{$t('vat')}}{{$t('amount')}}{{$t('services.theader.vat')}}{{$t('services.theader.amount')}}
- {{$t('subtotal')}} + {{$t('services.tfoot.subtotal')}} {{serviceTotal | currency('EUR', $i18n.locale)}}
+ * {{ $t('services.warning') }}
-

{{$t('packagings')}}

+

{{$t('packagings.title')}}

- - - + + + @@ -183,21 +184,18 @@
-
{{$t('reference')}}{{$t('quantity')}}{{$t('concept')}}{{$t('packagings.theader.reference')}}{{$t('packagings.theader.quantity')}}{{$t('packagings.theader.concept')}}
- + - - - - + + + + diff --git a/print/templates/reports/delivery-note/locale/en.yml b/print/templates/reports/delivery-note/locale/en.yml index ec961cabec..8a3ff834b9 100644 --- a/print/templates/reports/delivery-note/locale/en.yml +++ b/print/templates/reports/delivery-note/locale/en.yml @@ -12,17 +12,37 @@ price: PSP/u discount: Disc. vat: VAT amount: Amount -type: Type -taxBase: Tax base -tax: Tax -fee: Fee total: Total subtotal: Subtotal -taxBreakdown: Tax breakdown -packagings: Buckets and packaging -services: Services vatType: VAT Type digitalSignature: Digital signature ticket: Delivery note {0} plantPassport: Plant passport -packages: Packages \ No newline at end of file +packages: Packages +services: + title: Services + theader: + quantity: Qty. + concept: Concept + price: PSP/u + vat: VAT + amount: Amount + tfoot: + subtotal: Subtotal + warning: Deposit packaging will be invoiced if they have not been returned after 30 days of their delivery. +packagings: + title: Buckets and packaging + theader: + reference: Reference + quantity: Quantity + concept: Concept +taxes: + title: Tax breakdown + theader: + type: Type + taxBase: Tax base + tax: Tax + fee: Fee + tfoot: + subtotal: Subtotal + total: Total \ No newline at end of file diff --git a/print/templates/reports/delivery-note/locale/es.yml b/print/templates/reports/delivery-note/locale/es.yml index 674cb875e0..f9c2e02f30 100644 --- a/print/templates/reports/delivery-note/locale/es.yml +++ b/print/templates/reports/delivery-note/locale/es.yml @@ -12,17 +12,37 @@ price: PVP/u discount: Dto. vat: IVA amount: Importe -type: Tipo -taxBase: Base imp. -tax: Tasa -fee: Cuota total: Total subtotal: Subtotal -taxBreakdown: Desglose impositivo -packagings: Cubos y embalajes -services: Servicios vatType: Tipo de IVA digitalSignature: Firma digital ticket: Albarán {0} plantPassport: Pasaporte fitosanitario -packages: Bultos \ No newline at end of file +packages: Bultos +services: + title: Servicios + theader: + quantity: Cantidad + concept: Concepto + price: PVP/u + vat: IVA + amount: Importe + tfoot: + subtotal: Subtotal + warning: Los embalajes en depósito se facturarán si no han sido devueltos pasados 30 dias de su entrega. +packagings: + title: Cubos y embalajes + theader: + reference: Referencia + quantity: Cantidad + concept: Concepto +taxes: + title: Desglose impositivo + theader: + type: Tipo + taxBase: Base imp. + tax: Tasa + fee: Cuota + tfoot: + subtotal: Subtotal + total: Total \ No newline at end of file diff --git a/print/templates/reports/delivery-note/locale/fr.yml b/print/templates/reports/delivery-note/locale/fr.yml index 526df30686..72ca771e1e 100644 --- a/print/templates/reports/delivery-note/locale/fr.yml +++ b/print/templates/reports/delivery-note/locale/fr.yml @@ -12,17 +12,37 @@ price: PRIX/u discount: Remise vat: TVA amount: Montant -type: Type -taxBase: Base imposable -tax: Taxe -fee: Quote total: Total subtotal: Total partiel -taxBreakdown: Répartition taxes -packagings: Bacs et emballages -services: Service vatType: Type de TVA digitalSignature: Signature numérique ticket: BL {0} plantPassport: Passeport phytosanitaire -packages: Paquets \ No newline at end of file +packages: Paquets +services: + title: Service + theader: + quantity: Quantité + concept: Concept + price: PRIX/u + vat: TVA + amount: Montant + tfoot: + subtotal: Total partiel + warning: Les emballages de consigne seront facturés s'ils n'ont pas été retournés après 30 jours de leur livraison. +packagings: + title: Bacs et emballages + theader: + reference: Référence + quantity: Quantité + concept: Concept +taxes: + title: Répartition taxes + theader: + type: Type + taxBase: Base imposable + tax: Taxe + fee: Quote + tfoot: + subtotal: Total partiel + total: Total \ No newline at end of file diff --git a/print/templates/reports/delivery-note/locale/pt.yml b/print/templates/reports/delivery-note/locale/pt.yml index 95bcd857ec..e830871421 100644 --- a/print/templates/reports/delivery-note/locale/pt.yml +++ b/print/templates/reports/delivery-note/locale/pt.yml @@ -12,17 +12,37 @@ price: PVP/u discount: Dto. vat: IVA amount: Importe -type: Tipo -taxBase: Base imp. -tax: Taxa -fee: Quota total: Total subtotal: Sub-total -taxBreakdown: Desglose impositivo -packagings: Baldes e Embalagens -services: Serviços vatType: Tipo de IVA digitalSignature: Assinatura digital ticket: Nota de Entrega {0} plantPassport: Passaporte vegetal -packages: Pacotes \ No newline at end of file +packages: Pacotes +services: + title: Serviços + theader: + quantity: Quantidade + concept: Conceito + price: PVP/u + vat: IVA + amount: Quantia + tfoot: + subtotal: Subtotal + warning: As embalagens em depósito serão facturadas e cobradas se não são devolvidas 30 dias após a entrega. +packagings: + title: Baldes e Embalagens + theader: + reference: Referência + quantity: Quantidade + concept: Conceito +taxes: + title: Repartição de impostos + theader: + type: Cara + taxBase: Tributável + tax: Taxa + fee: Compartilhado + tfoot: + subtotal: Subtotal + total: Total \ No newline at end of file diff --git a/print/templates/reports/driver-route/driver-route.html b/print/templates/reports/driver-route/driver-route.html index bad1bf1790..eed85e1d73 100644 --- a/print/templates/reports/driver-route/driver-route.html +++ b/print/templates/reports/driver-route/driver-route.html @@ -1,163 +1,166 @@ - -
{{$t('taxBreakdown')}}{{$t('taxes.title')}}
{{$t('type')}} - {{$t('taxBase')}} - {{$t('tax')}}{{$t('fee')}}{{$t('taxes.theader.type')}}{{$t('taxes.theader.taxBase')}}{{$t('taxes.theader.tax')}}{{$t('taxes.theader.fee')}}
- - - + + +
- - - -
-
-

{{$t('route')}} {{route.id}}

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

Hora inicio

-
-

Hora fin

-
-

Km inicio

-
-

Km fin

-
-
- -
-
-
- -
-
-
-
-
-
- -
-
- - - - - - - - - - - - - - - - - - - -
{{$t('order')}}{{$t('ticket')}}{{$t('client')}}{{$t('address')}}{{$t('packages')}}
{{ticket.priority}}{{ticket.id}}{{ticket.clientFk}} {{ticket.addressName}} - {{ticket.addressFk.toString().substr(0, ticket.addressFk.toString().length - 3)}} - - {{ticket.addressFk.toString().substr(-3, 3)}} - - {{ticket.packages}}
-
+ + + + + - - -
+ + + +
+
+

{{$t('route')}} {{route.id}}

+
+
{{$t('information')}}
+
- - - - + + + + - - + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - +
{{$t('street')}}{{ticket.street}}{{$t('postcode')}}{{ticket.postalCode}}{{$t('route')}}{{route.id}}{{$t('driver')}}{{route.userNickName}}
{{$t('city')}}{{ticket.city}}{{$t('date')}}{{route.created | date('%d-%m-%Y')}}{{$t('vehicle')}}{{route.vehicleTradeMark}} {{route.vehicleModel}}
{{$t('time')}}{{route.time | date('%H:%M')}}{{route.plateNumber}}
{{$t('volume')}}{{route.m3}} {{$t('agency')}}{{ticket.ticketAgency}}
{{$t('mobile')}}{{ticket.mobile}}{{$t('phone')}}{{ticket.phone}}
{{$t('warehouse')}}{{ticket.warehouseName}}{{$t('salesPerson')}}{{ticket.salesPersonName}}
{{$t('import')}}{{ticket.import | currency('EUR', $i18n.locale)}}{{route.agencyName}}
-
-

{{ticket.description}}

-

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

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

Hora inicio

+
+

Hora fin

+
+

Km inicio

+
+

Km fin

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

{{ticket.description}}

+

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

+
+
+
- - - -
- +
+ + + +
+ \ No newline at end of file diff --git a/print/templates/reports/driver-route/driver-route.js b/print/templates/reports/driver-route/driver-route.js index 39b5d44e9f..0b26382393 100755 --- a/print/templates/reports/driver-route/driver-route.js +++ b/print/templates/reports/driver-route/driver-route.js @@ -30,7 +30,7 @@ module.exports = { return this.rawSqlFromDef('routes', [routesId]); }, fetchTickets(routesId) { - return this.rawSqlFromDef('tickets', [routesId]); + return this.rawSqlFromDef('tickets', [routesId, routesId]); } }, components: { diff --git a/print/templates/reports/driver-route/locale/es.yml b/print/templates/reports/driver-route/locale/es.yml index 7b86f527f9..4f0f3ac3c2 100644 --- a/print/templates/reports/driver-route/locale/es.yml +++ b/print/templates/reports/driver-route/locale/es.yml @@ -10,6 +10,7 @@ order: Orden client: Cliente address: Consignatario packages: Bultos +packagingType: Encajado street: Dirección postcode: Código Postal city: Ciudad diff --git a/print/templates/reports/driver-route/sql/tickets.sql b/print/templates/reports/driver-route/sql/tickets.sql index 1bdaf31a5c..8806a04739 100644 --- a/print/templates/reports/driver-route/sql/tickets.sql +++ b/print/templates/reports/driver-route/sql/tickets.sql @@ -18,8 +18,9 @@ SELECT am.name ticketAgency, tob.description, s.shipFk, - u.nickName salesPersonName -FROM route r + u.nickName salesPersonName, + ipkg.itemPackingTypes +FROM route r LEFT JOIN ticket t ON t.routeFk = r.id LEFT JOIN address a ON a.id = t.addressFk LEFT JOIN client c ON c.id = t.clientFk @@ -30,5 +31,15 @@ FROM route r LEFT JOIN warehouse wh ON wh.id = t.warehouseFk LEFT JOIN agencyMode am ON am.id = t.agencyModeFk LEFT JOIN stowaway s ON s.id = t.id -WHERE r.id IN(?) -ORDER BY t.priority, t.id \ No newline at end of file + LEFT JOIN ( + SELECT t.id AS ticketFk, + GROUP_CONCAT(DISTINCT(i.itemPackingTypeFk)) AS itemPackingTypes + FROM route r + JOIN ticket t ON t.routeFk = r.id + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + WHERE r.id IN (?) + GROUP BY t.id + ) ipkg ON ipkg.ticketFk = t.id +WHERE r.id IN (?) +ORDER BY t.priority, t.id; \ No newline at end of file diff --git a/print/templates/reports/entry-order/locale/en.yml b/print/templates/reports/entry-order/locale/en.yml deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/print/templates/reports/receipt/locale/en.yml b/print/templates/reports/receipt/locale/en.yml deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/print/templates/reports/receipt/receipt.html b/print/templates/reports/receipt/receipt.html index 3371e6871d..5dc1846f7e 100644 --- a/print/templates/reports/receipt/receipt.html +++ b/print/templates/reports/receipt/receipt.html @@ -21,7 +21,7 @@

{{$t('payed', [ - 'Silla', + 'Algemesí', receipt.payed.getDate(), $t('months')[receipt.payed.getMonth()], receipt.payed.getFullYear()]) diff --git a/print/templates/reports/receipt/sql/receipt.sql b/print/templates/reports/receipt/sql/receipt.sql index 9b39194958..b8f5a41124 100644 --- a/print/templates/reports/receipt/sql/receipt.sql +++ b/print/templates/reports/receipt/sql/receipt.sql @@ -1,9 +1,11 @@ SELECT r.id, r.amountPaid, - r.amountUnpaid, + cr.amount AS amountUnpaid, r.payed, r.companyFk FROM receipt r JOIN client c ON c.id = r.clientFk + JOIN vn.clientRisk cr ON cr.clientFk = c.id + AND cr.companyFk = r.companyFk WHERE r.id = ? \ No newline at end of file