diff --git a/.eslintrc.yml b/.eslintrc.yml index edbc47195..0d74348f2 100644 --- a/.eslintrc.yml +++ b/.eslintrc.yml @@ -36,3 +36,7 @@ rules: jasmine/no-focused-tests: 0 jasmine/prefer-toHaveBeenCalledWith: 0 arrow-spacing: ["error", { "before": true, "after": true }] + no-restricted-syntax: + - "error" + - selector: "NewExpression[callee.name='Date']" + message: "Use Date.vnNew() instead of new Date()." diff --git a/back/methods/collection/getSales.js b/back/methods/collection/getSales.js index a9e5f2e60..f3575672f 100644 --- a/back/methods/collection/getSales.js +++ b/back/methods/collection/getSales.js @@ -29,10 +29,8 @@ module.exports = Self => { }); Self.getSales = async(ctx, collectionOrTicketFk, print, source, options) => { - const models = Self.app.models; const userId = ctx.req.accessToken.userId; const myOptions = {userId}; - const $t = ctx.req.__; if (typeof options == 'object') Object.assign(myOptions, options); @@ -59,22 +57,6 @@ module.exports = Self => { if (print) await Self.rawSql('CALL vn.collection_printSticker(?,NULL)', [id], myOptions); - for (let ticket of tickets) { - if (ticket.observaciones) { - let observations = ticket.observaciones.split(' '); - - for (let observation of observations) { - const salesPerson = ticket.salesPersonFk; - if (observation.startsWith('#') || observation.startsWith('@')) { - await models.Chat.send(ctx, - observation, - $t('ticketCommercial', {ticket: ticket.ticketFk, salesPerson}) - ); - } - } - } - } - return getCollection(id, tickets, sales, placements, myOptions); }; diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js index 48301a366..3c2f6cb2d 100644 --- a/back/methods/collection/getTickets.js +++ b/back/methods/collection/getTickets.js @@ -57,10 +57,10 @@ module.exports = Self => { ROW_NUMBER () OVER (PARTITION BY s.id ORDER BY pickingOrder) currentItemShelving, COUNT(*) OVER (PARTITION BY s.id ORDER BY s.id) totalItemShelving, sh.code, - p2.code parkingCode, - p2.pickingOrder pickingOrder, - p.code parkingCodePrevia, - p.pickingOrder pickingOrderPrevia, + p2.code parkingCodePrevia, + p2.pickingOrder pickingOrderPrevia, + p.code parkingCode, + p.pickingOrder pickingOrder, iss.id itemShelvingSaleFk, iss.isPicked, iss.itemShelvingFk @@ -73,7 +73,7 @@ module.exports = Self => { JOIN item i ON i.id = s.itemFk JOIN itemShelvingSale iss ON iss.saleFk = s.id LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk - LEFT JOIN shelving sh ON sh.code = ish.shelvingFk + LEFT JOIN shelving sh ON sh.id = ish.shelvingFk LEFT JOIN parking p ON p.id = sh.parkingFk LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk LEFT JOIN origin o ON o.id = i.originFk @@ -114,7 +114,7 @@ module.exports = Self => { JOIN item i ON i.id = s.itemFk JOIN itemShelvingSale iss ON iss.saleFk = s.id LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk - LEFT JOIN shelving sh ON sh.code = ish.shelvingFk + LEFT JOIN shelving sh ON sh.id = ish.shelvingFk LEFT JOIN parking p ON p.id = sh.parkingFk LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk LEFT JOIN origin o ON o.id = i.originFk diff --git a/back/methods/collection/spec/assign.spec.js b/back/methods/collection/spec/assign.spec.js index 745343819..b00631d22 100644 --- a/back/methods/collection/spec/assign.spec.js +++ b/back/methods/collection/spec/assign.spec.js @@ -28,9 +28,10 @@ describe('ticket assign()', () => { await tx.rollback(); }); - it('should throw an error when there is not picking tickets', async() => { + it('should throw an error when there are no picking tickets', async() => { try { await models.Collection.assign(ctx, options); + fail('Expected an error to be thrown, but none was thrown.'); } catch (e) { expect(e.message).toEqual('There are not picking tickets'); } diff --git a/back/methods/mrw-config/cancelShipment.js b/back/methods/mrw-config/cancelShipment.js index 56d206529..98aa8be39 100644 --- a/back/methods/mrw-config/cancelShipment.js +++ b/back/methods/mrw-config/cancelShipment.js @@ -39,6 +39,9 @@ module.exports = Self => { const xmlString = response.data; const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlString, 'text/xml'); + + await Self.rawSql('CALL util.debugAdd(?,?);', ['cancelShipment', xmlDoc]); + const result = xmlDoc.getElementsByTagName('Mensaje')[0].textContent; return result.toLowerCase().includes('se ha cancelado correctamente'); }; diff --git a/back/methods/workerActivity/add.js b/back/methods/workerActivity/add.js index 4592a0797..89131491d 100644 --- a/back/methods/workerActivity/add.js +++ b/back/methods/workerActivity/add.js @@ -31,7 +31,7 @@ module.exports = Self => { return await Self.rawSql(` INSERT INTO workerActivity (workerFk, workerActivityTypeFk, model) SELECT ?, ?, ? - FROM workerTimeControlParams wtcp + FROM workerTimeControlConfig wtcc LEFT JOIN ( SELECT wa.workerFk, wa.created, @@ -44,7 +44,7 @@ module.exports = Self => { ) sub ON TRUE WHERE sub.workerFk IS NULL OR sub.code <> ? - OR TIMESTAMPDIFF(SECOND, sub.created, util.VN_NOW()) > wtcp.dayBreak;` + OR TIMESTAMPDIFF(SECOND, sub.created, util.VN_NOW()) > wtcc.dayBreak;` , [userId, code, model, userId, code], myOptions); }; }; diff --git a/back/model-config.json b/back/model-config.json index 5368769fd..b543071c9 100644 --- a/back/model-config.json +++ b/back/model-config.json @@ -79,6 +79,9 @@ "ImageCollectionSize": { "dataSource": "vn" }, + "ImageConfig": { + "dataSource": "vn" + }, "ImageContainer": { "dataSource": "imageStorage" }, @@ -139,6 +142,12 @@ "StarredModule": { "dataSource": "vn" }, + "SaySimpleCountry": { + "dataSource": "vn" + }, + "SaySimpleConfig": { + "dataSource": "vn" + }, "TempContainer": { "dataSource": "tempStorage" }, diff --git a/back/models/country.json b/back/models/country.json index 80d456702..ee72ae49d 100644 --- a/back/models/country.json +++ b/back/models/country.json @@ -44,6 +44,11 @@ "type": "belongsTo", "model": "Continent", "foreignKey": "continentFk" + }, + "saySimpleCountry": { + "type": "hasOne", + "model": "SaySimpleCountry", + "foreignKey": "countryFk" } }, "acls": [ @@ -54,4 +59,4 @@ "permission": "ALLOW" } ] -} +} \ No newline at end of file diff --git a/back/models/image-config.json b/back/models/image-config.json new file mode 100644 index 000000000..11f4c2284 --- /dev/null +++ b/back/models/image-config.json @@ -0,0 +1,22 @@ +{ + "name": "ImageConfig", + "base": "VnModel", + "options": { + "mysql": { + "table": "hedera.imageConfig" + } + }, + "properties": { + "url": { + "type": "string" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$authenticated", + "permission": "ALLOW" + } + ] +} \ No newline at end of file diff --git a/back/models/say-simple-config.json b/back/models/say-simple-config.json new file mode 100644 index 000000000..d5d4f8a6f --- /dev/null +++ b/back/models/say-simple-config.json @@ -0,0 +1,29 @@ +{ + "name": "SaySimpleConfig", + "base": "VnModel", + "options": { + "mysql": { + "table": "saySimpleConfig" + } + }, + "properties": { + "id": { + "type": "number", + "id": true + }, + "url": { + "type": "string" + }, + "defaultChannel": { + "type": "number" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$authenticated", + "permission": "ALLOW" + } + ] +} \ No newline at end of file diff --git a/back/models/say-simple-country.json b/back/models/say-simple-country.json new file mode 100644 index 000000000..adddddc02 --- /dev/null +++ b/back/models/say-simple-country.json @@ -0,0 +1,26 @@ +{ + "name": "SaySimpleCountry", + "base": "VnModel", + "options": { + "mysql": { + "table": "saySimpleCountry" + } + }, + "properties": { + "countryFk": { + "type": "number", + "id": true + }, + "channel": { + "type": "number" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$authenticated", + "permission": "ALLOW" + } + ] +} \ No newline at end of file diff --git a/db/dump/.dump/data.sql b/db/dump/.dump/data.sql index 5f464c5e2..6bcfe2c9f 100644 --- a/db/dump/.dump/data.sql +++ b/db/dump/.dump/data.sql @@ -4,7 +4,7 @@ USE `util`; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -INSERT INTO `version` VALUES ('vn-database','11278','fe10f03459a153fc213bf64e352804c043f94590','2024-10-03 07:47:47','11281'); +INSERT INTO `version` VALUES ('vn-database','11311','315864403260623fede9f0471ef3d9036faf23b1','2024-11-12 08:00:59','11336'); INSERT INTO `versionLog` VALUES ('vn-database','10107','00-firstScript.sql','jenkins@10.0.2.69','2022-04-23 10:53:53',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10112','00-firstScript.sql','jenkins@10.0.2.69','2022-05-09 09:14:53',NULL,NULL); @@ -988,6 +988,7 @@ INSERT INTO `versionLog` VALUES ('vn-database','11194','00-firstScript.sql','jen INSERT INTO `versionLog` VALUES ('vn-database','11195','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-03 08:58:01',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11196','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-18 07:28:14',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11197','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-03 08:58:01',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11198','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 07:42:49',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11201','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-08-27 13:04:26',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11204','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-03 08:58:01',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11205','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-04 13:54:55',NULL,NULL); @@ -1013,6 +1014,7 @@ INSERT INTO `versionLog` VALUES ('vn-database','11225','01-firstScript.sql','jen INSERT INTO `versionLog` VALUES ('vn-database','11225','02-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:41',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11227','00-addWorkerTimeControlMailAcl.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:41',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11229','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-16 08:24:17',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11230','00-addClientObservationType.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 07:42:52',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11234','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:42',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11235','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11236','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL); @@ -1021,18 +1023,53 @@ INSERT INTO `versionLog` VALUES ('vn-database','11237','00-firstScript.sql','jen INSERT INTO `versionLog` VALUES ('vn-database','11239','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-17 12:57:06',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11240','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11241','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-20 09:08:25',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11242','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 07:42:52',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11246','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-18 12:39:53',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11247','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-19 12:10:08',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11248','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-23 11:12:17',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11249','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11251','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 07:43:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11251','01-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 07:57:30',NULL,'Connection lost: The server closed the connection.'); INSERT INTO `versionLog` VALUES ('vn-database','11253','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-20 14:41:27',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11254','00-thermographTemperature.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:13',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11254','01-thermographFk.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:15',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11255','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11256','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-09-23 12:18:24',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11258','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:15',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11260','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:15',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11261','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:15',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11262','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11263','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-09-27 12:05:32',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11264','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:15',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11271','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:15',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11272','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:15',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11273','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 10:50:51',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11274','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:16',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11274','00-firstScript2.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:29',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11274','00-firstScript3.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:30',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11274','00-firstScript5.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:35',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11274','00-firstScript6.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:35',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11274','00-firstScript7.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:36',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11277','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:36',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11278','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-03 07:47:43',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11279','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-10-02 08:05:24',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11280','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-02 08:46:50',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11281','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:36',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11283','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:36',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11284','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:36',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11285','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:37',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11287','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:37',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11288','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-10 08:26:34',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11289','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-15 07:01:33',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11290','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:37',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11291','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-17 09:10:30',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11294','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:37',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11295','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-10 08:45:13',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11298','00-closure.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:37',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11300','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-18 08:27:05',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11302','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:57',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11308','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-10-23 12:41:55',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11311','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-11-12 08:00:57',NULL,NULL); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; @@ -1407,6 +1444,8 @@ INSERT INTO `roleInherit` VALUES (376,124,21,19336); INSERT INTO `roleInherit` VALUES (377,47,49,19295); INSERT INTO `roleInherit` VALUES (378,101,15,19294); INSERT INTO `roleInherit` VALUES (379,103,121,19294); +INSERT INTO `roleInherit` VALUES (381,119,123,19295); +INSERT INTO `roleInherit` VALUES (382,48,72,783); INSERT INTO `userPassword` VALUES (1,7,1,0,2,1); @@ -2045,7 +2084,7 @@ INSERT INTO `ACL` VALUES (756,'Route','findOne','READ','ALLOW','ROLE','employee' INSERT INTO `ACL` VALUES (757,'Route','getRoutesByWorker','READ','ALLOW','ROLE','employee',NULL); INSERT INTO `ACL` VALUES (758,'Route','canViewAllRoute','READ','ALLOW','ROLE','deliveryAssistant',NULL); INSERT INTO `ACL` VALUES (759,'Route','cmr','READ','ALLOW','ROLE','employee',NULL); -INSERT INTO `ACL` VALUES (760,'Route','downloadCmrsZip','READ','ALLOW','ROLE','employee',NULL); +INSERT INTO `ACL` VALUES (760,'Cmr','downloadZip','READ','ALLOW','ROLE','employee',NULL); INSERT INTO `ACL` VALUES (761,'Route','downloadZip','READ','ALLOW','ROLE','employee',NULL); INSERT INTO `ACL` VALUES (762,'Route','filter','READ','ALLOW','ROLE','employee',NULL); INSERT INTO `ACL` VALUES (763,'Route','getByWorker','READ','ALLOW','ROLE','employee',NULL); @@ -2174,7 +2213,6 @@ INSERT INTO `ACL` VALUES (892,'WorkerIncome','*','*','ALLOW','ROLE','hr',NULL); INSERT INTO `ACL` VALUES (893,'PayrollComponent','*','*','ALLOW','ROLE','hr',NULL); INSERT INTO `ACL` VALUES (894,'Worker','__get__incomes','*','ALLOW','ROLE','hr',NULL); INSERT INTO `ACL` VALUES (895,'ItemShelvingLog','*','READ','ALLOW','ROLE','production',NULL); -INSERT INTO `ACL` VALUES (897,'WorkerLog','*','READ','ALLOW','ROLE','employee',NULL); INSERT INTO `ACL` VALUES (901,'WorkerTimeControl','sendMail','WRITE','ALLOW','ROLE','system',NULL); INSERT INTO `ACL` VALUES (902,'Entry','filter','READ','ALLOW','ROLE','supplier',NULL); INSERT INTO `ACL` VALUES (903,'Entry','getBuys','READ','ALLOW','ROLE','supplier',NULL); @@ -2190,7 +2228,6 @@ INSERT INTO `ACL` VALUES (912,'Worker','__get__medicalReview','*','ALLOW','ROLE' INSERT INTO `ACL` VALUES (913,'VnToken','*','READ','ALLOW','ROLE','developer',10578); INSERT INTO `ACL` VALUES (914,'VnToken','killSession','*','ALLOW','ROLE','developer',10578); INSERT INTO `ACL` VALUES (915,'ACL','*','WRITE','ALLOW','ROLE','developerBoss',10578); -INSERT INTO `ACL` VALUES (916,'Entry','getBuysCsv','READ','ALLOW','ROLE','supplier',10578); INSERT INTO `ACL` VALUES (917,'InvoiceOut','refundAndInvoice','WRITE','ALLOW','ROLE','administrative',10578); INSERT INTO `ACL` VALUES (918,'Worker','__get__descriptor','READ','ALLOW','ROLE','employee',10578); INSERT INTO `ACL` VALUES (919,'Worker','findById','READ','ALLOW','ROLE','employee',10578); @@ -2212,6 +2249,7 @@ INSERT INTO `ACL` VALUES (935,'BankEntity','*','WRITE','ALLOW','ROLE','financial INSERT INTO `ACL` VALUES (936,'Device','handleUser','*','ALLOW','ROLE','employee',10578); INSERT INTO `ACL` VALUES (937,'WorkerTimeControlMail','count','READ','ALLOW','ROLE','employee',10578); INSERT INTO `ACL` VALUES (938,'Worker','__get__mail','READ','ALLOW','ROLE','hr',10578); +INSERT INTO `ACL` VALUES (939,'Machine','*','*','ALLOW','ROLE','productionBoss',10578); INSERT INTO `fieldAcl` VALUES (1,'Client','name','update','employee'); INSERT INTO `fieldAcl` VALUES (2,'Client','contact','update','employee'); @@ -2407,6 +2445,8 @@ INSERT INTO `claimResponsible` VALUES (22,'Paletizadores',0,'pal'); INSERT INTO `claimResponsible` VALUES (23,'Preparación Previa',0,'pre'); INSERT INTO `claimResponsible` VALUES (24,'Almacén PCA',0,'war'); INSERT INTO `claimResponsible` VALUES (25,'Huelga',0,'str'); +INSERT INTO `claimResponsible` VALUES (27,'Prep. por caja',0,''); +INSERT INTO `claimResponsible` VALUES (45,'Negativo',0,'neg'); INSERT INTO `claimReason` VALUES (1,'Prisas',0); INSERT INTO `claimReason` VALUES (2,'Novato',0); @@ -2449,6 +2489,9 @@ INSERT INTO `claimReason` VALUES (52,'Mala gestión comercial',0); INSERT INTO `claimReason` VALUES (53,'Mala gestión comprador',0); INSERT INTO `claimReason` VALUES (54,'A2',0); INSERT INTO `claimReason` VALUES (55,'Entrega 48h o más',0); +INSERT INTO `claimReason` VALUES (56,'Error cliente',0); +INSERT INTO `claimReason` VALUES (57,'A2/B1',0); +INSERT INTO `claimReason` VALUES (58,'Seguro',0); INSERT INTO `claimRedelivery` VALUES (1,'Cliente'); INSERT INTO `claimRedelivery` VALUES (2,'No dev./No especif.'); @@ -2456,6 +2499,7 @@ INSERT INTO `claimRedelivery` VALUES (3,'Reparto'); INSERT INTO `claimRedelivery` VALUES (4,'Agencia'); INSERT INTO `claimRedelivery` VALUES (5,'Tour'); INSERT INTO `claimRedelivery` VALUES (6,'Fuera Peninsula'); +INSERT INTO `claimRedelivery` VALUES (7,'Francia'); INSERT INTO `claimResult` VALUES (1,'Otros daños'); INSERT INTO `claimResult` VALUES (2,'Roces'); @@ -2533,39 +2577,39 @@ INSERT INTO `continent` VALUES (3,'África','AF'); INSERT INTO `continent` VALUES (4,'Europa','EU'); INSERT INTO `continent` VALUES (5,'Oceanía','OC'); -INSERT INTO `department` VALUES (1,'VN','VERDNATURA',1,114,763,0,0,0,0,26,NULL,'/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (1,'VN','VERDNATURA',1,116,763,0,0,0,0,26,NULL,'/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (22,'shopping','COMPRAS',2,5,NULL,72,0,0,1,1,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (23,'CMA','CAMARA',15,16,NULL,72,1,1,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,1,NULL,NULL,NULL,'PREVIOUS'); -INSERT INTO `department` VALUES (31,'it','INFORMATICA',6,7,NULL,72,0,0,1,0,1,'/1/','informatica-cau',1,NULL,1,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (34,'accounting','CONTABILIDAD',8,9,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (35,'finance','FINANZAS',10,11,NULL,0,0,0,1,0,1,'/1/',NULL,1,'begonya@verdnatura.es',1,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (36,'labor','LABORAL',12,13,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (31,'it','INFORMATICA',6,7,NULL,72,0,0,1,0,1,'/1/','informatica-cau',1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (34,'accounting','CONTABILIDAD',8,9,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (35,'finance','FINANZAS',10,11,NULL,0,0,0,1,0,1,'/1/',NULL,1,'begonya@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (36,'labor','LABORAL',12,13,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (37,'PROD','PRODUCCION',14,37,NULL,72,1,1,1,11,1,'/1/',NULL,0,NULL,0,1,1,1,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (38,'picking','SACADO',17,18,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,'ON_PREPARATION'); +INSERT INTO `department` VALUES (38,'picking','SACADO',17,18,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,0,1,NULL,NULL,NULL,'ON_PREPARATION'); INSERT INTO `department` VALUES (39,'packing','ENCAJADO',19,20,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,'PACKING'); -INSERT INTO `department` VALUES (41,'administration','ADMINISTRACION',38,39,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (43,'VT','VENTAS',40,73,NULL,0,0,0,1,16,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (44,'management','GERENCIA',74,75,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (45,'logistic','LOGISTICA',76,77,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (46,'delivery','REPARTO',78,79,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,'DELIVERY'); -INSERT INTO `department` VALUES (48,'storage','ALMACENAJE',80,81,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,'STORAGE'); -INSERT INTO `department` VALUES (49,NULL,'PROPIEDAD',82,83,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (52,NULL,'CARGA AEREA',84,85,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (53,'marketing','MARKETING Y COMUNICACIÓN',41,42,NULL,72,0,0,2,0,43,'/1/43/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (54,NULL,'ORNAMENTALES',86,87,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (41,'administration','ADMINISTRACION',38,39,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (43,'VT','VENTAS',40,75,NULL,0,0,0,1,17,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (44,'management','GERENCIA',76,77,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (45,'logistic','LOGISTICA',78,79,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (46,'delivery','REPARTO',80,81,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,'DELIVERY'); +INSERT INTO `department` VALUES (48,'storage','ALMACENAJE',82,83,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,'STORAGE'); +INSERT INTO `department` VALUES (49,NULL,'PROPIEDAD',84,85,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (52,NULL,'CARGA AEREA',86,87,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (53,'marketing','MARKETING Y COMUNICACIÓN',41,42,NULL,72,0,0,2,0,43,'/1/43/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (54,NULL,'ORNAMENTALES',88,89,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (55,NULL,'TALLER NATURAL',21,22,14548,72,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,0,1118,NULL,NULL,NULL); INSERT INTO `department` VALUES (56,NULL,'TALLER ARTIFICIAL',23,24,8470,72,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,0,1927,NULL,NULL,NULL); -INSERT INTO `department` VALUES (58,'CMP','CAMPOS',88,91,NULL,72,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,'FIELD'); -INSERT INTO `department` VALUES (59,'maintenance','MANTENIMIENTO',92,93,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (60,'claims','RECLAMACIONES',43,44,NULL,72,0,0,2,0,43,'/1/43/',NULL,0,NULL,1,1,0,0,NULL,NULL,NULL,'CLAIM'); -INSERT INTO `department` VALUES (61,NULL,'VNH',94,97,NULL,73,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (66,NULL,'VERDNAMADRID',98,99,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (58,'CMP','CAMPOS',90,93,NULL,72,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,'FIELD'); +INSERT INTO `department` VALUES (59,'maintenance','MANTENIMIENTO',94,95,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (60,'claims','RECLAMACIONES',43,44,NULL,72,0,0,2,0,43,'/1/43/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,'CLAIM'); +INSERT INTO `department` VALUES (61,NULL,'VNH',96,99,NULL,73,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (66,NULL,'VERDNAMADRID',100,101,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (68,NULL,'COMPLEMENTOS',25,26,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (69,NULL,'VERDNABARNA',100,101,NULL,74,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (69,NULL,'VERDNABARNA',102,103,NULL,74,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (80,'spainTeam5','EQUIPO ESPAÑA 5',45,46,4250,0,0,0,2,0,43,'/1/43/','es5_equipo',1,'es5@verdnatura.es',0,0,0,0,NULL,NULL,'5300',NULL); -INSERT INTO `department` VALUES (86,NULL,'LIMPIEZA',102,103,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (89,NULL,'COORDINACION',104,105,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (90,NULL,'TRAILER',95,96,NULL,0,0,0,2,0,61,'/1/61/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (86,NULL,'LIMPIEZA',104,105,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (89,NULL,'COORDINACION',106,107,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (90,NULL,'TRAILER',97,98,NULL,0,0,0,2,0,61,'/1/61/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (91,'artificial','ARTIFICIAL',27,28,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,'PREVIOUS'); INSERT INTO `department` VALUES (92,NULL,'EQUIPO SILVERIO',47,48,1203,0,0,0,2,0,43,'/1/43/','sdc_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (94,'spainTeam2','EQUIPO ESPAÑA 2',49,50,3797,0,0,0,2,0,43,'/1/43/','es2_equipo',1,'es2@verdnatura.es',0,0,0,0,NULL,NULL,'5100',NULL); @@ -2573,23 +2617,24 @@ INSERT INTO `department` VALUES (95,'spainTeam1','EQUIPO ESPAÑA 1',51,52,24065, INSERT INTO `department` VALUES (96,NULL,'EQUIPO C LOPEZ',53,54,4661,0,0,0,2,0,43,'/1/43/','cla_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (115,NULL,'EQUIPO CLAUDI',55,56,3810,0,0,0,2,0,43,'/1/43/','csr_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (123,NULL,'EQUIPO ELENA BASCUÑANA',57,58,7102,0,0,0,2,0,43,'/1/43/','ebt_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (124,NULL,'CONTROL INTERNO',106,107,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,1,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (124,NULL,'CONTROL INTERNO',108,109,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (125,'spainTeam3','EQUIPO ESPAÑA 3',59,60,1118,0,0,0,2,0,43,'/1/43/','es3_equipo',1,'es3@verdnatura.es',0,0,0,0,NULL,NULL,'5200',NULL); INSERT INTO `department` VALUES (126,NULL,'PRESERVADO',29,30,NULL,0,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (128,NULL,'PALETIZADO',31,32,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,'PALLETIZING'); INSERT INTO `department` VALUES (130,NULL,'REVISION',33,34,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,'ON_CHECKING'); -INSERT INTO `department` VALUES (131,'greenhouse','INVERNADERO',89,90,NULL,0,0,0,2,0,58,'/1/58/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (131,'greenhouse','INVERNADERO',91,92,NULL,0,0,0,2,0,58,'/1/58/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (132,NULL,'EQUIPO DC',61,62,1731,0,0,0,2,0,43,'/1/43/','dc_equipo',1,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (133,'franceTeam','EQUIPO FRANCIA',63,64,1731,72,0,0,2,0,43,'/1/43/','fr_equipo',1,'gestionfrancia@verdnatura.es',0,0,0,0,NULL,NULL,'3300',NULL); INSERT INTO `department` VALUES (134,'portugalTeam','EQUIPO PORTUGAL',65,66,6264,0,0,0,2,0,43,'/1/43/','pt_equipo',1,'portugal@verdnatura.es',0,0,0,0,NULL,NULL,'3500',NULL); -INSERT INTO `department` VALUES (135,'routers','ENRUTADORES',108,109,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (136,'heavyVehicles','VEHICULOS PESADOS',110,111,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (137,'sorter','SORTER',112,113,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (135,'routers','ENRUTADORES',110,111,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (136,'heavyVehicles','VEHICULOS PESADOS',112,113,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (137,'sorter','SORTER',114,115,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (139,'spainTeam4','EQUIPO ESPAÑA 4',67,68,3803,0,0,0,2,0,43,'/1/43/','es4_equipo',1,'es4@verdnatura.es',0,0,0,0,NULL,NULL,'5400',NULL); -INSERT INTO `department` VALUES (140,'hollandTeam','EQUIPO HOLANDA',69,70,NULL,0,0,0,2,0,43,'/1/43/','nl_equipo',1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (140,'internationalTeam','EQUIPO INTERNACIONAL',69,70,33320,0,0,0,2,0,43,'/1/43/','int_equipo',1,'international@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (141,NULL,'PREVIA',35,36,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,'PREVIOUS'); INSERT INTO `department` VALUES (146,NULL,'VERDNACOLOMBIA',3,4,NULL,72,0,0,2,0,22,'/1/22/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (147,'spainTeamAsia','EQUIPO ESPAÑA ASIA',71,72,40214,0,0,0,2,0,43,'/1/43/','esA_equipo',0,'esA@verdnatura.es',0,0,0,0,NULL,NULL,'5500',NULL); +INSERT INTO `department` VALUES (148,NULL,'CAPTATION FRANCIA',73,74,NULL,0,0,0,2,0,43,'/1/43/',NULL,0,NULL,0,0,0,0,NULL,NULL,'6000',NULL); INSERT INTO `docuware` VALUES (1,'deliveryNote','Albaranes cliente','find','find','N__ALBAR_N',NULL); INSERT INTO `docuware` VALUES (2,'deliveryNote','Albaranes cliente','store','Archivar','N__ALBAR_N',NULL); diff --git a/db/dump/.dump/privileges.sql b/db/dump/.dump/privileges.sql index 66e553763..486bec661 100644 --- a/db/dump/.dump/privileges.sql +++ b/db/dump/.dump/privileges.sql @@ -502,7 +502,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','receipt','alexm@%','0000- INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','grafana','visitUser','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','referenceRate','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','report','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','cache','productionBoss','available','guillermo@10.5.1.2','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyerAssistant','producer','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','time','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','role','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','config__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); @@ -605,7 +605,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','project','jua INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','productionConfig','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','manager','productionConfig','alexm@%','0000-00-00 00:00:00','Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','creditInsurance','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','cache','productionBoss','visible','guillermo@10.5.1.2','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','errorProduction__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','invoiceOut','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','coolerAssist','Tickets','alexm@%','0000-00-00 00:00:00','Update',''); @@ -792,7 +791,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hr','Movimientos','alexm@% INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerAssist','buy','alexm@%','0000-00-00 00:00:00','Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','itemMinimumQuantity','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','receipt','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Insert',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyerBoss','producer','alexm@%','0000-00-00 00:00:00','Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','link','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hr','link','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','delivery','vehicle','alexm@%','0000-00-00 00:00:00','Select',''); @@ -971,7 +969,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','officeBoss','ticketPackagingSt INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerRelatives','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','ticketPackagingStartingStock','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','supplierPackaging','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerDocument','alexm@%','0000-00-00 00:00:00','Select,Insert',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','supplierContact','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceCorrection','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ink','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','zone','alexm@%','0000-00-00 00:00:00','Select',''); @@ -1471,9 +1469,31 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','tillSerial',' INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','stockBuyed','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','alertLevel','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','workerActivityType','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','priceDelta','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','priceDelta','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','parkingLog','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','travelLog','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','supplierContact','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerDms','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','itemLog','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','account','developer','user','juan@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','claimReason','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','claimResponsible','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','claimResult','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','claimRedelivery','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','producer','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','itemStateTag','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','material','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','saleUnit','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','origin','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','itemType','jgallego@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','delivery','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','itemFarmingTag','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','itemWrappingTag','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','itemLanguageTag','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','itemStemTag','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','itemBaseTag','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','itemBreederTag','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','itemShelvingLog','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); /*!40000 ALTER TABLE `tables_priv` ENABLE KEYS */; /*!40000 ALTER TABLE `columns_priv` DISABLE KEYS */; @@ -1853,7 +1873,6 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','claimManager','buy_getVolumeByE INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','buy_getVolumeByEntry','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','entry_moveNotPrinted','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','buy_getVolume','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','stockbuyedbyworker','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','buy_getsplit','PROCEDURE','juan@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','subordinategetlist','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','buy_afterUpsert','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); @@ -2001,7 +2020,6 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','logshow','PROCEDURE','alex INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyerBoss','supplierpackaging_reportsource','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','financialBoss','supplierexpenses','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','grafana','firstdayofweek','FUNCTION','juan@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','stockbuyed_add','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','mail_insert','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','duaParcialMake','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','palletizerBoss','packingsite_startcollection','PROCEDURE','alexm@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00'); @@ -2211,7 +2229,10 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','guest','ticketCalculatePurge',' INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','buy_getUltimate','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','cooler','buy_getUltimate','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','bs','buyerBoss','waste_addSales','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','bs','grafana','waste_addSales','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); +INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','saletracking_sectorcollectionaddprevok','PROCEDURE','alexm@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); +INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','saleSplit','PROCEDURE','carlosap@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); +INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemShelvingSale_deleteAdded','PROCEDURE','guillermo@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); +INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','buy_getUltimate','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); /*!40000 ALTER TABLE `procs_priv` ENABLE KEYS */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; diff --git a/db/dump/.dump/structure.sql b/db/dump/.dump/structure.sql index 0bd03ac32..e6c0e6674 100644 --- a/db/dump/.dump/structure.sql +++ b/db/dump/.dump/structure.sql @@ -416,7 +416,7 @@ CREATE TABLE `user` ( `role` int(10) unsigned NOT NULL DEFAULT 2, `active` tinyint(1) NOT NULL DEFAULT 1, `email` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, - `emailVerified` tinyint(1) DEFAULT NULL, + `emailVerified` tinyint(1) NOT NULL DEFAULT 0, `verificationToken` varchar(512) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, `lang` char(2) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, `lastPassChange` datetime DEFAULT NULL, @@ -2955,55 +2955,55 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `analisis_ventas_update`() -BEGIN - DECLARE vLastMonth DATE; - - SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, util.VN_CURDATE())); - - DELETE FROM analisis_ventas - WHERE Año > YEAR(vLastMonth) - OR (Año = YEAR(vLastMonth) AND Mes >= MONTH(vLastMonth)); - - INSERT INTO analisis_ventas ( - Familia, - Reino, - Comercial, - Comprador, - Provincia, - almacen, - Año, - Mes, - Semana, - Vista, - Importe - ) - SELECT - it.name, - ic.name, - w.code, - w2.code, - p.name, - wa.name, - tm.year, - tm.month, - tm.week, - dm.description, - bt.importe - FROM bs.ventas bt - LEFT JOIN vn.itemType it ON it.id = bt.tipo_id - LEFT JOIN vn.itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN vn.client c on c.id = bt.Id_Cliente - LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.worker w2 ON w2.id = it.workerFk - JOIN vn.time tm ON tm.dated = bt.fecha - JOIN vn.sale s ON s.id = bt.Id_Movimiento - LEFT JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.agencyMode am ON am.id = t.agencyModeFk - LEFT JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk - LEFT JOIN vn.address a ON a.id = t.addressFk - LEFT JOIN vn.province p ON p.id = a.provinceFk - LEFT JOIN vn.warehouse wa ON wa.id = t.warehouseFk - WHERE bt.fecha >= vLastMonth AND ic.merchandise; +BEGIN + DECLARE vLastMonth DATE; + + SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, util.VN_CURDATE())); + + DELETE FROM analisis_ventas + WHERE Año > YEAR(vLastMonth) + OR (Año = YEAR(vLastMonth) AND Mes >= MONTH(vLastMonth)); + + INSERT INTO analisis_ventas ( + Familia, + Reino, + Comercial, + Comprador, + Provincia, + almacen, + Año, + Mes, + Semana, + Vista, + Importe + ) + SELECT + it.name, + ic.name, + w.code, + w2.code, + p.name, + wa.name, + tm.year, + tm.month, + tm.week, + dm.description, + bt.importe + FROM bs.ventas bt + LEFT JOIN vn.itemType it ON it.id = bt.tipo_id + LEFT JOIN vn.itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN vn.client c on c.id = bt.Id_Cliente + LEFT JOIN vn.worker w ON w.id = c.salesPersonFk + LEFT JOIN vn.worker w2 ON w2.id = it.workerFk + JOIN vn.time tm ON tm.dated = bt.fecha + JOIN vn.sale s ON s.id = bt.Id_Movimiento + LEFT JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.agencyMode am ON am.id = t.agencyModeFk + LEFT JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk + LEFT JOIN vn.address a ON a.id = t.addressFk + LEFT JOIN vn.province p ON p.id = a.provinceFk + LEFT JOIN vn.warehouse wa ON wa.id = t.warehouseFk + WHERE bt.fecha >= vLastMonth AND ic.merchandise; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3021,21 +3021,21 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`() -BEGIN - DECLARE vDateShort DATETIME; - DECLARE vDateLong DATETIME; - DECLARE vOneYearAgo DATETIME; - - SET vDateShort = TIMESTAMPADD(MONTH, -2, util.VN_CURDATE()); - SET vDateLong = TIMESTAMPADD(MONTH, -18,util.VN_CURDATE()); - SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,util.VN_CURDATE()); - - DELETE FROM bi.Greuge_Evolution - WHERE (Fecha < vDateShort AND weekday(Fecha) != 1) - OR Fecha < vOneYearAgo; - - DELETE FROM bi.defaulters WHERE `date` < vDateLong; - DELETE FROM bi.defaulting WHERE `date` < vDateLong; +BEGIN + DECLARE vDateShort DATETIME; + DECLARE vDateLong DATETIME; + DECLARE vOneYearAgo DATETIME; + + SET vDateShort = TIMESTAMPADD(MONTH, -2, util.VN_CURDATE()); + SET vDateLong = TIMESTAMPADD(MONTH, -18,util.VN_CURDATE()); + SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,util.VN_CURDATE()); + + DELETE FROM bi.Greuge_Evolution + WHERE (Fecha < vDateShort AND weekday(Fecha) != 1) + OR Fecha < vOneYearAgo; + + DELETE FROM bi.defaulters WHERE `date` < vDateLong; + DELETE FROM bi.defaulting WHERE `date` < vDateLong; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3224,18 +3224,18 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `facturacion_media_anual_update`() -BEGIN - TRUNCATE TABLE bs.clientAnnualConsumption; - - REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo) - SELECT clientFk, avg(Facturacion) - FROM ( - SELECT clientFk, YEAR(issued) year, MONTH(issued) month, sum(amount) as Facturacion - FROM vn.invoiceOut - WHERE issued BETWEEN TIMESTAMPADD(YEAR,-1,util.VN_CURDATE()) AND TIMESTAMPADD(DAY, - DAY(util.VN_CURDATE()),util.VN_CURDATE()) - GROUP BY clientFk, year, month - ) vol - GROUP BY clientFk; +BEGIN + TRUNCATE TABLE bs.clientAnnualConsumption; + + REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo) + SELECT clientFk, avg(Facturacion) + FROM ( + SELECT clientFk, YEAR(issued) year, MONTH(issued) month, sum(amount) as Facturacion + FROM vn.invoiceOut + WHERE issued BETWEEN TIMESTAMPADD(YEAR,-1,util.VN_CURDATE()) AND TIMESTAMPADD(DAY, - DAY(util.VN_CURDATE()),util.VN_CURDATE()) + GROUP BY clientFk, year, month + ) vol + GROUP BY clientFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3815,7 +3815,7 @@ CREATE TABLE `defaulter` ( `created` date NOT NULL, `amount` double NOT NULL DEFAULT 0, `defaulterSinced` date DEFAULT NULL, - `hasChanged` tinyint(1) DEFAULT NULL, + `hasChanged` tinyint(1) NOT NULL DEFAULT 0, `frozened` date DEFAULT NULL, PRIMARY KEY (`clientFk`,`created`), KEY `client` (`clientFk`), @@ -4516,29 +4516,29 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `carteras_add`() -BEGIN -/** - * Inserta en la tabla @bs.carteras las ventas desde el año pasado - * agrupadas por trabajador, año y mes - */ - DECLARE vYear INT DEFAULT YEAR(util.VN_CURDATE()) - 1; - - DELETE FROM bs.carteras WHERE Año >= vYear; - - CALL util.time_generate( - MAKEDATE(vYear, 1), - (SELECT MAX(fecha) FROM ventas) - ); - - INSERT INTO carteras(Año, Mes , CodigoTrabajador, Peso) - SELECT t.`year`, t.`month`, w.code, SUM(v.importe) - FROM tmp.time t - JOIN ventas v on t.dated = v.fecha - JOIN vn.client c on c.id = v.Id_Cliente - JOIN vn.worker w ON w.id = c.salesPersonFk - GROUP BY w.code, t.`year`, t.`month`; - - DROP TEMPORARY TABLE tmp.time; +BEGIN +/** + * Inserta en la tabla @bs.carteras las ventas desde el año pasado + * agrupadas por trabajador, año y mes + */ + DECLARE vYear INT DEFAULT YEAR(util.VN_CURDATE()) - 1; + + DELETE FROM bs.carteras WHERE Año >= vYear; + + CALL util.time_generate( + MAKEDATE(vYear, 1), + (SELECT MAX(fecha) FROM ventas) + ); + + INSERT INTO carteras(Año, Mes , CodigoTrabajador, Peso) + SELECT t.`year`, t.`month`, w.code, SUM(v.importe) + FROM tmp.time t + JOIN ventas v on t.dated = v.fecha + JOIN vn.client c on c.id = v.Id_Cliente + JOIN vn.worker w ON w.id = c.salesPersonFk + GROUP BY w.code, t.`year`, t.`month`; + + DROP TEMPORARY TABLE tmp.time; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4685,25 +4685,27 @@ BLOCK1: BEGIN DECLARE vShipped DATE; DECLARE vPreviousShipped DATE; DECLARE vDone boolean; - DECLARE cur cursor for - - SELECT clientFk, firstShipped - FROM bs.clientNewBorn; + + DECLARE cur CURSOR FOR + SELECT clientFk, firstShipped + FROM bs.clientNewBorn; DECLARE continue HANDLER FOR NOT FOUND SET vDone = TRUE; SET vDone := FALSE; DELETE FROM bs.clientNewBorn WHERE isModified = FALSE; - INSERT INTO clientNewBorn(clientFk, firstShipped, lastShipped) - SELECT c.id, MAX(t.shipped), MAX(t.shipped) - FROM vn.client c - JOIN vn.ticket t on t.clientFk = c.id - LEFT JOIN clientNewBorn cb on cb.clientFk = c.id - WHERE t.shipped BETWEEN TIMESTAMPADD(YEAR, -1, util.VN_CURDATE()) AND util.VN_CURDATE() AND cb.isModified is null - GROUP BY c.id; + INSERT INTO clientNewBorn(clientFk, firstShipped, lastShipped) + SELECT c.id, DATE(MAX(t.shipped)), DATE(MAX(t.shipped)) + FROM vn.client c + JOIN vn.ticket t ON t.clientFk = c.id + LEFT JOIN clientNewBorn cb ON cb.clientFk = c.id + WHERE t.shipped BETWEEN util.VN_CURDATE() - INTERVAL 1 YEAR + AND util.VN_CURDATE() + AND cb.isModified IS NULL + GROUP BY c.id; + OPEN cur; - LOOP1: LOOP SET vDone := FALSE; FETCH cur INTO vClientFk, vShipped; @@ -5463,82 +5465,82 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `nightTask_launchAll`() -BEGIN -/** - * Runs all nightly tasks. - */ - DECLARE vDone BOOL; - DECLARE vError VARCHAR(255); - DECLARE vErrorCode VARCHAR(255); - DECLARE vSchema VARCHAR(255); - DECLARE vProcedure VARCHAR(255); - DECLARE vLogMail VARCHAR(255); - DECLARE vNightTaskFk INT; - - DECLARE vQueue CURSOR FOR - SELECT id, `schema`, `procedure` - FROM nightTask - WHERE finished <= util.VN_CURDATE() - OR finished IS NULL - ORDER BY `order`; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - SET max_sp_recursion_depth = 3; - - SELECT logMail INTO vLogMail - FROM nightTaskConfig LIMIT 1; - - OPEN vQueue; - l: LOOP - SET vDone = FALSE; - FETCH vQueue INTO vNightTaskFk, vSchema, vProcedure; - - IF vDone THEN - LEAVE l; - END IF; - - UPDATE nightTask - SET `started` = util.VN_NOW(), - `finished` = NULL, - `error` = NULL, - `errorCode` = NULL - WHERE id = vNightTaskFk; - - SET vError = NULL; - CALL nightTask_launchTask( - vSchema, - vProcedure, - vError, - vErrorCode - ); - - IF vError IS NOT NULL THEN - IF vLogMail IS NOT NULL THEN - CALL vn.mail_insert( - vLogMail, - NULL, - CONCAT('Nightly task failed (', vSchema, '.', vProcedure, ')'), - CONCAT( - '[', vErrorCode, '] ', vError, CHAR(13, 10), -- Line break - 'See ', SCHEMA(), '.nightTask table for more info.' - ) - ); - END IF; - - UPDATE nightTask - SET `error` = vError, - `errorCode` = vErrorCode - WHERE id = vNightTaskFk; - ELSE - UPDATE nightTask - SET finished = util.VN_NOW(), - lastFinished = util.VN_NOW() - WHERE id = vNightTaskFk; - END IF; - END LOOP; - CLOSE vQueue; +BEGIN +/** + * Runs all nightly tasks. + */ + DECLARE vDone BOOL; + DECLARE vError VARCHAR(255); + DECLARE vErrorCode VARCHAR(255); + DECLARE vSchema VARCHAR(255); + DECLARE vProcedure VARCHAR(255); + DECLARE vLogMail VARCHAR(255); + DECLARE vNightTaskFk INT; + + DECLARE vQueue CURSOR FOR + SELECT id, `schema`, `procedure` + FROM nightTask + WHERE finished <= util.VN_CURDATE() + OR finished IS NULL + ORDER BY `order`; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + SET max_sp_recursion_depth = 3; + + SELECT logMail INTO vLogMail + FROM nightTaskConfig LIMIT 1; + + OPEN vQueue; + l: LOOP + SET vDone = FALSE; + FETCH vQueue INTO vNightTaskFk, vSchema, vProcedure; + + IF vDone THEN + LEAVE l; + END IF; + + UPDATE nightTask + SET `started` = util.VN_NOW(), + `finished` = NULL, + `error` = NULL, + `errorCode` = NULL + WHERE id = vNightTaskFk; + + SET vError = NULL; + CALL nightTask_launchTask( + vSchema, + vProcedure, + vError, + vErrorCode + ); + + IF vError IS NOT NULL THEN + IF vLogMail IS NOT NULL THEN + CALL vn.mail_insert( + vLogMail, + NULL, + CONCAT('Nightly task failed (', vSchema, '.', vProcedure, ')'), + CONCAT( + '[', vErrorCode, '] ', vError, CHAR(13, 10), -- Line break + 'See ', SCHEMA(), '.nightTask table for more info.' + ) + ); + END IF; + + UPDATE nightTask + SET `error` = vError, + `errorCode` = vErrorCode + WHERE id = vNightTaskFk; + ELSE + UPDATE nightTask + SET finished = util.VN_NOW(), + lastFinished = util.VN_NOW() + WHERE id = vNightTaskFk; + END IF; + END LOOP; + CLOSE vQueue; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -7283,27 +7285,27 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_end`(IN `v_calc` INT) -BEGIN - DECLARE v_cache_name VARCHAR(255); - DECLARE v_params VARCHAR(255); - - -- Libera el bloqueo y actualiza la fecha de ultimo refresco. - - UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id - SET - cc.last_refresh = NOW(), - cc.expires = ADDTIME(NOW(), c.lifetime), - cc.connection_id = NULL - WHERE cc.id = v_calc; - - SELECT c.name, ca.params INTO v_cache_name, v_params - FROM cache c - JOIN cache_calc ca ON c.id = ca.cache_id - WHERE ca.id = v_calc; - - IF v_cache_name IS NOT NULL THEN - DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); - END IF; +BEGIN + DECLARE v_cache_name VARCHAR(255); + DECLARE v_params VARCHAR(255); + + -- Libera el bloqueo y actualiza la fecha de ultimo refresco. + + UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id + SET + cc.last_refresh = NOW(), + cc.expires = ADDTIME(NOW(), c.lifetime), + cc.connection_id = NULL + WHERE cc.id = v_calc; + + SELECT c.name, ca.params INTO v_cache_name, v_params + FROM cache c + JOIN cache_calc ca ON c.id = ca.cache_id + WHERE ca.id = v_calc; + + IF v_cache_name IS NOT NULL THEN + DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -7321,89 +7323,89 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_start`(OUT `v_calc` INT, INOUT `v_refresh` INT, IN `v_cache_name` VARCHAR(50), IN `v_params` VARCHAR(100)) -proc: BEGIN - DECLARE v_valid BOOL; - DECLARE v_lock_id VARCHAR(100); - DECLARE v_cache_id INT; - DECLARE v_expires DATETIME; - DECLARE v_clean_time DATETIME; - DECLARE vLastRefresh DATETIME; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - IF v_lock_id IS NOT NULL THEN - DO RELEASE_LOCK(v_lock_id); - END IF; - - RESIGNAL; - END; - - SET v_params = IFNULL(v_params, ''); - - -- Si el servidor se ha reiniciado invalida todos los calculos. - - SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; - - IF !v_valid - THEN - DELETE FROM cache_calc; - INSERT INTO cache_valid (valid) VALUES (TRUE); - END IF; - - -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. - - SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); - - IF !GET_LOCK(v_lock_id, 30) - THEN - SET v_calc = NULL; - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Comprueba si el calculo solicitado existe y esta actualizado. - - SELECT c.id, ca.id, ca.expires, ca.last_refresh - INTO v_cache_id, v_calc, v_expires, vLastRefresh - FROM cache c - LEFT JOIN cache_calc ca - ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' - WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; - - -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. - - IF !v_refresh AND NOW() < v_expires AND vLastRefresh >= CURDATE() - THEN - DO RELEASE_LOCK(v_lock_id); - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Si el calculo no existe le crea una entrada en la tabla de calculos. - - IF v_calc IS NULL - THEN - INSERT INTO cache_calc SET - cache_id = v_cache_id, - cacheName = v_cache_name, - params = v_params, - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID(); - - SET v_calc = LAST_INSERT_ID(); - ELSE - UPDATE cache_calc - SET - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID() - WHERE id = v_calc; - END IF; - - -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. - - SET v_refresh = TRUE; +proc: BEGIN + DECLARE v_valid BOOL; + DECLARE v_lock_id VARCHAR(100); + DECLARE v_cache_id INT; + DECLARE v_expires DATETIME; + DECLARE v_clean_time DATETIME; + DECLARE vLastRefresh DATETIME; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + IF v_lock_id IS NOT NULL THEN + DO RELEASE_LOCK(v_lock_id); + END IF; + + RESIGNAL; + END; + + SET v_params = IFNULL(v_params, ''); + + -- Si el servidor se ha reiniciado invalida todos los calculos. + + SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; + + IF !v_valid + THEN + DELETE FROM cache_calc; + INSERT INTO cache_valid (valid) VALUES (TRUE); + END IF; + + -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. + + SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); + + IF !GET_LOCK(v_lock_id, 30) + THEN + SET v_calc = NULL; + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Comprueba si el calculo solicitado existe y esta actualizado. + + SELECT c.id, ca.id, ca.expires, ca.last_refresh + INTO v_cache_id, v_calc, v_expires, vLastRefresh + FROM cache c + LEFT JOIN cache_calc ca + ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' + WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; + + -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. + + IF !v_refresh AND NOW() < v_expires AND vLastRefresh >= CURDATE() + THEN + DO RELEASE_LOCK(v_lock_id); + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Si el calculo no existe le crea una entrada en la tabla de calculos. + + IF v_calc IS NULL + THEN + INSERT INTO cache_calc SET + cache_id = v_cache_id, + cacheName = v_cache_name, + params = v_params, + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID(); + + SET v_calc = LAST_INSERT_ID(); + ELSE + UPDATE cache_calc + SET + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID() + WHERE id = v_calc; + END IF; + + -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. + + SET v_refresh = TRUE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -7835,7 +7837,6 @@ CREATE TABLE `expedition_PrintOut` ( `longName` varchar(30) DEFAULT NULL, `shelvingFk` varchar(5) DEFAULT NULL, `comments` varchar(100) DEFAULT NULL, - `isChecked` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Indica si la expedición ha sido revisada por un revisor', PRIMARY KEY (`expeditionFk`), KEY `expedition_PrintOut_FK` (`printerFk`), CONSTRAINT `expedition_PrintOut_FK` FOREIGN KEY (`printerFk`) REFERENCES `printer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE @@ -10428,28 +10429,28 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `contact_request`( - vName VARCHAR(100), - vPhone VARCHAR(15), - vEmail VARCHAR(100), +CREATE DEFINER=`root`@`localhost` PROCEDURE `contact_request`( + vName VARCHAR(100), + vPhone VARCHAR(15), + vEmail VARCHAR(100), vMessage TEXT) READS SQL DATA -BEGIN -/** - * Set actions for contact request - * - * @param vName Name - * @param vPhone Phone number - * @param vEmail e-mail - * @param vMessage text of the message - */ - - CALL vn.mail_insert( - 'floranet@verdnatura.es', - vEmail, - 'Contact request', - CONCAT('Phone: ',vPhone, ' Message: ', vMessage) - ); +BEGIN +/** + * Set actions for contact request + * + * @param vName Name + * @param vPhone Phone number + * @param vEmail e-mail + * @param vMessage text of the message + */ + + CALL vn.mail_insert( + 'floranet@verdnatura.es', + vEmail, + 'Contact request', + CONCAT('Phone: ',vPhone, ' Message: ', vMessage) + ); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10468,27 +10469,27 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `deliveryDate_get`(vPostalCode VARCHAR(15)) READS SQL DATA -BEGIN -/** - * Returns available dates for this postalCode, in the next seven days. - * - * @param vPostalCode Delivery address postal code - */ - DECLARE vCurrentDayOfWeek INT; - - SET vCurrentDayOfWeek = DAYOFWEEK(NOW()); - - SELECT DISTINCT nextDay - FROM ( - SELECT CURDATE() + INTERVAL IF( - apc.dayOfWeek >= vCurrentDayOfWeek, - apc.dayOfWeek - vCurrentDayOfWeek, - 7 - apc.dayOfWeek - ) DAY nextDay, - NOW() + INTERVAL apc.hoursInAdvance HOUR minDeliveryTime - FROM addressPostCode apc - WHERE apc.postCode = vPostalCode - HAVING nextDay > minDeliveryTime) sub; +BEGIN +/** + * Returns available dates for this postalCode, in the next seven days. + * + * @param vPostalCode Delivery address postal code + */ + DECLARE vCurrentDayOfWeek INT; + + SET vCurrentDayOfWeek = DAYOFWEEK(NOW()); + + SELECT DISTINCT nextDay + FROM ( + SELECT CURDATE() + INTERVAL IF( + apc.dayOfWeek >= vCurrentDayOfWeek, + apc.dayOfWeek - vCurrentDayOfWeek, + 7 - apc.dayOfWeek + ) DAY nextDay, + NOW() + INTERVAL apc.hoursInAdvance HOUR minDeliveryTime + FROM addressPostCode apc + WHERE apc.postCode = vPostalCode + HAVING nextDay > minDeliveryTime) sub; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -11396,6 +11397,7 @@ CREATE TABLE `order` ( `tax` decimal(10,2) NOT NULL, `total` decimal(10,2) NOT NULL, `configured` datetime DEFAULT NULL, + `rowUpdated` datetime DEFAULT NULL COMMENT 'Timestamp for last updated record in orderRow table', PRIMARY KEY (`id`), KEY `address` (`address_id`), KEY `delivery_method` (`delivery_method_id`), @@ -13184,6 +13186,70 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `orderRow_updateOverstocking` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`vn`@`localhost` PROCEDURE `orderRow_updateOverstocking`(vOrderFk INT) +BEGIN +/** +* Set amount = 0 to avoid overbooking sales +* +* @param vOrderFk hedera.order.id +*/ + DECLARE vCalcFk INT; + DECLARE vDone BOOL; + DECLARE vWarehouseFk INT; + + DECLARE cWarehouses CURSOR FOR + SELECT DISTINCT warehouseFk + FROM orderRow + WHERE orderFk = vOrderFk + AND shipment = util.VN_CURDATE(); + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + OPEN cWarehouses; + checking: LOOP + SET vDone = FALSE; + + FETCH cWarehouses INTO vWarehouseFk; + + IF vDone THEN + LEAVE checking; + END IF; + + CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, util.VN_CURDATE()); + + UPDATE orderRow r + JOIN `order` o ON o.id = r.orderFk + JOIN orderConfig oc + JOIN cache.available a ON a.calc_id = vCalcFk AND a.item_id = r.itemFk + SET r.amount = 0 + WHERE ADDTIME(o.rowUpdated, oc.reserveTime) < util.VN_NOW() + AND a.available <= 0 + AND r.warehouseFk = vWarehouseFk + AND r.orderFk = vOrderFk; + END LOOP; + CLOSE cWarehouses; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `order_addItem` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -13689,6 +13755,7 @@ BEGIN * @param vUser The user identifier */ DECLARE vHasRows BOOL; + DECLARE vHas0Amount BOOL; DECLARE vDone BOOL; DECLARE vWarehouseFk INT; DECLARE vShipment DATE; @@ -13698,7 +13765,6 @@ BEGIN DECLARE vItemFk INT; DECLARE vConcept VARCHAR(30); DECLARE vAmount INT; - DECLARE vAvailable INT; DECLARE vPrice DECIMAL(10,2); DECLARE vSaleFk INT; DECLARE vRowFk INT; @@ -13708,7 +13774,6 @@ BEGIN DECLARE vClientFk INT; DECLARE vCompanyFk INT; DECLARE vAgencyModeFk INT; - DECLARE vCalcFk INT; DECLARE vIsTaxDataChecked BOOL; DECLARE vDates CURSOR FOR @@ -13774,6 +13839,20 @@ BEGIN SELECT employeeFk INTO vUserFk FROM orderConfig; END IF; + CALL orderRow_updateOverstocking(vSelf); + + -- Check if any product has a quantity of 0 + SELECT EXISTS ( + SELECT id + FROM orderRow + WHERE orderFk = vSelf + AND amount = 0 + ) INTO vHas0Amount; + + IF vHas0Amount THEN + CALL util.throw('Hay líneas vacías. Por favor, elimínelas'); + END IF; + START TRANSACTION; CALL order_checkEditable(vSelf); @@ -25827,7 +25906,7 @@ CREATE TABLE `address` ( `isActive` tinyint(4) NOT NULL DEFAULT 1, `longitude` decimal(11,7) DEFAULT NULL COMMENT 'Indica la última longitud proporcionada por tabla delivery', `latitude` decimal(11,7) DEFAULT NULL COMMENT 'Indica la última latitud proporcionada por tabla delivery', - `isEqualizated` tinyint(1) DEFAULT NULL, + `isEqualizated` tinyint(1) NOT NULL DEFAULT 0, `customsAgentFk` int(11) DEFAULT NULL, `incotermsFk` varchar(3) DEFAULT NULL, `isLogifloraAllowed` tinyint(4) NOT NULL DEFAULT 0, @@ -26035,7 +26114,7 @@ CREATE TABLE `agencyMode` ( `inflation` decimal(5,2) NOT NULL DEFAULT 0.00 COMMENT 'Este valor se utiliza para aumentar el valor del componente porte.', `isVolumetric` tinyint(1) NOT NULL DEFAULT 0, `reportMail` varchar(100) DEFAULT NULL, - `showAgencyName` tinyint(1) DEFAULT 1 COMMENT 'obsoleta', + `showAgencyName__` tinyint(1) DEFAULT 1 COMMENT '@deprecated 2024-09-24', `isActive` tinyint(1) NOT NULL DEFAULT 1, `isExternalAgency` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'obsoleta', `flag` blob DEFAULT NULL COMMENT 'obsoleta', @@ -27058,23 +27137,6 @@ CREATE TABLE `buyConfig` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; --- --- Table structure for table `buyMark` --- - -DROP TABLE IF EXISTS `buyMark`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `buyMark` ( - `id` int(11) NOT NULL, - `comment` varchar(255) DEFAULT NULL, - `mark` tinyint(1) DEFAULT NULL, - `odbcDate` timestamp NULL DEFAULT current_timestamp(), - PRIMARY KEY (`id`), - CONSTRAINT `Compres_mark_ibfk_1` FOREIGN KEY (`id`) REFERENCES `buy` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `buyer` -- @@ -27208,9 +27270,10 @@ DROP TABLE IF EXISTS `campaign`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `campaign` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `code` enum('mothersDay','allSaints','valentinesDay') NOT NULL, + `code` enum('mothersDay','allSaints','valentinesDay','frenchMothersDay') NOT NULL, `dated` datetime NOT NULL DEFAULT current_timestamp(), `scopeDays` int(11) NOT NULL DEFAULT 15, + `previousDays` int(10) unsigned NOT NULL DEFAULT 30 COMMENT 'Días previos para calcular e insertar en la tabla itemCampaign', PRIMARY KEY (`id`), UNIQUE KEY `campaign_dated_uindex` (`dated`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; @@ -27262,7 +27325,7 @@ CREATE TABLE `chat` ( `senderFk` int(10) unsigned DEFAULT NULL, `recipient` varchar(50) DEFAULT NULL, `dated` datetime DEFAULT NULL, - `checkUserStatus` tinyint(1) DEFAULT NULL, + `checkUserStatus` tinyint(1) NOT NULL DEFAULT 0, `message` text DEFAULT NULL, `attempts` int(1) DEFAULT NULL, `error` text DEFAULT NULL, @@ -27656,7 +27719,7 @@ CREATE TABLE `client` ( `credit` decimal(10,2) unsigned NOT NULL DEFAULT 0.00, `countryFk` mediumint(8) unsigned NOT NULL DEFAULT 1, `isActive` tinyint(1) NOT NULL DEFAULT 1, - `gestdocFk` int(11) DEFAULT NULL, + `gestdocFk__` int(11) DEFAULT NULL COMMENT '@deprecated 2024-10-17', `quality` int(2) DEFAULT 11, `payMethodFk` tinyint(3) unsigned NOT NULL DEFAULT 5, `created` timestamp NULL DEFAULT current_timestamp(), @@ -27969,11 +28032,14 @@ CREATE TABLE `clientObservation` ( `text` text NOT NULL, `created` timestamp NOT NULL DEFAULT current_timestamp(), `editorFk` int(10) unsigned DEFAULT NULL, + `observationTypeFk` tinyint(3) unsigned DEFAULT NULL, PRIMARY KEY (`id`), KEY `Id_Trabajador` (`workerFk`), KEY `Id_Cliente` (`clientFk`), KEY `clientObservation_created_IDX` (`created`) USING BTREE, KEY `clientObservation_fk_editor` (`editorFk`), + KEY `clientObservationTypeFk` (`observationTypeFk`), + CONSTRAINT `clientObservationTypeFk` FOREIGN KEY (`observationTypeFk`) REFERENCES `observationType` (`id`), CONSTRAINT `clientObservation_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), CONSTRAINT `clientObservation_ibfk_1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `clientObservation_ibfk_2` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE @@ -29619,6 +29685,10 @@ CREATE TABLE `docuwareConfig` ( `id` int(10) unsigned NOT NULL, `url` varchar(75) DEFAULT NULL, `cookie` varchar(1000) DEFAULT NULL, + `username` varchar(100) DEFAULT NULL, + `password` varchar(100) DEFAULT NULL, + `token` text DEFAULT NULL, + `expired` int(11) DEFAULT NULL, PRIMARY KEY (`id`), CONSTRAINT `docuwareConfig_check` CHECK (`id` = 1) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; @@ -31985,6 +32055,21 @@ CREATE TABLE `itemBarcode` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `itemBaseTag` +-- + +DROP TABLE IF EXISTS `itemBaseTag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `itemBaseTag` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `itemBotanical` -- @@ -32021,6 +32106,42 @@ SET character_set_client = utf8; 1 AS `ediBotanic` */; SET character_set_client = @saved_cs_client; +-- +-- Table structure for table `itemBreederTag` +-- + +DROP TABLE IF EXISTS `itemBreederTag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `itemBreederTag` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `itemCampaign` +-- + +DROP TABLE IF EXISTS `itemCampaign`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `itemCampaign` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `dated` date NOT NULL, + `itemFk` int(11) NOT NULL, + `quantity` decimal(10,2) NOT NULL, + `total` decimal(10,2) NOT NULL, + `campaign` varchar(100) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `itemCampaign_UNIQUE` (`dated`,`itemFk`), + KEY `itemCampaign_item_FK` (`itemFk`), + CONSTRAINT `itemCampaign_item_FK` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tallos confirmados por día en los días de más producción de una campaña. La tabla está pensada para que sea una foto.'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `itemCategory` -- @@ -32205,6 +32326,21 @@ CREATE TABLE `itemFamily` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `itemFarmingTag` +-- + +DROP TABLE IF EXISTS `itemFarmingTag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `itemFarmingTag` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `itemImageQueue` -- @@ -32256,6 +32392,21 @@ CREATE TABLE `itemLabel` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `itemLanguageTag` +-- + +DROP TABLE IF EXISTS `itemLanguageTag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `itemLanguageTag` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `itemLog` -- @@ -32470,6 +32621,7 @@ CREATE TABLE `itemShelving` ( `editorFk` int(10) unsigned DEFAULT NULL, `available` int(11) DEFAULT NULL, `isSplit` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Este valor cambia al splitar un carro que se ha quedado en holanda', + `movingState` enum('selected','printed') DEFAULT NULL, PRIMARY KEY (`id`), KEY `itemShelving_fk1_idx` (`itemFk`), KEY `itemShelving_fk2_idx` (`shelvingFk`), @@ -32478,7 +32630,7 @@ CREATE TABLE `itemShelving` ( KEY `itemShelvingBuy_FK` (`buyFk`), CONSTRAINT `itemShelvingBuy_FK` FOREIGN KEY (`buyFk`) REFERENCES `buy` (`id`), CONSTRAINT `itemShelving_fk1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `itemShelving_fk2` FOREIGN KEY (`shelvingFk`) REFERENCES `shelving` (`code`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `itemShelving_fk2` FOREIGN KEY (`shelvingFk`) REFERENCES `shelving` (`code`) ON UPDATE CASCADE, CONSTRAINT `itemShelving_fk3` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla utilizada para localizar los artículos dentro de los carros. Usado para la gestión del almacén en el altillo '; /*!40101 SET character_set_client = @saved_cs_client */; @@ -32737,6 +32889,36 @@ SET character_set_client = utf8; 1 AS `removed` */; SET character_set_client = @saved_cs_client; +-- +-- Table structure for table `itemStateTag` +-- + +DROP TABLE IF EXISTS `itemStateTag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `itemStateTag` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `itemStemTag` +-- + +DROP TABLE IF EXISTS `itemStemTag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `itemStemTag` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `itemTag` -- @@ -32957,6 +33139,36 @@ CREATE TABLE `itemTypeTag` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `itemVatRateTag` +-- + +DROP TABLE IF EXISTS `itemVatRateTag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `itemVatRateTag` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `itemWrappingTag` +-- + +DROP TABLE IF EXISTS `itemWrappingTag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `itemWrappingTag` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Temporary table structure for view `item_Free_Id` -- @@ -33809,6 +34021,7 @@ CREATE TABLE `operator` ( `volumeLimit` decimal(10,6) DEFAULT 0.500000 COMMENT 'Límite de volumen en una colección para la asignación de pedidos', `sizeLimit` int(10) unsigned DEFAULT NULL COMMENT 'Límite de altura en una colección para la asignación de pedidos', `isOnReservationMode` tinyint(1) NOT NULL DEFAULT 0, + `machineFk` int(11) DEFAULT NULL, PRIMARY KEY (`workerFk`), KEY `operator_FK` (`workerFk`), KEY `operator_FK_1` (`trainFk`), @@ -33816,11 +34029,13 @@ CREATE TABLE `operator` ( KEY `operator_FK_3` (`warehouseFk`), KEY `operator_FK_5` (`labelerFk`), KEY `operator_FK_4` (`sectorFk`), + KEY `operator_machine_FK` (`machineFk`), CONSTRAINT `operator_FK` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `operator_FK_1` FOREIGN KEY (`trainFk`) REFERENCES `train` (`id`) ON UPDATE CASCADE, CONSTRAINT `operator_FK_2` FOREIGN KEY (`itemPackingTypeFk`) REFERENCES `itemPackingType` (`code`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `operator_FK_3` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `operator_FK_4` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON UPDATE CASCADE + CONSTRAINT `operator_FK_4` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON UPDATE CASCADE, + CONSTRAINT `operator_machine_FK` FOREIGN KEY (`machineFk`) REFERENCES `machine` (`id`) ON DELETE SET NULL ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -34916,7 +35131,7 @@ CREATE TABLE `priceDelta` ( `warehouseFk` smallint(6) unsigned NOT NULL, `created` timestamp NOT NULL DEFAULT current_timestamp(), `editorFk` int(10) unsigned DEFAULT NULL, - `zoneGeoFk` int(11) DEFAULT NULL, + `zoneGeoFk` int(11) DEFAULT NULL COMMENT 'Application area for the bonus component', PRIMARY KEY (`id`), KEY `priceDelta_itemType_FK` (`itemTypeFk`), KEY `priceDelta_ink_FK` (`inkFk`), @@ -36929,6 +37144,7 @@ CREATE TABLE `sector` ( `isReserve` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Sectores de reserva, como Albenfruit o Fuentes', `backupPrinterFk` int(10) unsigned DEFAULT NULL, `typeFk` int(10) unsigned NOT NULL DEFAULT 1, + `isOnReservationMode` tinyint(1) DEFAULT 0, PRIMARY KEY (`id`), UNIQUE KEY `code_UNIQUE` (`code`), KEY `sector_fk1_idx` (`warehouseFk`), @@ -37651,13 +37867,13 @@ CREATE TABLE `stockBought` ( /*!40101 SET character_set_client = @saved_cs_client */; -- --- Table structure for table `stockBuyed` +-- Table structure for table `stockBuyed__` -- -DROP TABLE IF EXISTS `stockBuyed`; +DROP TABLE IF EXISTS `stockBuyed__`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `stockBuyed` ( +CREATE TABLE `stockBuyed__` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `userFk` int(10) unsigned DEFAULT NULL, `buyed` decimal(10,2) DEFAULT NULL, @@ -37669,7 +37885,7 @@ CREATE TABLE `stockBuyed` ( PRIMARY KEY (`id`), KEY `stockBuyed_user_idx` (`userFk`), CONSTRAINT `stockBuyedUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='@deprecated 2024-10-01 rename and refactor to stockBought'; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -38374,10 +38590,12 @@ CREATE TABLE `ticketConfig` ( `packingDelay` int(11) DEFAULT 1 COMMENT 'Horas que marcará el retraso respecto hora de cierre web del ticket', `daysForWarningClaim` int(11) NOT NULL DEFAULT 2 COMMENT 'dias restantes hasta que salte el aviso de reclamación fuera de plazo', `defaultAttenderFk` int(10) unsigned DEFAULT NULL, + `closureDaysAgo` int(11) NOT NULL DEFAULT 2 COMMENT 'Number of days to look back for ticket closure', PRIMARY KEY (`id`), KEY `ticketConfig_worker_FK` (`defaultAttenderFk`), CONSTRAINT `ticketConfig_worker_FK` FOREIGN KEY (`defaultAttenderFk`) REFERENCES `worker` (`id`), - CONSTRAINT `ticketConfig_check` CHECK (`id` = 1) + CONSTRAINT `ticketConfig_check` CHECK (`id` = 1), + CONSTRAINT `closureDaysAgo_check` CHECK (`closureDaysAgo` > 0) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -39414,6 +39632,8 @@ CREATE TABLE `travelThermograph` ( `result` varchar(45) DEFAULT NULL, `dmsFk` int(11) DEFAULT NULL, `temperatureFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT 'cool' COMMENT 'En la versión de Agosto de Salix se empezará a usar este campo y se actualizaran los anteriores mirando temperature.', + `maxTemperature` decimal(5,2) DEFAULT NULL, + `minTemperature` decimal(5,2) DEFAULT NULL, `editorFk` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), KEY `thermograph_fk_idx` (`thermographFk`), @@ -39422,7 +39642,7 @@ CREATE TABLE `travelThermograph` ( KEY `warehouse_id` (`warehouseFk`), KEY `travelThermographTemperatureFgn` (`temperatureFk`), KEY `travelThermograph_fk_editor` (`editorFk`), - CONSTRAINT `travelThermographDmsFgn` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON UPDATE CASCADE, + CONSTRAINT `travelThermographDmsFgn` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `travelThermographTemperatureFgn` FOREIGN KEY (`temperatureFk`) REFERENCES `temperature` (`code`), CONSTRAINT `travelThermographThermographFgn` FOREIGN KEY (`thermographFk`) REFERENCES `thermograph` (`id`) ON UPDATE CASCADE, CONSTRAINT `travelThermographTravelFgn` FOREIGN KEY (`travelFk`) REFERENCES `travel` (`id`), @@ -39938,8 +40158,8 @@ CREATE TABLE `warehouse` ( `isLogiflora` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Este almacén acepta productos de Logiflora', `isBionic` tinyint(1) NOT NULL DEFAULT 1, `isHalt` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Almacén en el que descargan nuestros troncales', - `isOrigin` tinyint(1) DEFAULT NULL, - `isDestiny` tinyint(1) DEFAULT NULL, + `isOrigin` tinyint(1) NOT NULL DEFAULT 0, + `isDestiny` tinyint(1) NOT NULL DEFAULT 0, PRIMARY KEY (`id`), UNIQUE KEY `name_UNIQUE` (`name`), KEY `Id_Paises` (`countryFk`), @@ -41174,7 +41394,7 @@ CREATE TABLE `zoneIncluded` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `zoneFk` int(11) NOT NULL, `geoFk` int(11) NOT NULL, - `isIncluded` tinyint(1) DEFAULT NULL, + `isIncluded` tinyint(1) NOT NULL DEFAULT 0, `editorFk` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `unique_zone_geo` (`zoneFk`,`geoFk`), @@ -41428,6 +41648,24 @@ DELIMITER ;; /*!50003 SET character_set_client = @saved_cs_client */ ;; /*!50003 SET character_set_results = @saved_cs_results */ ;; /*!50003 SET collation_connection = @saved_col_connection */ ;; +/*!50106 DROP EVENT IF EXISTS `itemCampaig_add` */;; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8mb4 */ ;; +/*!50003 SET character_set_results = utf8mb4 */ ;; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`vn`@`localhost`*/ /*!50106 EVENT `itemCampaig_add` ON SCHEDULE EVERY 1 DAY STARTS '2024-10-18 03:00:00' ON COMPLETION PRESERVE ENABLE DO CALL itemCampaign_add() */ ;; +/*!50003 SET time_zone = @saved_time_zone */ ;; +/*!50003 SET sql_mode = @saved_sql_mode */ ;; +/*!50003 SET character_set_client = @saved_cs_client */ ;; +/*!50003 SET character_set_results = @saved_cs_results */ ;; +/*!50003 SET collation_connection = @saved_col_connection */ ;; /*!50106 DROP EVENT IF EXISTS `itemImageQueue_check` */;; DELIMITER ;; /*!50003 SET @saved_cs_client = @@character_set_client */ ;; @@ -42159,37 +42397,37 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`vn`@`localhost` FUNCTION `client_getDebt`(`vClient` INT, `vDate` DATE) RETURNS decimal(10,2) READS SQL DATA -BEGIN -/** - * Returns the risk of a customer. - * - * @param vClient client id - * @param vDate date to check the risk - * @return Client risk - */ - DECLARE vDebt DECIMAL(10,2); - DECLARE vHasDebt BOOLEAN; - - SELECT COUNT(*) INTO vHasDebt - FROM `client` c - WHERE c.id = vClient AND c.typeFk = 'normal'; - - IF NOT vHasDebt THEN - RETURN 0; - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt (clientFk INT); - INSERT INTO tmp.clientGetDebt SET clientFk = vClient; - - CALL vn.client_getDebt(vDate); - - SELECT risk INTO vDebt FROM tmp.risk; - - DROP TEMPORARY TABLE - tmp.clientGetDebt, - tmp.risk; - - RETURN vDebt; +BEGIN +/** + * Returns the risk of a customer. + * + * @param vClient client id + * @param vDate date to check the risk + * @return Client risk + */ + DECLARE vDebt DECIMAL(10,2); + DECLARE vHasDebt BOOLEAN; + + SELECT COUNT(*) INTO vHasDebt + FROM `client` c + WHERE c.id = vClient AND c.typeFk = 'normal'; + + IF NOT vHasDebt THEN + RETURN 0; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt (clientFk INT); + INSERT INTO tmp.clientGetDebt SET clientFk = vClient; + + CALL vn.client_getDebt(vDate); + + SELECT risk INTO vDebt FROM tmp.risk; + + DROP TEMPORARY TABLE + tmp.clientGetDebt, + tmp.risk; + + RETURN vDebt; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48028,39 +48266,6 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `buy_getVolumeByAgency` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `buy_getVolumeByAgency`(vDated DATE, vAgencyFk INT) -BEGIN - - DROP TEMPORARY TABLE IF EXISTS tmp.buy; - CREATE TEMPORARY TABLE tmp.buy (buyFk INT NOT NULL, PRIMARY KEY (buyFk)) ENGINE = MEMORY; - - INSERT INTO tmp.buy - SELECT b.id - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed = vDated - AND t.agencyModeFk IN (0, vAgencyFk); - - CALL buy_getVolume(); - DROP TEMPORARY TABLE tmp.buy; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `buy_getVolumeByEntry` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -49309,6 +49514,13 @@ BEGIN DELETE FROM messageInbox WHERE sendDate < v2Months; DELETE FROM messageInbox WHERE sendDate < v2Months; DELETE FROM workerTimeControl WHERE timed < v4Years; + DELETE FROM itemShelvingSale + WHERE itemShelvingFk IN ( + SELECT id + FROM itemShelving + WHERE created < util.VN_CURDATE() + AND visible = 0 + ); DELETE FROM itemShelving WHERE created < util.VN_CURDATE() AND visible = 0; DELETE FROM ticketDown WHERE created < util.yesterday(); DELETE IGNORE FROM expedition WHERE created < v26Months; @@ -49336,16 +49548,10 @@ BEGIN DELETE FROM claim WHERE ticketCreated < v4Years; -- Robert ubicacion anterior de travelLog comentario para debug DELETE FROM zoneEvent WHERE `type` = 'day' AND dated < v3Months; - DELETE bm - FROM buyMark bm - JOIN buy b ON b.id = bm.id - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed <= v2Months; DELETE b FROM buy b JOIN entryConfig e ON e.defaultEntry = b.entryFk WHERE b.created < v2Months; - DELETE FROM stockBuyed WHERE creationDate < v2Months; + DELETE FROM stockBought WHERE dated < v2Months; DELETE FROM printQueue WHERE statusCode = 'printed' AND created < v2Months; -- Equipos duplicados DELETE w.* @@ -50287,22 +50493,19 @@ BEGIN DECLARE vIsTaxDataChecked TINYINT(1); DECLARE vHasCoreVnl BOOLEAN; DECLARE vMandateTypeFk INT; - DECLARE vHasDailyInvoice BOOLEAN; SELECT cc.defaultPayMethodFk, cc.defaultDueDay, cc.defaultCredit, cc.defaultIsTaxDataChecked, cc.defaultHasCoreVnl, - cc.defaultMandateTypeFk, - c.hasDailyInvoice + cc.defaultMandateTypeFk INTO vPayMethodFk, vDueDay, vDefaultCredit, vIsTaxDataChecked, vHasCoreVnl, - vMandateTypeFk, - vHasDailyInvoice + vMandateTypeFk FROM clientConfig cc LEFT JOIN province p ON p.id = vProvinceFk LEFT JOIN country c ON c.id = p.countryFk; @@ -50323,8 +50526,7 @@ BEGIN credit = vDefaultCredit, isTaxDataChecked = vIsTaxDataChecked, hasCoreVnl = vHasCoreVnl, - isEqualizated = FALSE, - hasDailyInvoice = vHasDailyInvoice + isEqualizated = FALSE ON duplicate KEY UPDATE payMethodFk = vPayMethodFk, dueDay = vDueDay, @@ -51019,93 +51221,93 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `collection_addWithReservation`( - vItemFk INT, - vQuantity INT, - vTicketFk INT, - vSaleGroupFk INT, - vSectorFk INT +CREATE DEFINER=`vn`@`localhost` PROCEDURE `collection_addWithReservation`( + vItemFk INT, + vQuantity INT, + vTicketFk INT, + vSaleGroupFk INT, + vSectorFk INT ) -BEGIN -/** - * En el ámbito de las colecciones se añade una línea de sale a un ticket - * de una colección en caso de tener disponible y se realiza la reserva. - * - * @param vItemFk id of item - * @param vQuantity quantity to be added to the ticket - * @param vTicketFk ticket to which the sales line is added - * @param vSaleGroupFk saleGroupFk id to add saleGroupDetail - */ - - DECLARE vWarehouseFk INT; - DECLARE vCacheAvailableFk INT; - DECLARE vAvailable INT; - DECLARE vSaleFk INT; - DECLARE vConcept VARCHAR(50); - DECLARE vItemName VARCHAR(50); - DECLARE vHasThrow BOOLEAN DEFAULT FALSE; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - SELECT t.warehouseFk INTO vWarehouseFk - FROM ticket t - JOIN ticketCollection tc ON tc.ticketFk = t.id - WHERE t.id = vTicketFk; - - CALL cache.available_refresh( - vCacheAvailableFk, - FALSE, - vWarehouseFk, - util.VN_CURDATE()); - - SELECT available INTO vAvailable - FROM cache.available - WHERE calc_id = vCacheAvailableFk - AND item_id = vItemFk; - - IF vAvailable < vQuantity THEN - SET vHasThrow = TRUE; - ELSE - SELECT `name`, - CONCAT(getUser(), ' ', DATE_FORMAT(util.VN_NOW(), '%H:%i'), ' ', name) - INTO vItemName, vConcept - FROM item - WHERE id = vItemFk; - - START TRANSACTION; - - INSERT INTO sale - SET itemFk = vItemFk, - ticketFk = vTicketFk, - concept = vConcept, - quantity = vQuantity, - isAdded = TRUE; - - SELECT LAST_INSERT_ID() INTO vSaleFk; - - CALL sale_calculateComponent(vSaleFk, NULL); - CALL itemShelvingSale_addBySale(vSaleFk, vSectorFk); - - IF NOT EXISTS (SELECT TRUE FROM itemShelvingSale WHERE saleFk = vSaleFk LIMIT 1) THEN - SET vHasThrow = TRUE; - END IF; - END IF; - - IF vHasThrow THEN - CALL util.throw("There is no available for the selected item"); - END IF; - - IF vSaleGroupFk THEN - INSERT INTO saleGroupDetail - SET saleFk = vSaleFk, - saleGroupFk = vSaleGroupFk; - END IF; - - COMMIT; +BEGIN +/** + * En el ámbito de las colecciones se añade una línea de sale a un ticket + * de una colección en caso de tener disponible y se realiza la reserva. + * + * @param vItemFk id of item + * @param vQuantity quantity to be added to the ticket + * @param vTicketFk ticket to which the sales line is added + * @param vSaleGroupFk saleGroupFk id to add saleGroupDetail + */ + + DECLARE vWarehouseFk INT; + DECLARE vCacheAvailableFk INT; + DECLARE vAvailable INT; + DECLARE vSaleFk INT; + DECLARE vConcept VARCHAR(50); + DECLARE vItemName VARCHAR(50); + DECLARE vHasThrow BOOLEAN DEFAULT FALSE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + SELECT t.warehouseFk INTO vWarehouseFk + FROM ticket t + JOIN ticketCollection tc ON tc.ticketFk = t.id + WHERE t.id = vTicketFk; + + CALL cache.available_refresh( + vCacheAvailableFk, + FALSE, + vWarehouseFk, + util.VN_CURDATE()); + + SELECT available INTO vAvailable + FROM cache.available + WHERE calc_id = vCacheAvailableFk + AND item_id = vItemFk; + + IF vAvailable < vQuantity THEN + SET vHasThrow = TRUE; + ELSE + SELECT `name`, + CONCAT(getUser(), ' ', DATE_FORMAT(util.VN_NOW(), '%H:%i'), ' ', name) + INTO vItemName, vConcept + FROM item + WHERE id = vItemFk; + + START TRANSACTION; + + INSERT INTO sale + SET itemFk = vItemFk, + ticketFk = vTicketFk, + concept = vConcept, + quantity = vQuantity, + isAdded = TRUE; + + SELECT LAST_INSERT_ID() INTO vSaleFk; + + CALL sale_calculateComponent(vSaleFk, NULL); + CALL itemShelvingSale_addBySale(vSaleFk, vSectorFk); + + IF NOT EXISTS (SELECT TRUE FROM itemShelvingSale WHERE saleFk = vSaleFk LIMIT 1) THEN + SET vHasThrow = TRUE; + END IF; + END IF; + + IF vHasThrow THEN + CALL util.throw("There is no available for the selected item"); + END IF; + + IF vSaleGroupFk THEN + INSERT INTO saleGroupDetail + SET saleFk = vSaleFk, + saleGroupFk = vSaleGroupFk; + END IF; + + COMMIT; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51122,129 +51324,145 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `collection_assign`( - vUserFk INT, - OUT vCollectionFk INT +CREATE DEFINER=`vn`@`localhost` PROCEDURE `collection_assign`( + vUserFk INT, + OUT vCollectionFk INT ) -BEGIN -/** - * Comprueba si existen colecciones libres que se ajustan - * al perfil del usuario y le asigna la más antigua. - * Añade un registro al semillero de colecciones. - * - * @param vUserFk Id de usuario - * @param vCollectionFk Id de colección - */ - DECLARE vHasTooMuchCollections BOOL; - DECLARE vDone BOOL DEFAULT FALSE; - DECLARE vCollectionWorker INT; - DECLARE vMaxNotAssignedCollectionLifeTime TIME; - - DECLARE vCollections CURSOR FOR - WITH collections AS ( - SELECT tc.collectionFk, - SUM(sv.volume) volume, - c.saleTotalCount, - c.itemPackingTypeFk, - c.trainFk, - c.warehouseFk, - c.wagons - FROM vn.ticketCollection tc - JOIN vn.collection c ON c.id = tc.collectionFk - JOIN vn.saleVolume sv ON sv.ticketFk = tc.ticketFk - WHERE c.workerFk IS NULL - AND sv.shipped >= util.VN_CURDATE() - GROUP BY tc.collectionFk - ) SELECT c.collectionFk - FROM collections c - JOIN vn.operator o - WHERE o.workerFk = vUserFk - AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL) - AND (c.itemPackingTypeFk = o.itemPackingTypeFk OR o.itemPackingTypeFk IS NULL) - AND o.numberOfWagons = c.wagons - AND o.trainFk = c.trainFk - AND o.warehouseFk = c.warehouseFk; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - -- Si hay colecciones sin terminar, sale del proceso - - CALL collection_get(vUserFk); - - SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, pc.maxNotAssignedCollectionLifeTime - INTO vHasTooMuchCollections, vMaxNotAssignedCollectionLifeTime - FROM productionConfig pc - LEFT JOIN tmp.collection ON TRUE; - - DROP TEMPORARY TABLE tmp.collection; - - IF vHasTooMuchCollections THEN - CALL util.throw('Hay colecciones pendientes'); - END IF; - - -- Se eliminan las colecciones sin asignar que estan obsoletas - - INSERT INTO ticketTracking(stateFk, ticketFk) - SELECT s.id, tc.ticketFk - FROM `collection` c - JOIN ticketCollection tc ON tc.collectionFk = c.id - JOIN `state` s ON s.code = 'PRINTED_AUTO' - WHERE c.workerFk IS NULL - AND TIMEDIFF(util.VN_NOW(), c.created) > vMaxNotAssignedCollectionLifeTime; - - DELETE FROM `collection` - WHERE workerFk IS NULL - AND TIMEDIFF(util.VN_NOW(), created) > vMaxNotAssignedCollectionLifeTime; - - -- Se añade registro al semillero - - INSERT INTO collectionHotbed(userFk) VALUES(vUserFk); - - -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion - - OPEN vCollections; - l: LOOP - SET vDone = FALSE; - FETCH vCollections INTO vCollectionFk; - - IF vDone THEN - LEAVE l; - END IF; - - BEGIN - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - SET vCollectionFk = NULL; - RESIGNAL; - END; - - START TRANSACTION; - - SELECT workerFk INTO vCollectionWorker - FROM `collection` - WHERE id = vCollectionFk FOR UPDATE; - - IF vCollectionWorker IS NULL THEN - UPDATE `collection` - SET workerFk = vUserFk - WHERE id = vCollectionFk; - - COMMIT; - LEAVE l; - END IF; - - ROLLBACK; - END; - END LOOP; - CLOSE vCollections; - - IF vCollectionFk IS NULL THEN - CALL collection_new(vUserFk, vCollectionFk); - - UPDATE `collection` - SET workerFk = vUserFk - WHERE id = vCollectionFk; - END IF; +BEGIN +/** + * Comprueba si existen colecciones libres que se ajustan + * al perfil del usuario y le asigna la más antigua. + * Añade un registro al semillero de colecciones. + * + * @param vUserFk Id de usuario + * @param vCollectionFk Id de colección + */ + DECLARE vHasTooMuchCollections BOOL; + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vCollectionWorker INT; + DECLARE vMaxNotAssignedCollectionLifeTime TIME; + + DECLARE vCollections CURSOR FOR + WITH collections AS ( + SELECT tc.collectionFk, + SUM(sv.volume) volume, + c.saleTotalCount, + c.itemPackingTypeFk, + c.trainFk, + c.warehouseFk, + c.wagons + FROM vn.ticketCollection tc + JOIN vn.collection c ON c.id = tc.collectionFk + JOIN vn.saleVolume sv ON sv.ticketFk = tc.ticketFk + WHERE c.workerFk IS NULL + AND sv.shipped >= util.VN_CURDATE() + GROUP BY tc.collectionFk + ) SELECT c.collectionFk + FROM collections c + JOIN vn.operator o + WHERE o.workerFk = vUserFk + AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL) + AND (c.itemPackingTypeFk = o.itemPackingTypeFk OR o.itemPackingTypeFk IS NULL) + AND o.numberOfWagons = c.wagons + AND o.trainFk = c.trainFk + AND o.warehouseFk = c.warehouseFk; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + -- Si hay colecciones sin terminar, sale del proceso + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + CALL collection_get(vUserFk); + + SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, pc.maxNotAssignedCollectionLifeTime + INTO vHasTooMuchCollections, vMaxNotAssignedCollectionLifeTime + FROM productionConfig pc + LEFT JOIN tmp.collection ON TRUE; + + DROP TEMPORARY TABLE tmp.collection; + + IF vHasTooMuchCollections THEN + CALL util.throw('Hay colecciones pendientes'); + END IF; + + -- Se eliminan las colecciones sin asignar que estan obsoletas + + INSERT INTO ticketTracking(stateFk, ticketFk) + SELECT s.id, tc.ticketFk + FROM `collection` c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN `state` s ON s.code = 'PRINTED_AUTO' + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > vMaxNotAssignedCollectionLifeTime; + + DELETE FROM `collection` + WHERE workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), created) > vMaxNotAssignedCollectionLifeTime; + + -- Se añade registro al semillero + + INSERT INTO collectionHotbed(userFk) VALUES(vUserFk); + + -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion + + OPEN vCollections; + l: LOOP + SET vDone = FALSE; + FETCH vCollections INTO vCollectionFk; + + IF vDone THEN + LEAVE l; + END IF; + + BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + SET vCollectionFk = NULL; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT workerFk INTO vCollectionWorker + FROM `collection` + WHERE id = vCollectionFk FOR UPDATE; + + IF vCollectionWorker IS NULL THEN + UPDATE `collection` + SET workerFk = vUserFk + WHERE id = vCollectionFk; + + COMMIT; + LEAVE l; + END IF; + + ROLLBACK; + END; + END LOOP; + CLOSE vCollections; + + IF vCollectionFk IS NULL THEN + CALL collection_new(vUserFk, vCollectionFk); + + START TRANSACTION; + + SELECT workerFk INTO vCollectionWorker + FROM `collection` + WHERE id = vCollectionFk FOR UPDATE; + + IF vCollectionWorker IS NULL THEN + UPDATE `collection` + SET workerFk = vUserFk + WHERE id = vCollectionFk; + END IF; + + COMMIT; + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51312,107 +51530,146 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `collection_getAssigned`( - vUserFk INT, - OUT vCollectionFk INT +CREATE DEFINER=`vn`@`localhost` PROCEDURE `collection_getAssigned`( + vUserFk INT, + OUT vCollectionFk INT ) -BEGIN -/** - * Comprueba si existen colecciones libres que se ajustan al perfil del usuario - * y le asigna la más antigua. - * Añade un registro al semillero de colecciones y hace la reserva para la colección - * - * @param vUserFk Id de usuario - * @param vCollectionFk Id de colección - */ - DECLARE vHasTooMuchCollections BOOL; - DECLARE vItemPackingTypeFk VARCHAR(1); - DECLARE vWarehouseFk INT; - DECLARE vLockName VARCHAR(215); - DECLARE vLockTime INT DEFAULT 30; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - IF vLockName IS NOT NULL THEN - DO RELEASE_LOCK(vLockName); - END IF; - - RESIGNAL; - END; - - -- Si hay colecciones sin terminar, sale del proceso - CALL collection_get(vUserFk); - - SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, - pc.collection_assign_lockname - INTO vHasTooMuchCollections, - vLockName - FROM tmp.collection c - JOIN productionConfig pc; - - DROP TEMPORARY TABLE tmp.collection; - - IF vHasTooMuchCollections THEN - CALL util.throw('There are pending collections'); - END IF; - - SELECT warehouseFk, itemPackingTypeFk - INTO vWarehouseFk, vItemPackingTypeFk - FROM operator - WHERE workerFk = vUserFk; - - SET vLockName = CONCAT_WS('/', - vLockName, - vWarehouseFk, - vItemPackingTypeFk - ); - - IF NOT GET_LOCK(vLockName, vLockTime) THEN - CALL util.throw(CONCAT('Cannot get lock: ', vLockName)); - END IF; - - -- Se eliminan las colecciones sin asignar que estan obsoletas - INSERT INTO ticketTracking(stateFk, ticketFk) - SELECT s.id, tc.ticketFk - FROM collection c - JOIN ticketCollection tc ON tc.collectionFk = c.id - JOIN state s ON s.code = 'PRINTED_AUTO' - JOIN productionConfig pc - WHERE c.workerFk IS NULL - AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; - - DELETE c - FROM collection c - JOIN productionConfig pc - WHERE c.workerFk IS NULL - AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; - - -- Se añade registro al semillero - INSERT INTO collectionHotbed - SET userFk = vUserFk; - - -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion - SELECT MIN(c.id) INTO vCollectionFk - FROM collection c - JOIN operator o ON (o.itemPackingTypeFk = c.itemPackingTypeFk - OR c.itemPackingTypeFk IS NULL) - AND o.numberOfWagons = c.wagons - AND o.trainFk = c.trainFk - AND o.warehouseFk = c.warehouseFk - AND c.workerFk IS NULL - WHERE o.workerFk = vUserFk; - - IF vCollectionFk IS NULL THEN - CALL collection_new(vUserFk, vCollectionFk); - END IF; - - UPDATE collection - SET workerFk = vUserFk - WHERE id = vCollectionFk; - - CALL itemShelvingSale_addByCollection(vCollectionFk); - - DO RELEASE_LOCK(vLockName); +BEGIN +/** + * Comprueba si existen colecciones libres que se ajustan + * al perfil del usuario y le asigna la más antigua. + * Añade un registro al semillero de colecciones. + * + * @param vUserFk Id de usuario + * @param vCollectionFk Id de colección + */ + DECLARE vHasTooMuchCollections BOOL; + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vCollectionWorker INT; + DECLARE vMaxNotAssignedCollectionLifeTime TIME; + + DECLARE vCollections CURSOR FOR + WITH collections AS ( + SELECT tc.collectionFk, + SUM(sv.volume) volume, + c.saleTotalCount, + c.itemPackingTypeFk, + c.trainFk, + c.warehouseFk, + c.wagons + FROM vn.ticketCollection tc + JOIN vn.collection c ON c.id = tc.collectionFk + JOIN vn.saleVolume sv ON sv.ticketFk = tc.ticketFk + WHERE c.workerFk IS NULL + AND sv.shipped >= util.VN_CURDATE() + GROUP BY tc.collectionFk + ) SELECT c.collectionFk + FROM collections c + JOIN vn.operator o + WHERE o.workerFk = vUserFk + AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL) + AND (c.itemPackingTypeFk = o.itemPackingTypeFk OR o.itemPackingTypeFk IS NULL) + AND o.numberOfWagons = c.wagons + AND o.trainFk = c.trainFk + AND o.warehouseFk = c.warehouseFk; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + -- Si hay colecciones sin terminar, sale del proceso + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + CALL collection_get(vUserFk); + + SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, pc.maxNotAssignedCollectionLifeTime + INTO vHasTooMuchCollections, vMaxNotAssignedCollectionLifeTime + FROM productionConfig pc + LEFT JOIN tmp.collection ON TRUE; + + DROP TEMPORARY TABLE tmp.collection; + + IF vHasTooMuchCollections THEN + CALL util.throw('Hay colecciones pendientes'); + END IF; + + -- Se eliminan las colecciones sin asignar que estan obsoletas + + INSERT INTO ticketTracking(stateFk, ticketFk) + SELECT s.id, tc.ticketFk + FROM `collection` c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN `state` s ON s.code = 'PRINTED_AUTO' + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > vMaxNotAssignedCollectionLifeTime; + + DELETE FROM `collection` + WHERE workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), created) > vMaxNotAssignedCollectionLifeTime; + + -- Se añade registro al semillero + + INSERT INTO collectionHotbed(userFk) VALUES(vUserFk); + + -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion + + OPEN vCollections; + l: LOOP + SET vDone = FALSE; + FETCH vCollections INTO vCollectionFk; + + IF vDone THEN + LEAVE l; + END IF; + + BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + SET vCollectionFk = NULL; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT workerFk INTO vCollectionWorker + FROM `collection` + WHERE id = vCollectionFk FOR UPDATE; + + IF vCollectionWorker IS NULL THEN + UPDATE `collection` + SET workerFk = vUserFk + WHERE id = vCollectionFk; + + COMMIT; + LEAVE l; + END IF; + + ROLLBACK; + END; + END LOOP; + CLOSE vCollections; + + IF vCollectionFk IS NULL THEN + CALL collection_new(vUserFk, vCollectionFk); + + START TRANSACTION; + + SELECT workerFk INTO vCollectionWorker + FROM `collection` + WHERE id = vCollectionFk FOR UPDATE; + + IF vCollectionWorker IS NULL THEN + UPDATE `collection` + SET workerFk = vUserFk + WHERE id = vCollectionFk; + END IF; + + COMMIT; + END IF; + CALL itemShelvingSale_addByCollection(vCollectionFk); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51451,9 +51708,8 @@ BEGIN SELECT tob.ticketFk, tob.description FROM vn.ticketObservation tob JOIN vn.ticketCollection tc ON tc.ticketFk = tob.ticketFk - LEFT JOIN vn.observationType ot ON ot.id = tob.observationTypeFk - WHERE ot.`code` = 'itemPicker' - AND tc.collectionFk = vParamFk OR tc.ticketFk = vParamFk + JOIN vn.observationType ot ON ot.id = tob.observationTypeFk AND ot.`code` = 'itemPicker' + WHERE tc.collectionFk = vParamFk OR tc.ticketFk = vParamFk ) SELECT t.id ticketFk, IF(!(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, @@ -51476,7 +51732,7 @@ BEGIN LEFT JOIN observation ob ON ob.ticketFk = t.id WHERE t.id = vParamFk AND t.shipped >= vYesterday - UNION ALL + UNION SELECT t.id ticketFk, IF(NOT(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, am.name agencyName, @@ -51497,7 +51753,7 @@ BEGIN LEFT JOIN vn.worker w ON w.id = c.salesPersonFk LEFT JOIN observation ob ON ob.ticketFk = t.id WHERE tc.collectionFk = vParamFk - UNION ALL + UNION SELECT sg.ticketFk, NULL `level`, am.name agencyName, @@ -51514,7 +51770,8 @@ BEGIN LEFT JOIN observation ob ON ob.ticketFk = t.id LEFT JOIN vn.client c ON c.id = t.clientFk WHERE sc.id = vParamFk - AND t.shipped >= vYesterday; + AND t.shipped >= vYesterday + GROUP BY ticketFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51683,7 +51940,10 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `collection_new`(vUserFk INT, OUT vCollectionFk INT) +CREATE DEFINER=`vn`@`localhost` PROCEDURE `collection_new`( + vUserFk INT, + OUT vCollectionFk INT +) BEGIN /** * Genera colecciones de tickets sin asignar trabajador. @@ -51696,30 +51956,29 @@ BEGIN DECLARE vLinesLimit INT; DECLARE vTicketLines INT; DECLARE vVolumeLimit DECIMAL; - DECLARE vTicketVolume DECIMAL; DECLARE vSizeLimit INT; + DECLARE vTicketVolume DECIMAL; DECLARE vMaxTickets INT; - DECLARE vStateFk VARCHAR(45); + DECLARE vStateCode VARCHAR(45); DECLARE vFirstTicketFk INT; - DECLARE vHour INT; - DECLARE vMinute INT; DECLARE vWorkerCode VARCHAR(3); - DECLARE vWagonCounter INT DEFAULT 0; + DECLARE vWagonCounter INT DEFAULT 1; DECLARE vTicketFk INT; DECLARE vItemPackingTypeFk VARCHAR(1); - DECLARE vHasAssignedTickets BOOLEAN; + DECLARE vHasAssignedTickets BOOL; DECLARE vHasUniqueCollectionTime BOOL; - DECLARE vDone INT DEFAULT FALSE; - DECLARE vLockName VARCHAR(215); - DECLARE vLockTime INT DEFAULT 30; + DECLARE vHeight INT; + DECLARE vVolume INT; + DECLARE vLiters INT; + DECLARE vLines INT; + DECLARE vTotalLines INT DEFAULT 0; + DECLARE vTotalVolume INT DEFAULT 0; DECLARE vFreeWagonFk INT; - DECLARE vErrorNumber INT; - DECLARE vErrorMsg TEXT; + DECLARE vDone INT DEFAULT FALSE; - DECLARE c1 CURSOR FOR + DECLARE vTickets CURSOR FOR SELECT ticketFk, `lines`, m3 FROM tmp.productionBuffer - WHERE ticketFk <> vFirstTicketFk ORDER BY HH, mm, productionOrder DESC, @@ -51732,26 +51991,6 @@ BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - GET DIAGNOSTICS CONDITION 1 - vErrorNumber = MYSQL_ERRNO, - vErrorMsg = MESSAGE_TEXT; - - CALL util.debugAdd('collection_new', JSON_OBJECT( - 'errorNumber', vErrorNumber, - 'errorMsg', vErrorMsg, - 'lockName', vLockName, - 'userFk', vUserFk, - 'ticketFk', vTicketFk - )); -- Tmp - - IF vLockName IS NOT NULL THEN - DO RELEASE_LOCK(vLockName); - END IF; - RESIGNAL; - END; - SELECT pc.ticketTrolleyMax * o.numberOfWagons, pc.hasUniqueCollectionTime, w.code, @@ -51762,36 +52001,26 @@ BEGIN o.trainFk, o.linesLimit, o.volumeLimit, - o.sizeLimit, - pc.collection_new_lockname + o.sizeLimit INTO vMaxTickets, - vHasUniqueCollectionTime, - vWorkerCode, - vWarehouseFk, - vItemPackingTypeFk, - vStateFk, - vWagons, - vTrainFk, - vLinesLimit, - vVolumeLimit, - vSizeLimit, - vLockName - FROM productionConfig pc - JOIN worker w ON w.id = vUserFk + vHasUniqueCollectionTime, + vWorkerCode, + vWarehouseFk, + vItemPackingTypeFk, + vStateCode, + vWagons, + vTrainFk, + vLinesLimit, + vVolumeLimit, + vSizeLimit + FROM worker w + JOIN operator o ON o.workerFk = w.id JOIN state st ON st.`code` = 'ON_PREPARATION' - JOIN operator o ON o.workerFk = vUserFk; - - SET vLockName = CONCAT_WS('/', - vLockName, - vWarehouseFk, - vItemPackingTypeFk - ); - - IF NOT GET_LOCK(vLockName, vLockTime) THEN - CALL util.throw(CONCAT('Cannot get lock: ', vLockName)); - END IF; + JOIN productionConfig pc + WHERE w.id = vUserFk; -- Se prepara el tren, con tantos vagones como sea necesario. + CREATE OR REPLACE TEMPORARY TABLE tTrain (wagon INT, shelve INT, @@ -51802,63 +52031,62 @@ BEGIN PRIMARY KEY(wagon, shelve)) ENGINE = MEMORY; - WHILE vWagons > vWagonCounter DO - SET vWagonCounter = vWagonCounter + 1; - - INSERT INTO tTrain(wagon, shelve, liters, `lines`, height) - SELECT vWagonCounter, cv.`level` , cv.liters , cv.`lines` , cv.height - FROM collectionVolumetry cv - WHERE cv.trainFk = vTrainFk + INSERT INTO tTrain (wagon, shelve, liters, `lines`, height) + WITH RECURSIVE wagonSequence AS ( + SELECT vWagonCounter wagon + UNION ALL + SELECT wagon + 1 wagon + FROM wagonSequence + WHERE wagon < vWagonCounter + vWagons -1 + ) + SELECT ws.wagon, cv.`level`, cv.liters, cv.`lines`, cv.height + FROM wagonSequence ws + JOIN vn.collectionVolumetry cv ON cv.trainFk = vTrainFk AND cv.itemPackingTypeFk = vItemPackingTypeFk; - END WHILE; -- Esto desaparecerá cuando tengamos la table cache.ticket + CALL productionControl(vWarehouseFk, 0); ALTER TABLE tmp.productionBuffer ADD COLUMN liters INT, ADD COLUMN height INT; - -- Se obtiene nº de colección. - INSERT INTO collection - SET itemPackingTypeFk = vItemPackingTypeFk, - trainFk = vTrainFk, - wagons = vWagons, - warehouseFk = vWarehouseFk; - - SELECT LAST_INSERT_ID() INTO vCollectionFk; - -- Los tickets de recogida en Algemesí sólo se sacan si están asignados. -- Los pedidos con riesgo no se sacan aunque se asignen. - DELETE pb.* + + DELETE pb FROM tmp.productionBuffer pb JOIN state s ON s.id = pb.state WHERE (pb.agency = 'REC_ALGEMESI' AND s.code <> 'PICKER_DESIGNED') OR pb.problem LIKE '%RIESGO%'; - -- Comprobamos si hay tickets asignados. En ese caso, nos centramos - -- exclusivamente en esos tickets y los sacamos independientemente - -- de problemas o tamaños - SELECT COUNT(*) INTO vHasAssignedTickets - FROM tmp.productionBuffer pb - JOIN state s ON s.id = pb.state - WHERE s.code = 'PICKER_DESIGNED' - AND pb.workerCode = vWorkerCode; + -- Si hay tickets asignados, nos centramos exclusivamente en esos tickets + -- y los sacamos independientemente de problemas o tamaños + + SELECT EXISTS ( + SELECT TRUE + FROM tmp.productionBuffer pb + JOIN state s ON s.id = pb.state + WHERE (s.code = 'PICKER_DESIGNED' + AND pb.workerCode = vWorkerCode) + OR s.code = 'LAST_CALL' + ) INTO vHasAssignedTickets; -- Se dejan en la tabla tmp.productionBuffer sólo aquellos tickets adecuados + IF vHasAssignedTickets THEN - DELETE pb.* + DELETE pb FROM tmp.productionBuffer pb JOIN state s ON s.id = pb.state - WHERE s.code <> 'PICKER_DESIGNED' - OR pb.workerCode <> vWorkerCode; + WHERE (s.code <> 'PICKER_DESIGNED' + OR pb.workerCode <> vWorkerCode) + AND s.code <> 'LAST_CALL'; ELSE - DELETE pb.* + DELETE pb FROM tmp.productionBuffer pb JOIN state s ON s.id = pb.state - JOIN agencyMode am ON am.id = pb.agencyModeFk - JOIN agency a ON a.id = am.agencyFk LEFT JOIN ( SELECT pb.ticketFk, MAX(i.`size`) maxSize FROM tmp.productionBuffer pb @@ -51869,7 +52097,7 @@ BEGIN ) sub ON sub.ticketFk = pb.ticketFk JOIN productionConfig pc WHERE pb.shipped <> util.VN_CURDATE() - OR (pb.ubicacion IS NULL AND a.isOwn) + OR pb.ubicacion IS NULL OR (NOT s.isPreparable AND NOT s.isPrintable) OR pb.collectionH IS NOT NULL OR pb.collectionV IS NOT NULL @@ -51877,26 +52105,25 @@ BEGIN OR (NOT pb.H AND pb.V > 0 AND vItemPackingTypeFk = 'H') OR (NOT pb.V AND vItemPackingTypeFk = 'V') OR (pc.isPreviousPreparationRequired AND pb.previousWithoutParking) - OR LENGTH(pb.problem) > 0 + OR LENGTH(pb.problem) OR pb.lines > vLinesLimit OR pb.m3 > vVolumeLimit OR sub.maxSize > vSizeLimit OR pb.hasPlantTray; END IF; - -- Es importante que el primer ticket se coja en todos los casos - SELECT ticketFk, - HH, - mm, - `lines`, - m3 - INTO vFirstTicketFk, - vHour, - vMinute, - vTicketLines, - vTicketVolume + -- Hay que excluir aquellos que no tengan la misma hora de preparacion, si procede + + IF vHasUniqueCollectionTime THEN + DELETE pb + FROM tmp.productionBuffer pb + JOIN tmp.productionBuffer pb2 ON pb2.ticketFk = vFirstTicketFk + AND (pb.HH <> pb2.HH OR pb.mm <> pb2.mm); + END IF; + + SELECT ticketFk INTO vFirstTicketFk FROM tmp.productionBuffer - ORDER BY HH, + ORDER BY HH, mm, productionOrder DESC, m3 DESC, @@ -51906,44 +52133,37 @@ BEGIN ticketFk LIMIT 1; - -- Hay que excluir aquellos que no tengan la misma hora de preparacion, si procede - IF vHasUniqueCollectionTime THEN - DELETE FROM tmp.productionBuffer - WHERE HH <> vHour - OR mm <> vMinute; - END IF; - - SET vTicketFk = vFirstTicketFk; - SET @lines = 0; - SET @volume = 0; - - OPEN c1; - read_loop: LOOP + OPEN vTickets; + l: LOOP SET vDone = FALSE; + FETCH vTickets INTO vTicketFk, vTicketLines, vTicketVolume; + + IF vDone THEN + LEAVE l; + END IF; -- Buscamos un ticket que cumpla con los requisitos en el listado - IF ((vTicketLines + @lines) <= vLinesLimit OR vLinesLimit IS NULL) - AND ((vTicketVolume + @volume) <= vVolumeLimit OR vVolumeLimit IS NULL) THEN + + IF (vLinesLimit IS NULL OR (vTotalLines + vTicketLines) <= vLinesLimit) + AND (vVolumeLimit IS NULL OR (vTotalVolume + vTicketVolume) <= vVolumeLimit) THEN CALL ticket_splitItemPackingType(vTicketFk, vItemPackingTypeFk); DROP TEMPORARY TABLE tmp.ticketIPT; + SELECT COUNT(*), SUM(litros), MAX(i.`size`), SUM(sv.volume) + INTO vLines, vLiters, vHeight, vVolume + FROM saleVolume sv + JOIN sale s ON s.id = sv.saleFk + JOIN item i ON i.id = s.itemFk + WHERE sv.ticketFk = vTicketFk; + + SET vTotalVolume = vTotalVolume + vVolume, + vTotalLines = vTotalLines + vLines; + UPDATE tmp.productionBuffer pb - JOIN ( - SELECT SUM(litros) liters, - @lines:= COUNT(*) + @lines, - COUNT(*) `lines`, - MAX(i.`size`) height, - @volume := SUM(sv.volume) + @volume, - SUM(sv.volume) volume - FROM saleVolume sv - JOIN sale s ON s.id = sv.saleFk - JOIN item i ON i.id = s.itemFk - WHERE sv.ticketFk = vTicketFk - ) sub - SET pb.liters = sub.liters, - pb.`lines` = sub.`lines`, - pb.height = sub.height + SET pb.liters = vLiters, + pb.`lines` = vLines, + pb.height = vHeight WHERE pb.ticketFk = vTicketFk; UPDATE tTrain tt @@ -51960,17 +52180,13 @@ BEGIN tt.height LIMIT 1; - -- Si no le encuentra una balda adecuada, intentamos darle un carro entero si queda alguno libre + -- Si no le encuentra una balda, intentamos darle un carro entero libre + IF NOT (SELECT COUNT(*) FROM tTrain WHERE ticketFk) THEN - SELECT tt.wagon - INTO vFreeWagonFk - FROM tTrain tt - LEFT JOIN ( - SELECT DISTINCT wagon - FROM tTrain - WHERE ticketFk IS NOT NULL - ) nn ON nn.wagon = tt.wagon - WHERE nn.wagon IS NULL + SELECT wagon INTO vFreeWagonFk + FROM tTrain + GROUP BY wagon + HAVING COUNT(ticketFk) = 0 ORDER BY wagon LIMIT 1; @@ -51979,38 +52195,35 @@ BEGIN SET ticketFk = vFirstTicketFk WHERE wagon = vFreeWagonFk; - -- Se anulan el resto de carros libres para que sólo uno lleve un pedido excesivo - DELETE tt.* - FROM tTrain tt - LEFT JOIN ( - SELECT DISTINCT wagon - FROM tTrain - WHERE ticketFk IS NOT NULL - ) nn ON nn.wagon = tt.wagon - WHERE nn.wagon IS NULL; - END IF; - END IF; + -- Se anulan el resto de carros libres, + -- máximo un carro con pedido excesivo - FETCH c1 INTO vTicketFk, vTicketLines, vTicketVolume; - IF vDone OR NOT (SELECT COUNT(*) FROM tTrain WHERE ticketFk IS NULL) THEN - LEAVE read_loop; - END IF; - ELSE - FETCH c1 INTO vTicketFk, vTicketLines, vTicketVolume; - IF vDone THEN - LEAVE read_loop; - END IF; + DELETE tt + FROM tTrain tt + JOIN (SELECT wagon + FROM tTrain + GROUP BY wagon + HAVING COUNT(ticketFk) = 0 + ) sub ON sub.wagon = tt.wagon; + END IF; + END IF; END IF; END LOOP; - CLOSE c1; + CLOSE vTickets; IF (SELECT COUNT(*) FROM tTrain WHERE ticketFk) THEN - UPDATE collection c - JOIN state st ON st.code = 'ON_PREPARATION' - SET c.stateFk = st.id - WHERE c.id = vCollectionFk; + -- Se obtiene nº de colección + + INSERT INTO collection + SET itemPackingTypeFk = vItemPackingTypeFk, + trainFk = vTrainFk, + wagons = vWagons, + warehouseFk = vWarehouseFk; + + SELECT LAST_INSERT_ID() INTO vCollectionFk; -- Asigna las bandejas + INSERT IGNORE INTO ticketCollection(ticketFk, collectionFk, `level`, wagon, liters) SELECT tt.ticketFk, vCollectionFk, tt.shelve, tt.wagon, tt.liters FROM tTrain tt @@ -52018,37 +52231,34 @@ BEGIN ORDER BY tt.wagon, tt.shelve; -- Actualiza el estado de los tickets - CALL collection_setState(vCollectionFk, vStateFk); + + CALL collection_setState(vCollectionFk, vStateCode); -- Aviso para la preparacion previa + INSERT INTO ticketDown(ticketFk, collectionFk) SELECT tc.ticketFk, tc.collectionFk FROM ticketCollection tc WHERE tc.collectionFk = vCollectionFk; - CALL sales_mergeByCollection(vCollectionFk); + CALL collection_mergeSales(vCollectionFk); UPDATE `collection` c - JOIN ( + JOIN( SELECT COUNT(*) saleTotalCount, SUM(s.isPicked <> 0) salePickedCount FROM ticketCollection tc JOIN sale s ON s.ticketFk = tc.ticketFk - WHERE tc.collectionFk = vCollectionFk - AND s.quantity > 0 - ) sub + WHERE tc.collectionFk = vCollectionFk + AND s.quantity > 0 + )sub SET c.saleTotalCount = sub.saleTotalCount, c.salePickedCount = sub.salePickedCount WHERE c.id = vCollectionFk; - ELSE - DELETE FROM `collection` - WHERE id = vCollectionFk; - SET vCollectionFk = NULL; + SET vCollectionFk = NULL; END IF; - DO RELEASE_LOCK(vLockName); - DROP TEMPORARY TABLE tTrain, tmp.productionBuffer; @@ -55362,22 +55572,26 @@ CREATE DEFINER=`vn`@`localhost` PROCEDURE `expeditionPallet_build`( vWorkerFk INT, OUT vPalletFk INT ) -BEGIN -/** Construye un pallet de expediciones. +proc: BEGIN +/** + * Builds an expedition pallet. * - * Primero comprueba si esas expediciones ya pertenecen a otro pallet, - * en cuyo caso actualiza ese pallet. + * First, it checks if these expeditions already belong to another pallet, + * in which case it returns an error. * - * @param vExpeditions JSON_ARRAY con esta estructura [exp1, exp2, exp3, ...] - * @param vArcId INT Identificador de arcRead - * @param vWorkerFk INT Identificador de worker - * @param out vPalletFk Identificador de expeditionPallet + * @param vExpeditions JSON_ARRAY with this structure [exp1, exp2, exp3, ...] + * @param vArcId INT Identifier of arcRead + * @param vWorkerFk INT Identifier of worker + * @param out vPalletFk Identifier of expeditionPallet */ + DECLARE vCounter INT; DECLARE vExpeditionFk INT; DECLARE vTruckFk INT; DECLARE vPrinterFk INT; DECLARE vExpeditionStateTypeFk INT; + DECLARE vFreeExpeditionCount INT; + DECLARE vExpeditionWithPallet INT; CREATE OR REPLACE TEMPORARY TABLE tExpedition ( expeditionFk INT, @@ -55401,48 +55615,63 @@ BEGIN WHERE e.id = vExpeditionFk; END WHILE; - SELECT palletFk INTO vPalletFk - FROM ( - SELECT palletFk, count(*) n - FROM tExpedition - WHERE palletFk > 0 - GROUP BY palletFk - ORDER BY n DESC - LIMIT 100 - ) sub - LIMIT 1; + SELECT COUNT(expeditionFk) INTO vFreeExpeditionCount + FROM tExpedition + WHERE palletFk IS NULL; - IF vPalletFk IS NULL THEN - SELECT roadmapStopFk INTO vTruckFk - FROM ( - SELECT rm.roadmapStopFk, count(*) n - FROM routesMonitor rm - JOIN tExpedition e ON e.routeFk = rm.routeFk - GROUP BY roadmapStopFk - ORDER BY n DESC - LIMIT 1 - ) sub; + SELECT COUNT(expeditionFk) INTO vExpeditionWithPallet + FROM tExpedition + WHERE palletFk; - IF vTruckFk IS NULL THEN - CALL util.throw ('TRUCK_NOT_AVAILABLE'); - END IF; - - INSERT INTO expeditionPallet SET truckFk = vTruckFk; - - SET vPalletFk = LAST_INSERT_ID(); + IF vExpeditionWithPallet THEN + UPDATE arcRead + SET error = ( + SELECT GROUP_CONCAT(expeditionFk SEPARATOR ', ') + FROM tExpedition + WHERE palletFk + ) + WHERE id = vArcId; + LEAVE proc; END IF; + IF NOT vFreeExpeditionCount THEN + CALL util.throw ('NO_FREE_EXPEDITIONS'); + END IF; + + SELECT roadmapStopFk INTO vTruckFk + FROM ( + SELECT rm.roadmapStopFk, count(*) n + FROM routesMonitor rm + JOIN tExpedition e ON e.routeFk = rm.routeFk + WHERE e.palletFk IS NULL + GROUP BY roadmapStopFk + ORDER BY n DESC + LIMIT 1 + ) sub; + + IF vTruckFk IS NULL THEN + CALL util.throw ('TRUCK_NOT_AVAILABLE'); + END IF; + + INSERT INTO expeditionPallet SET truckFk = vTruckFk; + + SET vPalletFk = LAST_INSERT_ID(); + INSERT INTO expeditionScan(expeditionFk, palletFk, workerFk) SELECT expeditionFk, vPalletFk, vWorkerFk FROM tExpedition - ON DUPLICATE KEY UPDATE palletFk = vPalletFk, workerFk = vWorkerFk; + WHERE palletFk IS NULL; SELECT id INTO vExpeditionStateTypeFk FROM expeditionStateType WHERE code = 'PALLETIZED'; - + INSERT INTO expeditionState(expeditionFk, typeFk) - SELECT expeditionFk, vExpeditionStateTypeFk FROM tExpedition; + SELECT expeditionFk, vExpeditionStateTypeFk + FROM tExpedition + WHERE palletFk IS NULL; + + UPDATE arcRead SET error = NULL WHERE id = vArcId; SELECT printerFk INTO vPrinterFk FROM arcRead WHERE id = vArcId; @@ -58550,6 +58779,75 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceOut_newFromAddress` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`vn`@`localhost` PROCEDURE `invoiceOut_newFromAddress`( + IN vAddressFk INT, + IN vSerial CHAR(2), + IN vMaxShipped DATE, + IN vCompanyFk INT, + IN vTaxArea VARCHAR(25), + IN vRef VARCHAR(25), + OUT vInvoiceId INT) +BEGIN +/** + * Factura los tickets de un consignatario hasta una fecha dada + * @param vAddressFk Id del consignatario a facturar + * @param vSerial Serie de factura + * @param vMaxShipped Fecha hasta la cual cogerá tickets para facturar + * @param vCompanyFk Id de la empresa desde la que se factura + * @param vTaxArea Tipo de iva en relacion a la empresa y al cliente, NULL por defecto + * @param vRef Referencia de la factura en caso que se quiera forzar, NULL por defecto + * @return vInvoiceId factura + */ + DECLARE vIsRefEditable BOOLEAN; + + IF vRef IS NOT NULL AND vSerial IS NOT NULL THEN + SELECT isRefEditable INTO vIsRefEditable + FROM invoiceOutSerial + WHERE code = vSerial; + + IF NOT vIsRefEditable THEN + CALL util.throw('serial non editable'); + END IF; + END IF; + + DROP TEMPORARY TABLE IF EXISTS `tmp`.`ticketToInvoice`; + CREATE TEMPORARY TABLE `tmp`.`ticketToInvoice` + (PRIMARY KEY (`id`)) + ENGINE = MEMORY + SELECT id FROM ticket t + WHERE t.addressFk = vAddressFk + AND t.refFk IS NULL + AND t.companyFk = vCompanyFk + AND t.shipped BETWEEN + util.firstDayOfYear(vMaxShipped - INTERVAL 1 YEAR) + AND util.dayend(vMaxShipped); + + CALL invoiceOut_new(vSerial, util.VN_CURDATE(), vTaxArea, vInvoiceId); + + UPDATE invoiceOut + SET `ref` = vRef + WHERE id = vInvoiceId + AND vRef IS NOT NULL; + + IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN + CALL invoiceOutBooking(vInvoiceId); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `invoiceOut_newFromClient` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -58739,6 +59037,73 @@ ELSE INSERT INTO vn.itemBarcode(itemFk,code) VALUES (vItemFk,vCode); END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemCampaign_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemCampaign_add`() +proc: BEGIN +/** + * Añade registros a tabla itemCampaign. + * + * @param vDateFrom Fecha desde + * @param vDateTo Fecha hasta + * @param vCampaign Código de la campaña + */ + DECLARE vYesterday DATE; + DECLARE vCampaign VARCHAR(100); + DECLARE vScopeDays INT; + DECLARE vPreviousDays INT; + DECLARE vDateSumFrom DATE; + DECLARE vDateSumTo DATE; + + SET vYesterday = util.yesterday(); + + SELECT dated, code, scopeDays, previousDays + INTO vDateSumTo, vCampaign, vScopeDays, vPreviousDays + FROM campaign + WHERE dated >= vYesterday + ORDER BY dated + LIMIT 1; + + IF vCampaign IS NULL THEN + CALL util.throw('Missing data in campaign table'); + END IF; + + IF NOT vYesterday BETWEEN vDateSumTo - INTERVAL vPreviousDays DAY + AND vDateSumTo THEN + LEAVE proc; + END IF; + + SET vDateSumFrom = vDateSumTo - INTERVAL vScopeDays DAY; + SET vDateSumTo = vDateSumTo - INTERVAL 1 DAY; + + INSERT INTO itemCampaign(dated, itemFk, quantity, total, campaign) + SELECT vYesterday, + s.itemFk, + SUM(s.quantity) quantity, + SUM((s.quantity * s.price) * (100 - s.discount) / 100) total, + vCampaign + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN client c ON c.id = t.clientFk + WHERE t.shipped BETWEEN vDateSumFrom AND util.dayEnd(vDateSumTo) + AND c.typeFk = 'normal' + AND NOT t.isDeleted + GROUP BY s.itemFk + HAVING quantity; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -59685,53 +60050,53 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelvingSale_addByCollection`( - vCollectionFk INT(11) +CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelvingSale_addByCollection`( + vCollectionFk INT(11) ) -BEGIN -/** - * Reserva cantidades con ubicaciones para el contenido de una colección - * - * @param vCollectionFk Identificador de collection - */ - DECLARE vDone BOOL DEFAULT FALSE; - DECLARE vSaleFk INT; - DECLARE vSales CURSOR FOR - WITH sales AS ( - SELECT s.id saleFk, s.quantity, SUM(IFNULL(iss.quantity, 0)) quantityReserved - FROM vn.ticketCollection tc - JOIN vn.sale s ON s.ticketFk = tc.ticketFk - LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id - WHERE tc.collectionFk = vCollectionFk - GROUP BY s.id - HAVING quantity <> quantityReserved - ), trackedSales AS ( - SELECT sa.saleFk - FROM sales sa - JOIN vn.saleTracking st ON st.saleFk = sa.saleFk - JOIN vn.`state` s ON s.id = st.stateFk - WHERE st.isChecked - AND s.`code` IN ('PREVIOUS_PREPARATION', 'OK PREVIOUS', 'OK STOWAWAY') - GROUP BY sa.saleFk - ) SELECT s.saleFk - FROM sales s - LEFT JOIN trackedSales ts ON ts.saleFk = s.saleFk - WHERE ts.saleFk IS NULL; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - OPEN vSales; - l: LOOP - SET vDone = FALSE; - FETCH vSales INTO vSaleFk; - - IF vDone THEN - LEAVE l; - END IF; - - CALL itemShelvingSale_addBySale(vSaleFk, NULL); - END LOOP; - CLOSE vSales; +BEGIN +/** + * Reserva cantidades con ubicaciones para el contenido de una colección + * + * @param vCollectionFk Identificador de collection + */ + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vSaleFk INT; + DECLARE vSales CURSOR FOR + WITH sales AS ( + SELECT s.id saleFk, s.quantity, SUM(IFNULL(iss.quantity, 0)) quantityReserved + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id + WHERE tc.collectionFk = vCollectionFk + GROUP BY s.id + HAVING quantity <> quantityReserved + ), trackedSales AS ( + SELECT sa.saleFk + FROM sales sa + JOIN vn.saleTracking st ON st.saleFk = sa.saleFk + JOIN vn.`state` s ON s.id = st.stateFk + WHERE st.isChecked + AND s.`code` IN ('PREVIOUS_PREPARATION', 'OK PREVIOUS', 'OK STOWAWAY') + GROUP BY sa.saleFk + ) SELECT s.saleFk + FROM sales s + LEFT JOIN trackedSales ts ON ts.saleFk = s.saleFk + WHERE ts.saleFk IS NULL; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + OPEN vSales; + l: LOOP + SET vDone = FALSE; + FETCH vSales INTO vSaleFk; + + IF vDone THEN + LEAVE l; + END IF; + + CALL itemShelvingSale_addBySale(vSaleFk, NULL); + END LOOP; + CLOSE vSales; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -59767,8 +60132,9 @@ proc: BEGIN DECLARE vReservedQuantity INT; DECLARE vOutStanding INT; DECLARE vUserFk INT; - DECLARE vTotalReservedQuantity INT; + DECLARE vTotalReservedQuantity INT; DECLARE vSaleQuantity INT; + DECLARE vIsRequiredTx BOOL DEFAULT NOT @@in_transaction; DECLARE vItemShelvingAvailable CURSOR FOR SELECT ish.id itemShelvingFk, @@ -59778,7 +60144,7 @@ proc: BEGIN JOIN shelving sh ON sh.code = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk JOIN sector sc ON sc.id = p.sectorFk - JOIN productionConfig pc + JOIN productionConfig pc WHERE s.id = vSaleFk AND NOT sc.isHideForPickers AND (sc.id = vSectorFk OR vSectorFk IS NULL) @@ -59793,15 +60159,15 @@ proc: BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - ROLLBACK; + CALL util.tx_rollback(vIsRequiredTx); RESIGNAL; END; - - START TRANSACTION; - + + CALL util.tx_start(vIsRequiredTx); + SELECT id INTO vSaleFk FROM sale - WHERE id = vSaleFk + WHERE id = vSaleFk FOR UPDATE; SELECT MAX(p.pickingOrder), s.quantity - SUM(IFNULL(iss.quantity, 0)), s.quantity @@ -59814,7 +60180,7 @@ proc: BEGIN WHERE s.id = vSaleFk; IF vOutStanding <= 0 THEN - COMMIT; + CALL util.tx_commit(vIsRequiredTx); LEAVE proc; END IF; @@ -59834,7 +60200,7 @@ proc: BEGIN IF vTotalReservedQuantity <> vSaleQuantity THEN CALL util.debugAdd('itemShelvingSale_addBySale', CONCAT(vSaleFk, ' - ', vSaleQuantity,' - ', vTotalReservedQuantity,'-', vOutStanding,'-', account.myUser_getId())); - + UPDATE sale SET quantity = vTotalReservedQuantity WHERE id = vSaleFk; @@ -59842,7 +60208,7 @@ proc: BEGIN LEAVE l; END IF; - SELECT id INTO vItemShelvingFk + SELECT id INTO vItemShelvingFk FROM itemShelving WHERE id = vItemShelvingFk FOR UPDATE; @@ -59851,19 +60217,19 @@ proc: BEGIN SET vOutStanding = vOutStanding - vReservedQuantity; IF vReservedQuantity > 0 THEN - CALL util.debugAdd('itemShelvingSale_addBySale_reservedQuantity', - CONCAT(vSaleFk, ' - ', vReservedQuantity, ' - ', vOutStanding, account.myUser_getId())); - INSERT INTO itemShelvingSale( - itemShelvingFk, - saleFk, - quantity, - userFk, - isPicked) - SELECT vItemShelvingFk, - vSaleFk, - vReservedQuantity, - vUserFk, - FALSE; + CALL util.debugAdd('itemShelvingSale_addBySale_reservedQuantity', + CONCAT(vSaleFk, ' - ', vReservedQuantity, ' - ', vOutStanding, account.myUser_getId())); + INSERT INTO itemShelvingSale( + itemShelvingFk, + saleFk, + quantity, + userFk, + isPicked) + SELECT vItemShelvingFk, + vSaleFk, + vReservedQuantity, + vUserFk, + FALSE; UPDATE itemShelving SET available = available - vReservedQuantity @@ -59872,7 +60238,7 @@ proc: BEGIN END IF; END LOOP; CLOSE vItemShelvingAvailable; - COMMIT; + CALL util.tx_commit(vIsRequiredTx); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60000,6 +60366,68 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_deleteAdded` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelvingSale_deleteAdded`( + vSelf INT(11) +) +proc: BEGIN +/** + * Borra una reservea devolviendo la cantidad al itemShelving + * + * @param vSelf Identificador del itemShelvingSale + */ + DECLARE vSaleFk INT; + DECLARE vHasSalesPicked BOOL; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT iss.saleFk INTO vSaleFk + FROM itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + WHERE iss.id = vSelf AND s.isAdded + FOR UPDATE; + + IF vSaleFk IS NULL THEN + CALL util.throw('The sale can not be deleted'); + END IF; + + SELECT COUNT(*) INTO vHasSalesPicked + FROM itemShelvingSale + WHERE saleFk = vSaleFk AND isPicked; + + IF vHasSalesPicked THEN + CALL util.throw('A sale with picked sales cannot be deleted'); + END IF; + + UPDATE itemShelvingSale iss + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + SET ish.available = ish.available + iss.quantity + WHERE iss.saleFk = vSaleFk; + + DELETE FROM sale WHERE id = vSaleFk; + + COMMIT; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_doReserve` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -60009,56 +60437,56 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelvingSale_doReserve`() -proc: BEGIN -/** - * Genera reservas de la tabla vn.itemShelvingSaleReserve - */ - DECLARE vDone BOOL; - DECLARE vSaleFk INT; - DECLARE vSectorFk INT; - - DECLARE vSales CURSOR FOR - SELECT DISTINCT saleFk, sectorFk FROM tSale; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - DECLARE CONTINUE HANDLER FOR SQLEXCEPTION - BEGIN - DO RELEASE_LOCK('vn.itemShelvingSale_doReserve'); - ROLLBACK; - RESIGNAL; - END; - - IF !GET_LOCK('vn.itemShelvingSale_doReserve', 0) THEN - LEAVE proc; - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tSale - ENGINE = MEMORY - SELECT id, saleFk, sectorFk FROM itemShelvingSaleReserve; - - OPEN vSales; - - myLoop: LOOP - SET vDone = FALSE; - FETCH vSales INTO vSaleFk, vSectorFk; - - IF vDone THEN - LEAVE myLoop; - END IF; - - CALL itemShelvingSale_addBySale (vSaleFk, vSectorFk); - END LOOP; - - CLOSE vSales; - - DELETE iss FROM itemShelvingSaleReserve iss - JOIN tSale s ON s.id = iss.id AND s.sectorFk = iss.sectorFk; - - DROP TEMPORARY TABLE tSale; - - DO RELEASE_LOCK('vn.itemShelvingSale_doReserve'); +proc: BEGIN +/** + * Genera reservas de la tabla vn.itemShelvingSaleReserve + */ + DECLARE vDone BOOL; + DECLARE vSaleFk INT; + DECLARE vSectorFk INT; + + DECLARE vSales CURSOR FOR + SELECT DISTINCT saleFk, sectorFk FROM tSale; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('vn.itemShelvingSale_doReserve'); + ROLLBACK; + RESIGNAL; + END; + + IF !GET_LOCK('vn.itemShelvingSale_doReserve', 0) THEN + LEAVE proc; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tSale + ENGINE = MEMORY + SELECT id, saleFk, sectorFk FROM itemShelvingSaleReserve; + + OPEN vSales; + + myLoop: LOOP + SET vDone = FALSE; + FETCH vSales INTO vSaleFk, vSectorFk; + + IF vDone THEN + LEAVE myLoop; + END IF; + + CALL itemShelvingSale_addBySale (vSaleFk, vSectorFk); + END LOOP; + + CLOSE vSales; + + DELETE iss FROM itemShelvingSaleReserve iss + JOIN tSale s ON s.id = iss.id AND s.sectorFk = iss.sectorFk; + + DROP TEMPORARY TABLE tSale; + + DO RELEASE_LOCK('vn.itemShelvingSale_doReserve'); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60143,37 +60571,37 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelvingSale_setPicked`( - vSaleGroupFk INT(10) +CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelvingSale_setPicked`( + vSaleGroupFk INT(10) ) -BEGIN -/** - * Gestiona la reserva de un vn.saleGroup actualizando vn.itemShelvingSale.isPicked - * y cambiando el estado de la vn.sale - * - * @param vSaleGroupFk Id saleGroupFk - */ - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - IF NOT (SELECT COUNT(*) FROM saleGroup WHERE id = vSaleGroupFk) THEN - CALL util.throw('Sale group not exists'); - END IF; - - START TRANSACTION; - - UPDATE itemShelvingSale iss - JOIN sale s ON s.id = iss.saleFk - JOIN saleGroupDetail sg ON sg.saleFk = s.id - SET iss.isPicked = TRUE - WHERE sg.saleGroupFk = vSaleGroupFk; - - CALL saleTracking_addPreparedSaleGroup(vSaleGroupFk); - - COMMIT; +BEGIN +/** + * Gestiona la reserva de un vn.saleGroup actualizando vn.itemShelvingSale.isPicked + * y cambiando el estado de la vn.sale + * + * @param vSaleGroupFk Id saleGroupFk + */ + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF NOT (SELECT COUNT(*) FROM saleGroup WHERE id = vSaleGroupFk) THEN + CALL util.throw('Sale group not exists'); + END IF; + + START TRANSACTION; + + UPDATE itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + JOIN saleGroupDetail sg ON sg.saleFk = s.id + SET iss.isPicked = TRUE + WHERE sg.saleGroupFk = vSaleGroupFk; + + CALL saleTracking_addPreparedSaleGroup(vSaleGroupFk); + + COMMIT; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60190,114 +60618,114 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelvingSale_setQuantity`( - vItemShelvingSaleFk INT(10), - vQuantity DECIMAL(10,0), - vIsItemShelvingSaleEmpty BOOLEAN, - vSectorFk INT +CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelvingSale_setQuantity`( + vItemShelvingSaleFk INT(10), + vQuantity DECIMAL(10,0), + vIsItemShelvingSaleEmpty BOOLEAN, + vSectorFk INT ) -BEGIN -/** - * Gestiona la reserva de un itemShelvingFk, actualizando isPicked y quantity - * en itemShelvingSale y sale.isPicked en caso necesario. - * Si la reserva de la ubicación es fallida, se regulariza la situación - * - * @param vItemShelvingSaleFk Id itemShelvingSaleFK - * @param vQuantity Cantidad real que se ha cogido de la ubicación - * @param vIsItemShelvingSaleEmpty determina si la ubicación itemShelvingSale se ha - * quedado vacio tras el movimiento - * @param vSectorFk Id del sector - */ - DECLARE vSaleFk INT; - DECLARE vItemShelvingFk INT; - DECLARE vReservedQuantity INT; - DECLARE vRemainingQuantity INT; - DECLARE vItemFk INT; - DECLARE vTotalQuantity INT; - DECLARE vStateCode VARCHAR(45); - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - IF vQuantity > vReservedQuantity - OR (vQuantity < vReservedQuantity AND NOT vIsItemShelvingSaleEmpty) - OR (vQuantity = vReservedQuantity AND vIsItemShelvingSaleEmpty) THEN - CALL util.throw('The quantity cannot be different from the reserved'); - END IF; - - IF (SELECT isPicked FROM itemShelvingSale WHERE id = vItemShelvingSaleFk) THEN - CALL util.throw('Reservation completed'); - END IF; - - SELECT s.itemFk, - iss.saleFk, - iss.itemShelvingFk, - SUM(IFNULL(iss.quantity,0)), - IF(sgd.id, 'PREVIOUS_PREPARATION', 'PREPARED') - INTO vItemFk, - vSaleFk, - vItemShelvingFk, - vReservedQuantity, - vStateCode - FROM itemShelvingSale iss - JOIN sale s ON s.id = iss.saleFk - LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleFk = iss.saleFk - WHERE iss.id = vItemShelvingSaleFk - AND NOT iss.isPicked; - - IF vQuantity > vReservedQuantity - OR (vQuantity < vReservedQuantity AND NOT vIsItemShelvingSaleEmpty) - OR (vQuantity = vReservedQuantity AND vIsItemShelvingSaleEmpty) THEN - CALL util.throw('The quantity cannot be different from the reserved'); - END IF; - - START TRANSACTION; - - UPDATE itemShelvingSale - SET isPicked = TRUE, - quantity = vQuantity - WHERE id = vItemShelvingSaleFk; - - SELECT id INTO vItemShelvingFk - FROM itemShelving - WHERE id = vItemShelvingFk - FOR UPDATE; - - UPDATE itemShelving - SET visible = GREATEST(0, visible - vQuantity) - WHERE id = vItemShelvingFk; - - SELECT SUM(IF(isPicked OR id = vItemShelvingSaleFk, 0, quantity)), SUM(quantity) - INTO vRemainingQuantity, vTotalQuantity - FROM itemShelvingSale - WHERE saleFk = vSaleFk; - - IF vRemainingQuantity = 0 AND NOT vIsItemShelvingSaleEmpty THEN - CALL saleTracking_new( - vSaleFk, - TRUE, - vTotalQuantity, - `account`.`myUser_getId`(), - NULL, - vStateCode, - TRUE); - - UPDATE sale s - SET s.quantity = vTotalQuantity, - isPicked = TRUE - WHERE s.id = vSaleFk; - END IF; - - COMMIT; - - IF vIsItemShelvingSaleEmpty AND vQuantity <> vReservedQuantity THEN - INSERT INTO itemShelvingSaleReserve (saleFk, sectorFk) - SELECT vSaleFk, vSectorFk; - CALL itemShelvingSale_reallocate(vItemShelvingFk, vItemFk, vSectorFk); - END IF; +BEGIN +/** + * Gestiona la reserva de un itemShelvingFk, actualizando isPicked y quantity + * en itemShelvingSale y sale.isPicked en caso necesario. + * Si la reserva de la ubicación es fallida, se regulariza la situación + * + * @param vItemShelvingSaleFk Id itemShelvingSaleFK + * @param vQuantity Cantidad real que se ha cogido de la ubicación + * @param vIsItemShelvingSaleEmpty determina si la ubicación itemShelvingSale se ha + * quedado vacio tras el movimiento + * @param vSectorFk Id del sector + */ + DECLARE vSaleFk INT; + DECLARE vItemShelvingFk INT; + DECLARE vReservedQuantity INT; + DECLARE vRemainingQuantity INT; + DECLARE vItemFk INT; + DECLARE vTotalQuantity INT; + DECLARE vStateCode VARCHAR(45); + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF vQuantity > vReservedQuantity + OR (vQuantity < vReservedQuantity AND NOT vIsItemShelvingSaleEmpty) + OR (vQuantity = vReservedQuantity AND vIsItemShelvingSaleEmpty) THEN + CALL util.throw('The quantity cannot be different from the reserved'); + END IF; + + IF (SELECT isPicked FROM itemShelvingSale WHERE id = vItemShelvingSaleFk) THEN + CALL util.throw('Reservation completed'); + END IF; + + SELECT s.itemFk, + iss.saleFk, + iss.itemShelvingFk, + SUM(IFNULL(iss.quantity,0)), + IF(sgd.id, 'PREVIOUS_PREPARATION', 'PREPARED') + INTO vItemFk, + vSaleFk, + vItemShelvingFk, + vReservedQuantity, + vStateCode + FROM itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleFk = iss.saleFk + WHERE iss.id = vItemShelvingSaleFk + AND NOT iss.isPicked; + + IF vQuantity > vReservedQuantity + OR (vQuantity < vReservedQuantity AND NOT vIsItemShelvingSaleEmpty) + OR (vQuantity = vReservedQuantity AND vIsItemShelvingSaleEmpty) THEN + CALL util.throw('The quantity cannot be different from the reserved'); + END IF; + + START TRANSACTION; + + UPDATE itemShelvingSale + SET isPicked = TRUE, + quantity = vQuantity + WHERE id = vItemShelvingSaleFk; + + SELECT id INTO vItemShelvingFk + FROM itemShelving + WHERE id = vItemShelvingFk + FOR UPDATE; + + UPDATE itemShelving + SET visible = GREATEST(0, visible - vQuantity) + WHERE id = vItemShelvingFk; + + SELECT SUM(IF(isPicked OR id = vItemShelvingSaleFk, 0, quantity)), SUM(quantity) + INTO vRemainingQuantity, vTotalQuantity + FROM itemShelvingSale + WHERE saleFk = vSaleFk; + + IF vRemainingQuantity = 0 AND NOT vIsItemShelvingSaleEmpty THEN + CALL saleTracking_new( + vSaleFk, + TRUE, + vTotalQuantity, + `account`.`myUser_getId`(), + NULL, + vStateCode, + TRUE); + + UPDATE sale s + SET s.quantity = vTotalQuantity, + isPicked = TRUE + WHERE s.id = vSaleFk; + END IF; + + COMMIT; + + IF vIsItemShelvingSaleEmpty AND vQuantity <> vReservedQuantity THEN + INSERT INTO itemShelvingSaleReserve (saleFk, sectorFk) + SELECT vSaleFk, vSectorFk; + CALL itemShelvingSale_reallocate(vItemShelvingFk, vItemFk, vSectorFk); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60314,63 +60742,63 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelvingSale_unpicked`( - vSelf INT(11) +CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelvingSale_unpicked`( + vSelf INT(11) ) -BEGIN -/** - * Desmarca una línea que ya estaba sacada, devolviendo la cantidad al itemShelving - * - * @param vSelf Identificador del itemShelvingSale - */ - DECLARE vSaleFk INT; - DECLARE vReservedQuantity INT; - DECLARE vIsSaleGroup BOOL; - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - IF (SELECT NOT isPicked FROM itemShelvingSale WHERE id = vSelf) THEN - CALL util.throw('Reserva no completada'); - END IF; - - SELECT ish.saleFk, ish.quantity, IF(sg.id, TRUE, FALSE) - INTO vSaleFk, vReservedQuantity, vIsSaleGroup - FROM itemShelvingSale ish - LEFT JOIN saleGroupDetail sg ON sg.saleFk = ish.saleFk - WHERE ish.id = vSelf; - - /*IF vIsSaleGroup THEN - CALL util.throw('Can not unpicked a sale group'); - END IF;*/ - - START TRANSACTION; - - UPDATE itemShelvingSale - SET isPicked = FALSE - WHERE id = vSelf; - - UPDATE sale s - JOIN itemShelvingSale ish ON ish.saleFk = s.id - SET s.isPicked = FALSE - WHERE ish.id = vSelf; - - UPDATE itemShelvingSale iss - JOIN itemShelving ish ON ish.id = iss.itemShelvingFk - SET ish.visible = ish.visible + iss.quantity - WHERE iss.id = vSelf; - - CALL saleTracking_new( - vSaleFk, - FALSE, - vReservedQuantity, - `account`.`myUser_getId`(), - NULL, - 'ON_PREPARATION', - TRUE); - COMMIT; +BEGIN +/** + * Desmarca una línea que ya estaba sacada, devolviendo la cantidad al itemShelving + * + * @param vSelf Identificador del itemShelvingSale + */ + DECLARE vSaleFk INT; + DECLARE vReservedQuantity INT; + DECLARE vIsSaleGroup BOOL; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF (SELECT NOT isPicked FROM itemShelvingSale WHERE id = vSelf) THEN + CALL util.throw('Reserva no completada'); + END IF; + + SELECT ish.saleFk, ish.quantity, IF(sg.id, TRUE, FALSE) + INTO vSaleFk, vReservedQuantity, vIsSaleGroup + FROM itemShelvingSale ish + LEFT JOIN saleGroupDetail sg ON sg.saleFk = ish.saleFk + WHERE ish.id = vSelf; + + /*IF vIsSaleGroup THEN + CALL util.throw('Can not unpicked a sale group'); + END IF;*/ + + START TRANSACTION; + + UPDATE itemShelvingSale + SET isPicked = FALSE + WHERE id = vSelf; + + UPDATE sale s + JOIN itemShelvingSale ish ON ish.saleFk = s.id + SET s.isPicked = FALSE + WHERE ish.id = vSelf; + + UPDATE itemShelvingSale iss + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + SET ish.visible = ish.visible + iss.quantity + WHERE iss.id = vSelf; + + CALL saleTracking_new( + vSaleFk, + FALSE, + vReservedQuantity, + `account`.`myUser_getId`(), + NULL, + 'ON_PREPARATION', + TRUE); + COMMIT; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60517,18 +60945,24 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelving_addList`(vShelvingFk VARCHAR(3), vList TEXT, vIsChecking BOOL, vWarehouseFk INT) +CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelving_addList`( + vShelvingFk VARCHAR(3), + vList TEXT, + vIsChecking BOOL, + vWarehouseFk INT +) BEGIN -/* Recorre cada elemento en la colección vList. +/** + * Recorre cada elemento en la colección vList. * Si el parámetro isChecking = FALSE, llama a itemShelving_add. * * Cuando es TRUE sólo inserta los elementos de la colección que no están ya en - * ese shelving, actualizando los valores del campo vn.itemShelving.isChecked + * ese shelving, actualizando los valores del campo itemShelving.isChecked * - * param vShelvingFk Identificador de vn.shelving - * param vList JSON array con esta estructura: '[value1, value2, ...]' - * param vIsChecking Define si hay que añadir o comprobar los items - * param vWarehouseFk Identificador de vn.warehouse + * @param vShelvingFk Identificador de shelving + * @param vList JSON array con esta estructura: '[value1, value2, ...]' + * @param vIsChecking Define si hay que añadir o comprobar los items + * @param vWarehouseFk Identificador de warehouse */ DECLARE vListLength INT DEFAULT JSON_LENGTH(vList); DECLARE vCounter INT DEFAULT 0; @@ -60538,26 +60972,27 @@ BEGIN DECLARE vIsChecked BOOL; WHILE vCounter < vListLength DO - SET vPath = CONCAT('$[',vCounter,']'); - SET vBarcode = JSON_EXTRACT(vList,vPath); + SET vPath = CONCAT('$[', vCounter, ']'); + SET vBarcode = JSON_EXTRACT(vList, vPath); SET vIsChecked = NULL; IF vIsChecking THEN SELECT barcodeToItem(vBarcode) INTO vItemFk; - SELECT COUNT(*) INTO vIsChecked - FROM vn.itemShelving + SELECT IF(COUNT(*), TRUE, FALSE) INTO vIsChecked + FROM itemShelving WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk; END IF; - IF NOT (vIsChecking AND vIsChecked) THEN - CALL vn.itemShelving_add(vShelvingFk, vBarcode, 1, NULL, NULL, NULL, vWarehouseFk); + IF NOT vIsChecking OR NOT vIsChecked THEN + CALL itemShelving_add(vShelvingFk, vBarcode, 1, NULL, NULL, NULL, vWarehouseFk); END IF; - UPDATE vn.itemShelving + UPDATE itemShelving SET isChecked = vIsChecked WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk - AND itemFk = vItemFk AND isChecked IS NULL; + AND itemFk = vItemFk + AND isChecked IS NULL; SET vCounter = vCounter + 1; END WHILE; @@ -60858,167 +61293,167 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelving_getSaleDate`(vShelvingFk VARCHAR(3)) -BEGIN - - /* Devuelve la mínima fecha en que se necesita cada producto en esa matrícula. - * - * @param vShelvingFk Matrícula del carro o pallet - */ - - DECLARE vWarehouseFk INT; - DECLARE vStockScopeDays INT; - - SELECT s.warehouseFk, stockScopeDays - INTO vWarehouseFk, vStockScopeDays - FROM sector s - JOIN operator o ON s.id = o.sectorFk - JOIN productionConfig pc - WHERE o.workerFk = account.myUser_getId(); - - IF vWarehouseFk IS NULL - THEN CALL util.throw('WarehouseFk not setted'); - END IF; - - IF vStockScopeDays IS NULL - THEN CALL util.throw('StockScopeDays not setted'); - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tmp.tItems - (PRIMARY KEY (itemFk)) - ENGINE = MEMORY - SELECT itemFk, SUM(visible) visible - FROM itemShelving - WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci - GROUP BY itemFk; - - CREATE OR REPLACE TEMPORARY TABLE tmp.tStockByDay - (INDEX (itemFk, dated)) - ENGINE = MEMORY - SELECT dated, - SUM(t3.amount) OVER (PARTITION BY t3.itemFk ORDER BY dated) stock, - t3.itemFk - FROM ( - SELECT t.itemFk, dated, SUM(amount) amount - FROM ( - SELECT t2.itemFk, t2.amount, t2.dated - FROM ( - SELECT item_id itemFk, amount, util.VN_CURDATE() dated - FROM cache.stock s - JOIN tmp.tItems i ON i.itemFk = s.item_id - WHERE s.warehouse_id = vWarehouseFk - UNION ALL - SELECT ish.itemFk, - SUM(ish.visible), util.VN_CURDATE() - FROM itemShelving ish - JOIN tmp.tItems i ON i.itemFk = ish.itemFk - JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON sh.parkingFk = p.id - JOIN sector s ON s.id = p.sectorFk - WHERE s.isReserve - GROUP BY ish.itemFk - UNION ALL - SELECT iei.itemFk, SUM(quantity), landed - FROM itemEntryIn iei - JOIN tmp.tItems i ON i.itemFk = iei.itemFk - WHERE iei.landed BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY - AND iei.warehouseInFk = vWarehouseFk - AND NOT isVirtualStock - GROUP BY iei.itemFk, iei.landed - UNION ALL - SELECT ieo.itemFk, SUM(quantity), shipped - FROM itemEntryOut ieo - JOIN tmp.tItems i ON i.itemFk = ieo.itemFk - WHERE ieo.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY - AND ieo.warehouseOutFk = vWarehouseFk - GROUP BY ieo.itemFk, ieo.shipped - UNION ALL - SELECT i.itemFk, SUM(ito.quantity), DATE(ito.shipped) - FROM itemTicketOut ito - JOIN tmp.tItems i ON i.itemFk = ito.itemFk - WHERE ito.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY - AND ito.warehouseFk = vWarehouseFk - GROUP BY ito.itemFk, ito.shipped - ) t2 - JOIN tmp.tItems i ON i.itemFk = t2.itemFk)t - GROUP BY t.itemFk, dated - ) t3; - - -- Se restan las entradas de hoy - UPDATE tmp.tStockByDay sbd - JOIN (SELECT iei.itemFk, SUM(quantity) todayEntry - FROM itemEntryIn iei - JOIN tmp.tItems i ON i.itemFk = iei.itemFk - WHERE iei.landed = util.VN_CURDATE() - AND iei.warehouseInFk = vWarehouseFk - AND NOT iei.isVirtualStock) sub ON sub.itemFk = sbd.itemFk - SET sbd.stock = sbd.stock - sub.todayEntry - WHERE sbd.dated = util.VN_CURDATE(); - - -- Se añaden las lineas de venta servidas - UPDATE tmp.tStockByDay sbd - JOIN (SELECT s.itemFK, SUM(quantity) amount - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - WHERE t.warehouseFk = vWarehouseFk - AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight() - AND s.isPicked - GROUP BY s.itemFk) sub ON sub.itemFk = sbd.itemFk - SET sbd.stock = sbd.stock + sub.amount; - - -- Se añaden los items ubicados hoy - UPDATE tmp.tStockByDay sbd - JOIN (SELECT ish.itemFK, SUM(ish.visible) amount - FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON p.id = sh.parkingFk - JOIN sector s ON s.id = p.sectorFk - WHERE s.warehouseFk = vWarehouseFk - AND NOT s.isReserve - AND ish.created BETWEEN util.VN_CURDATE() AND util.midnight() - GROUP BY ish.itemFk) sub ON sub.itemFk = sbd.itemFk - SET sbd.stock = sbd.stock + sub.amount; - - SELECT ts.itemFk, - i.longName, - IF(ts.stock<=0, ts.dated, NULL) dated, - ts.stock, - sub4.visible, - sub4.shelvingFk - FROM( - SELECT IFNULL(sub2.minDated, sub.minDated) dated, - IFNULL(sub2.itemFk, sub.itemFk) itemFk - FROM(SELECT sbd.itemFk, - MIN(dated) minDated, - sbd.stock - FROM tmp.tItems ti - LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk - GROUP BY itemFk)sub - LEFT JOIN ( - SELECT sbd.itemFk, - MIN(dated) minDated, - sbd.stock - FROM tmp.tItems ti - LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk - WHERE sbd.stock <= 0 - GROUP BY itemFk)sub2 ON sub2.itemFk =sub.itemFk - WHERE sub2.itemFk IS NOT NULL - OR (sub2.itemFk IS NULL AND sub.itemFk IS NOT NULL)) sub3 - LEFT JOIN tmp.tStockByDay ts ON ts.itemFk = sub3.itemFk AND ts.dated = sub3.dated - JOIN (SELECT ish.itemFk, - ish.visible, - p.sectorFk, - ish.shelvingFk - FROM itemShelving ish - JOIN vn.shelving sh ON sh.code = ish.shelvingFk - LEFT JOIN parking p ON p.id = parkingFk - LEFT JOIN vn.sector s ON s.id = p.sectorFk - WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci - ) sub4 ON sub4.itemFk = ts.itemFk - LEFT JOIN sector s ON s.id = sub4.sectorFk - LEFT JOIN item i ON i.id = ts.itemFk - WHERE NOT s.isReserve; - - DROP TEMPORARY TABLE tmp.tStockByDay, tmp.tItems; - +BEGIN + + /* Devuelve la mínima fecha en que se necesita cada producto en esa matrícula. + * + * @param vShelvingFk Matrícula del carro o pallet + */ + + DECLARE vWarehouseFk INT; + DECLARE vStockScopeDays INT; + + SELECT s.warehouseFk, stockScopeDays + INTO vWarehouseFk, vStockScopeDays + FROM sector s + JOIN operator o ON s.id = o.sectorFk + JOIN productionConfig pc + WHERE o.workerFk = account.myUser_getId(); + + IF vWarehouseFk IS NULL + THEN CALL util.throw('WarehouseFk not setted'); + END IF; + + IF vStockScopeDays IS NULL + THEN CALL util.throw('StockScopeDays not setted'); + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tmp.tItems + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT itemFk, SUM(visible) visible + FROM itemShelving + WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci + GROUP BY itemFk; + + CREATE OR REPLACE TEMPORARY TABLE tmp.tStockByDay + (INDEX (itemFk, dated)) + ENGINE = MEMORY + SELECT dated, + SUM(t3.amount) OVER (PARTITION BY t3.itemFk ORDER BY dated) stock, + t3.itemFk + FROM ( + SELECT t.itemFk, dated, SUM(amount) amount + FROM ( + SELECT t2.itemFk, t2.amount, t2.dated + FROM ( + SELECT item_id itemFk, amount, util.VN_CURDATE() dated + FROM cache.stock s + JOIN tmp.tItems i ON i.itemFk = s.item_id + WHERE s.warehouse_id = vWarehouseFk + UNION ALL + SELECT ish.itemFk, - SUM(ish.visible), util.VN_CURDATE() + FROM itemShelving ish + JOIN tmp.tItems i ON i.itemFk = ish.itemFk + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON sh.parkingFk = p.id + JOIN sector s ON s.id = p.sectorFk + WHERE s.isReserve + GROUP BY ish.itemFk + UNION ALL + SELECT iei.itemFk, SUM(quantity), landed + FROM itemEntryIn iei + JOIN tmp.tItems i ON i.itemFk = iei.itemFk + WHERE iei.landed BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY + AND iei.warehouseInFk = vWarehouseFk + AND NOT isVirtualStock + GROUP BY iei.itemFk, iei.landed + UNION ALL + SELECT ieo.itemFk, SUM(quantity), shipped + FROM itemEntryOut ieo + JOIN tmp.tItems i ON i.itemFk = ieo.itemFk + WHERE ieo.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY + AND ieo.warehouseOutFk = vWarehouseFk + GROUP BY ieo.itemFk, ieo.shipped + UNION ALL + SELECT i.itemFk, SUM(ito.quantity), DATE(ito.shipped) + FROM itemTicketOut ito + JOIN tmp.tItems i ON i.itemFk = ito.itemFk + WHERE ito.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY + AND ito.warehouseFk = vWarehouseFk + GROUP BY ito.itemFk, ito.shipped + ) t2 + JOIN tmp.tItems i ON i.itemFk = t2.itemFk)t + GROUP BY t.itemFk, dated + ) t3; + + -- Se restan las entradas de hoy + UPDATE tmp.tStockByDay sbd + JOIN (SELECT iei.itemFk, SUM(quantity) todayEntry + FROM itemEntryIn iei + JOIN tmp.tItems i ON i.itemFk = iei.itemFk + WHERE iei.landed = util.VN_CURDATE() + AND iei.warehouseInFk = vWarehouseFk + AND NOT iei.isVirtualStock) sub ON sub.itemFk = sbd.itemFk + SET sbd.stock = sbd.stock - sub.todayEntry + WHERE sbd.dated = util.VN_CURDATE(); + + -- Se añaden las lineas de venta servidas + UPDATE tmp.tStockByDay sbd + JOIN (SELECT s.itemFK, SUM(quantity) amount + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + WHERE t.warehouseFk = vWarehouseFk + AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight() + AND s.isPicked + GROUP BY s.itemFk) sub ON sub.itemFk = sbd.itemFk + SET sbd.stock = sbd.stock + sub.amount; + + -- Se añaden los items ubicados hoy + UPDATE tmp.tStockByDay sbd + JOIN (SELECT ish.itemFK, SUM(ish.visible) amount + FROM itemShelving ish + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON p.id = sh.parkingFk + JOIN sector s ON s.id = p.sectorFk + WHERE s.warehouseFk = vWarehouseFk + AND NOT s.isReserve + AND ish.created BETWEEN util.VN_CURDATE() AND util.midnight() + GROUP BY ish.itemFk) sub ON sub.itemFk = sbd.itemFk + SET sbd.stock = sbd.stock + sub.amount; + + SELECT ts.itemFk, + i.longName, + IF(ts.stock<=0, ts.dated, NULL) dated, + ts.stock, + sub4.visible, + sub4.shelvingFk + FROM( + SELECT IFNULL(sub2.minDated, sub.minDated) dated, + IFNULL(sub2.itemFk, sub.itemFk) itemFk + FROM(SELECT sbd.itemFk, + MIN(dated) minDated, + sbd.stock + FROM tmp.tItems ti + LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk + GROUP BY itemFk)sub + LEFT JOIN ( + SELECT sbd.itemFk, + MIN(dated) minDated, + sbd.stock + FROM tmp.tItems ti + LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk + WHERE sbd.stock <= 0 + GROUP BY itemFk)sub2 ON sub2.itemFk =sub.itemFk + WHERE sub2.itemFk IS NOT NULL + OR (sub2.itemFk IS NULL AND sub.itemFk IS NOT NULL)) sub3 + LEFT JOIN tmp.tStockByDay ts ON ts.itemFk = sub3.itemFk AND ts.dated = sub3.dated + JOIN (SELECT ish.itemFk, + ish.visible, + p.sectorFk, + ish.shelvingFk + FROM itemShelving ish + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + LEFT JOIN parking p ON p.id = parkingFk + LEFT JOIN vn.sector s ON s.id = p.sectorFk + WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci + ) sub4 ON sub4.itemFk = ts.itemFk + LEFT JOIN sector s ON s.id = sub4.sectorFk + LEFT JOIN item i ON i.id = ts.itemFk + WHERE NOT s.isReserve; + + DROP TEMPORARY TABLE tmp.tStockByDay, tmp.tItems; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -61625,6 +62060,58 @@ SET tag8 = t.name, value8 = it.value WHERE it.priority = 4 AND (vItem IS NULL OR vItem = it.itemFk); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `item_calculateStock` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`vn`@`localhost` PROCEDURE `item_calculateStock`( + vDated DATE +) +BEGIN +/** + * Calculate the stock of the auction warehouse from the inventory date to vDated + * + * @param vDated Date to calculate the stock. + * @return tmp.item, tmp.buyUltimate + */ + DECLARE vAuctionWarehouseFk INT; + + SELECT warehouseFk INTO vAuctionWarehouseFk + FROM auctionConfig; + + CREATE OR REPLACE TEMPORARY TABLE tmp.item + (UNIQUE INDEX i USING HASH (itemFk)) + ENGINE = MEMORY + SELECT itemFk, SUM(quantity) quantity + FROM itemEntryIn + WHERE landed = vDated + AND vDated >= util.VN_CURDATE() + AND warehouseInFk = vAuctionWarehouseFk + AND NOT isVirtualStock + GROUP BY itemFk + HAVING quantity; + + CALL `cache`.stock_refresh(FALSE); + + INSERT INTO tmp.item (itemFk, quantity) + SELECT item_id, amount + FROM `cache`.stock + WHERE warehouse_id = vAuctionWarehouseFk + ON DUPLICATE KEY UPDATE quantity = tmp.item.quantity + VALUES(quantity); + + CALL buy_getUltimate(NULL, vAuctionWarehouseFk, vDated); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -62706,50 +63193,50 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`vn`@`localhost` PROCEDURE `item_getAtp`(vDated DATE) -BEGIN -/** - * Calcula el valor mínimo acumulado para cada artículo ordenado por fecha y - * almacén. - * - * @param vDated Si no hay movimientos en la fecha indicada, debe devolver 0 - * @table tmp.itemCalc(itemFk, wareHouseFk, dated, quantity) - * @return tmp.itemAtp(itemFk, warehouseFk, quantity) - */ - CREATE OR REPLACE TEMPORARY TABLE tItemOrdered - (UNIQUE(itemFk, warehouseFk, dated)) - ENGINE = MEMORY - SELECT itemFk, warehouseFk, dated, SUM(quantity) quantity - FROM ( - SELECT itemFk, warehouseFk, dated, quantity - FROM tmp.itemCalc - UNION ALL - SELECT itemFk, warehouseFk, vDated, 0 - FROM (SELECT DISTINCT itemFk, warehouseFk FROM tmp.itemCalc) t2 - ) t1 - GROUP BY itemFk, warehouseFk, dated - ORDER BY itemFk, warehouseFk, dated; - - SET @lastItemFk := 0; - SET @lastWareHouseFk := 0; - SET @lastQuantity := 0; - - CREATE OR REPLACE TEMPORARY TABLE tmp.itemAtp - (INDEX (itemFk, wareHouseFk)) - SELECT itemFk, wareHouseFk, MIN(quantityAccumulated) quantity - FROM ( - SELECT - itemFk, - IF(itemFk <> @lastItemFk OR wareHouseFk <> @lastWareHouseFk, - @lastQuantity := quantity, - @lastQuantity := @lastQuantity + quantity) quantityAccumulated, - wareHouseFk, - @lastItemFk := itemFk, - @lastWareHouseFk := wareHouseFk - FROM tItemOrdered - )sub - GROUP BY itemFk, wareHouseFk; - - DROP TEMPORARY TABLE tItemOrdered; +BEGIN +/** + * Calcula el valor mínimo acumulado para cada artículo ordenado por fecha y + * almacén. + * + * @param vDated Si no hay movimientos en la fecha indicada, debe devolver 0 + * @table tmp.itemCalc(itemFk, wareHouseFk, dated, quantity) + * @return tmp.itemAtp(itemFk, warehouseFk, quantity) + */ + CREATE OR REPLACE TEMPORARY TABLE tItemOrdered + (UNIQUE(itemFk, warehouseFk, dated)) + ENGINE = MEMORY + SELECT itemFk, warehouseFk, dated, SUM(quantity) quantity + FROM ( + SELECT itemFk, warehouseFk, dated, quantity + FROM tmp.itemCalc + UNION ALL + SELECT itemFk, warehouseFk, vDated, 0 + FROM (SELECT DISTINCT itemFk, warehouseFk FROM tmp.itemCalc) t2 + ) t1 + GROUP BY itemFk, warehouseFk, dated + ORDER BY itemFk, warehouseFk, dated; + + SET @lastItemFk := 0; + SET @lastWareHouseFk := 0; + SET @lastQuantity := 0; + + CREATE OR REPLACE TEMPORARY TABLE tmp.itemAtp + (INDEX (itemFk, wareHouseFk)) + SELECT itemFk, wareHouseFk, MIN(quantityAccumulated) quantity + FROM ( + SELECT + itemFk, + IF(itemFk <> @lastItemFk OR wareHouseFk <> @lastWareHouseFk, + @lastQuantity := quantity, + @lastQuantity := @lastQuantity + quantity) quantityAccumulated, + wareHouseFk, + @lastItemFk := itemFk, + @lastWareHouseFk := wareHouseFk + FROM tItemOrdered + )sub + GROUP BY itemFk, wareHouseFk; + + DROP TEMPORARY TABLE tItemOrdered; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63380,19 +63867,23 @@ CREATE DEFINER=`vn`@`localhost` PROCEDURE `item_getSimilar`( ) BEGIN /** -* Propone articulos ordenados, con la cantidad -* de veces usado y segun sus caracteristicas. -* -* @param vSelf Id de artículo -* @param vWarehouseFk Id de almacen -* @param vDated Fecha -* @param vShowType Mostrar tipos -* @param vDaysInForward Días de alcance para las ventas -*/ + * Propone articulos ordenados, con la cantidad + * de veces usado y segun sus caracteristicas. + * + * @param vSelf Id de artículo + * @param vWarehouseFk Id de almacen + * @param vDated Fecha + * @param vShowType Mostrar tipos + * @param vDaysInForward Días de alcance para las ventas (https://redmine.verdnatura.es/issues/7956#note-4) + */ DECLARE vAvailableCalcFk INT; + DECLARE vVisibleCalcFk INT; + DECLARE vTypeFk INT; DECLARE vPriority INT DEFAULT 1; CALL cache.available_refresh(vAvailableCalcFk, FALSE, vWarehouseFk, vDated); + CALL cache.visible_refresh(vVisibleCalcFk, FALSE, vWarehouseFk); + CALL buy_getUltimate(NULL, vWarehouseFk, vDated); WITH itemTags AS ( SELECT i.id, @@ -63412,25 +63903,9 @@ BEGIN AND it.priority = vPriority LEFT JOIN vn.tag t ON t.id = it.tagFk WHERE i.id = vSelf - ), - stock AS ( - SELECT itemFk, SUM(visible) stock - FROM vn.itemShelvingStock - WHERE warehouseFk = vWarehouseFk - GROUP BY itemFk - ), - sold AS ( - SELECT SUM(s.quantity) quantity, s.itemFk - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id - WHERE t.shipped >= CURDATE() + INTERVAL vDaysInForward DAY - AND iss.saleFk IS NULL - AND t.warehouseFk = vWarehouseFk - GROUP BY s.itemFk ) SELECT i.id itemFk, - LEAST(CAST(sd.quantity AS INT), sk.stock) advanceable, + NULL advanceable, -- https://redmine.verdnatura.es/issues/7956#note-4 i.longName, i.subName, i.tag5, @@ -63452,38 +63927,38 @@ BEGIN WHEN b.groupingMode = 'packing' THEN b.packing ELSE 1 END minQuantity, - sk.stock located, + v.visible located, b.price2 FROM vn.item i - LEFT JOIN sold sd ON sd.itemFk = i.id JOIN cache.available a ON a.item_id = i.id AND a.calc_id = vAvailableCalcFk - LEFT JOIN stock sk ON sk.itemFk = i.id - LEFT JOIN cache.last_buy lb ON lb.item_id = i.id - AND lb.warehouse_id = vWarehouseFk + LEFT JOIN cache.visible v ON v.item_id = i.id + AND v.calc_id = vVisibleCalcFk + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.id LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vSelf LEFT JOIN vn.itemTag it ON it.itemFk = i.id AND it.priority = vPriority LEFT JOIN vn.tag t ON t.id = it.tagFk - LEFT JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN vn.buy b ON b.id = bu.buyFk JOIN itemTags its - WHERE (a.available > 0 OR sd.quantity < sk.stock) + WHERE a.available > 0 AND (i.typeFk = its.typeFk OR NOT vShowType) AND i.id <> vSelf - ORDER BY (a.available > 0) DESC, - `counter` DESC, - (t.name = its.name) DESC, - (it.value = its.value) DESC, - (i.tag5 = its.tag5) DESC, - match5 DESC, - (i.tag6 = its.tag6) DESC, - match6 DESC, - (i.tag7 = its.tag7) DESC, - match7 DESC, - (i.tag8 = its.tag8) DESC, - match8 DESC + ORDER BY `counter` DESC, + (t.name = its.name) DESC, + (it.value = its.value) DESC, + (i.tag5 = its.tag5) DESC, + match5 DESC, + (i.tag6 = its.tag6) DESC, + match6 DESC, + (i.tag7 = its.tag7) DESC, + match7 DESC, + (i.tag8 = its.tag8) DESC, + match8 DESC LIMIT 100; + + DROP TEMPORARY TABLE tmp.buyUltimate; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64949,176 +65424,176 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `multipleInventory`( - vDate DATE, - vWarehouseFk TINYINT, - vMaxDays TINYINT +CREATE DEFINER=`vn`@`localhost` PROCEDURE `multipleInventory`( + vDate DATE, + vWarehouseFk TINYINT, + vMaxDays TINYINT ) -proc: BEGIN - DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY; - DECLARE vDateFrom DATE DEFAULT vDate; - DECLARE vDateTo DATETIME; - DECLARE vDateToTomorrow DATETIME; - DECLARE vDefaultDayRange INT; - DECLARE vCalcFk INT; - - IF vDate < util.VN_CURDATE() THEN - LEAVE proc; - END IF; - - IF vDate = util.VN_CURDATE() THEN - SELECT inventoried INTO vDateFrom - FROM config; - END IF; - - SELECT defaultDayRange INTO vDefaultDayRange - FROM comparativeConfig; - - SET vDateTo = vDate + INTERVAL IFNULL(vMaxDays, vDefaultDayRange) DAY; - SET vDateToTomorrow = vDateTo + INTERVAL 1 DAY; - - ALTER TABLE tmp.itemInventory - ADD `avalaible` INT NOT NULL, - ADD `sd` INT NOT NULL, - ADD `rest` INT NOT NULL, - ADD `expected` INT NOT NULL, - ADD `inventory` INT NOT NULL, - ADD `visible` INT NOT NULL, - ADD `life` TINYINT NOT NULL DEFAULT '0'; - - -- Calculo del inventario - CREATE OR REPLACE TEMPORARY TABLE tItemInventoryCalc - (PRIMARY KEY (itemFk)) - ENGINE = MEMORY - SELECT itemFk, - SUM(quantity) quantity - FROM ( - SELECT s.itemFk, - s.quantity quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed BETWEEN vDateFrom AND util.dayEnd(vDate) - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - UNION ALL - SELECT b.itemFk, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - ) sub - GROUP BY itemFk; - - -- Cálculo del visible - CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk); - - CREATE OR REPLACE TEMPORARY TABLE tItemVisibleCalc - (PRIMARY KEY (item_id)) - ENGINE = MEMORY - SELECT item_id, visible - FROM cache.visible - WHERE calc_id = vCalcFk; - - UPDATE tmp.itemInventory it - LEFT JOIN tItemInventoryCalc iic ON iic.itemFk = it.id - LEFT JOIN tItemVisibleCalc ivc ON ivc.item_id = it.id - SET it.inventory = iic.quantity, - it.visible = ivc.visible, - it.avalaible = iic.quantity, - it.sd = iic.quantity; - - -- Calculo del disponible - CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc - (INDEX (itemFk, warehouseFk)) - ENGINE = MEMORY - SELECT sub.itemFk, - vWarehouseFk warehouseFk, - sub.dated, - SUM(sub.quantity) quantity - FROM ( - SELECT s.itemFk, - DATE(t.shipped) dated, - - s.quantity quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, t.landed, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed BETWEEN vDateTomorrow AND vDateTo - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - UNION ALL - SELECT b.itemFk, t.shipped, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - ) sub - GROUP BY sub.itemFk, sub.dated; - - CALL item_getAtp(vDate); - CALL travel_upcomingArrivals(vWarehouseFk, vDate); - - CREATE OR REPLACE TEMPORARY TABLE tItemAvailableCalc - (PRIMARY KEY (itemFk)) - ENGINE = MEMORY - SELECT it.itemFk, - SUM(it.quantity) quantity, - im.quantity minQuantity - FROM tmp.itemCalc it - JOIN tmp.itemAtp im ON im.itemFk = it.itemFk - JOIN item i ON i.id = it.itemFk - LEFT JOIN origin o ON o.id = i.originFk - LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk - WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL, - t.landing, - vDateToTomorrow) - GROUP BY it.itemFk; - - UPDATE tmp.itemInventory it - JOIN tItemAvailableCalc iac ON iac.itemFk = it.id - SET it.avalaible = IF(iac.minQuantity > 0, - it.avalaible, - it.avalaible + iac.minQuantity), - it.sd = it.inventory + iac.quantity; - - DROP TEMPORARY TABLE - tmp.itemTravel, - tmp.itemCalc, - tmp.itemAtp, - tItemInventoryCalc, - tItemVisibleCalc, - tItemAvailableCalc; +proc: BEGIN + DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY; + DECLARE vDateFrom DATE DEFAULT vDate; + DECLARE vDateTo DATETIME; + DECLARE vDateToTomorrow DATETIME; + DECLARE vDefaultDayRange INT; + DECLARE vCalcFk INT; + + IF vDate < util.VN_CURDATE() THEN + LEAVE proc; + END IF; + + IF vDate = util.VN_CURDATE() THEN + SELECT inventoried INTO vDateFrom + FROM config; + END IF; + + SELECT defaultDayRange INTO vDefaultDayRange + FROM comparativeConfig; + + SET vDateTo = vDate + INTERVAL IFNULL(vMaxDays, vDefaultDayRange) DAY; + SET vDateToTomorrow = vDateTo + INTERVAL 1 DAY; + + ALTER TABLE tmp.itemInventory + ADD `avalaible` INT NOT NULL, + ADD `sd` INT NOT NULL, + ADD `rest` INT NOT NULL, + ADD `expected` INT NOT NULL, + ADD `inventory` INT NOT NULL, + ADD `visible` INT NOT NULL, + ADD `life` TINYINT NOT NULL DEFAULT '0'; + + -- Calculo del inventario + CREATE OR REPLACE TEMPORARY TABLE tItemInventoryCalc + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT itemFk, + SUM(quantity) quantity + FROM ( + SELECT s.itemFk, - s.quantity quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed BETWEEN vDateFrom AND util.dayEnd(vDate) + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + UNION ALL + SELECT b.itemFk, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + ) sub + GROUP BY itemFk; + + -- Cálculo del visible + CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk); + + CREATE OR REPLACE TEMPORARY TABLE tItemVisibleCalc + (PRIMARY KEY (item_id)) + ENGINE = MEMORY + SELECT item_id, visible + FROM cache.visible + WHERE calc_id = vCalcFk; + + UPDATE tmp.itemInventory it + LEFT JOIN tItemInventoryCalc iic ON iic.itemFk = it.id + LEFT JOIN tItemVisibleCalc ivc ON ivc.item_id = it.id + SET it.inventory = iic.quantity, + it.visible = ivc.visible, + it.avalaible = iic.quantity, + it.sd = iic.quantity; + + -- Calculo del disponible + CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc + (INDEX (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT sub.itemFk, + vWarehouseFk warehouseFk, + sub.dated, + SUM(sub.quantity) quantity + FROM ( + SELECT s.itemFk, + DATE(t.shipped) dated, + - s.quantity quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, t.landed, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed BETWEEN vDateTomorrow AND vDateTo + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + UNION ALL + SELECT b.itemFk, t.shipped, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + ) sub + GROUP BY sub.itemFk, sub.dated; + + CALL item_getAtp(vDate); + CALL travel_upcomingArrivals(vWarehouseFk, vDate); + + CREATE OR REPLACE TEMPORARY TABLE tItemAvailableCalc + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT it.itemFk, + SUM(it.quantity) quantity, + im.quantity minQuantity + FROM tmp.itemCalc it + JOIN tmp.itemAtp im ON im.itemFk = it.itemFk + JOIN item i ON i.id = it.itemFk + LEFT JOIN origin o ON o.id = i.originFk + LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk + WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL, + t.landing, + vDateToTomorrow) + GROUP BY it.itemFk; + + UPDATE tmp.itemInventory it + JOIN tItemAvailableCalc iac ON iac.itemFk = it.id + SET it.avalaible = IF(iac.minQuantity > 0, + it.avalaible, + it.avalaible + iac.minQuantity), + it.sd = it.inventory + iac.quantity; + + DROP TEMPORARY TABLE + tmp.itemTravel, + tmp.itemCalc, + tmp.itemAtp, + tItemInventoryCalc, + tItemVisibleCalc, + tItemAvailableCalc; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66055,13 +66530,11 @@ proc: BEGIN DECLARE vEndingDate DATETIME; DECLARE vIsTodayRelative BOOLEAN; - SELECT util.dayEnd(util.VN_CURDATE()) + INTERVAL LEAST(vScopeDays, maxProductionScopeDays) DAY - INTO vEndingDate - FROM productionConfig; - - SELECT isTodayRelative INTO vIsTodayRelative - FROM worker - WHERE id = getUser(); -- Cambiar por account.myUser_getId(), falta dar permisos + SELECT w.isTodayRelative, util.dayEnd(util.VN_CURDATE()) + INTERVAL LEAST(vScopeDays, pc.maxProductionScopeDays) DAY + INTO vIsTodayRelative,vEndingDate + FROM worker w + JOIN productionConfig pc + WHERE w.id = account.myUser_getId(); CALL prepareTicketList(util.yesterday(), vEndingDate); @@ -66308,15 +66781,14 @@ proc: BEGIN UPDATE tmp.productionBuffer pb JOIN sale s ON s.ticketFk = pb.ticketFk JOIN item i ON i.id = s.itemFk - JOIN cache.last_buy lb ON lb.warehouse_id = vWarehouseFk + JOIN cache.last_buy lb ON lb.warehouse_id = vWarehouseFk AND lb.item_id = s.itemFk JOIN buy b ON b.id = lb.buy_id JOIN packaging p ON p.id = b.packagingFk - JOIN productionConfig pc SET pb.hasPlantTray = TRUE WHERE p.isPlantTray AND s.quantity >= b.packing - AND pb.isOwn; + AND pb.isOwn; DROP TEMPORARY TABLE tmp.productionTicket, @@ -66691,6 +67163,47 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `queueMember_updateQueue` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`vn`@`localhost` PROCEDURE `queueMember_updateQueue`( + vBusinessFk INT +) +BEGIN + /** + * Elimina la entrada de la cola anterior y luego inserta la nueva para un trabajador. + * + * @param vBusinessFk ID del negocio + */ + DECLARE vNewQueue VARCHAR(10); + DECLARE vExtension VARCHAR(10); + DECLARE exit handler FOR SQLEXCEPTION + + SELECT d.pbxQueue, s.extension + INTO vNewQueue, vExtension + FROM business b + JOIN department d ON d.id = b.departmentFk + JOIN pbx.sip s ON s.user_id = b.workerFk + WHERE b.id = vBusinessFk; + + DELETE FROM pbx.queueMember + WHERE extension = vExtension COLLATE utf8_general_ci; + + INSERT IGNORE INTO pbx.queueMember (queue, extension) + VALUES (vNewQueue, vExtension); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `raidUpdate` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -68192,6 +68705,39 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `saleTracking_sectorCollectionAddPrevOK` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`vn`@`localhost` PROCEDURE `saleTracking_sectorCollectionAddPrevOK`( + vSectorCollectionFk INT +) +BEGIN +/** + * Inserta los registros de sectorCollection con el estado PREVIA OK si la reserva está picked + * + * @param vSectorCollectionFk Identificador de vn.sectorCollection + */ + REPLACE saleTracking(saleFk, isChecked, workerFk, stateFk) + SELECT sgd.saleFk, TRUE, sc.userFk, s.id + FROM sectorCollection sc + JOIN sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + JOIN saleGroupDetail sgd ON sgd.saleGroupFk = scsg.saleGroupFk + JOIN state s ON s.code = 'OK PREVIOUS' + JOIN itemShelvingSale iss ON iss.saleFk = sgd.saleFk + WHERE sc.id = vSectorCollectionFk AND iss.isPicked; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `saleTracking_updateIsChecked` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -68834,7 +69380,7 @@ BEGIN isTooLittle BOOL DEFAULT FALSE, isVip BOOL DEFAULT FALSE, PRIMARY KEY (ticketFk, saleFk) - ) ENGINE = MEMORY; + ); -- No memory INSERT INTO tmp.sale_problems(ticketFk, saleFk, @@ -69705,30 +70251,30 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`vn`@`localhost` PROCEDURE `sectorCollection_new`(vSectorFk INT) -BEGIN -/** - * Inserta una nueva colección, si el usuario no tiene ninguna vacia. - * Esto se hace para evitar que por error se generen colecciones sin sentido. - * - * @param vSectorFk Identificador de #vn.sector - */ - DECLARE hasEmptyCollections BOOL; - DECLARE vUserFk INT; - - SET vUserFk = account.myUser_getId(); - - SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections - FROM vn.sectorCollection sc - LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id - WHERE ISNULL(scsg.id) - AND sc.userFk = vUserFk - AND sc.sectorFk = vSectorFk - AND sc.created >= util.VN_CURDATE(); - - IF NOT hasEmptyCollections THEN - INSERT INTO vn.sectorCollection(userFk, sectorFk) - VALUES(vUserFk, vSectorFk); - END IF; +BEGIN +/** + * Inserta una nueva colección, si el usuario no tiene ninguna vacia. + * Esto se hace para evitar que por error se generen colecciones sin sentido. + * + * @param vSectorFk Identificador de #vn.sector + */ + DECLARE hasEmptyCollections BOOL; + DECLARE vUserFk INT; + + SET vUserFk = account.myUser_getId(); + + SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections + FROM vn.sectorCollection sc + LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + WHERE ISNULL(scsg.id) + AND sc.userFk = vUserFk + AND sc.sectorFk = vSectorFk + AND sc.created >= util.VN_CURDATE(); + + IF NOT hasEmptyCollections THEN + INSERT INTO vn.sectorCollection(userFk, sectorFk) + VALUES(vUserFk, vSectorFk); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -70238,13 +70784,13 @@ proc: BEGIN * Calculate the stock of the auction warehouse from the inventory date to vDated * without taking into account the outputs of the same day vDated * - * @param vDated Date to calculate the stock. + * @param vDated Date to calculate the stock */ IF vDated < util.VN_CURDATE() THEN LEAVE proc; END IF; - CREATE OR REPLACE TEMPORARY TABLE tStockBought + CREATE OR REPLACE TEMPORARY TABLE tCurrentData SELECT workerFk, reserve FROM stockBought WHERE dated = vDated @@ -70252,15 +70798,28 @@ proc: BEGIN DELETE FROM stockBought WHERE dated = vDated; + CREATE OR REPLACE TEMPORARY TABLE tStockSold + SELECT it.workerFk, + SUM(ic.cm3 * ito.quantity / vc.palletM3 / 1000000) sold + FROM itemTicketOut ito + JOIN item i ON i.id = ito.itemFk + JOIN itemType it ON it.id = i.typeFk + JOIN ticket t ON t.id = ito.ticketFk + JOIN warehouse wh ON wh.id = t.warehouseFk + JOIN itemCost ic ON ic.itemFk = ito.itemFk + AND ic.warehouseFk = t.warehouseFk + JOIN volumeConfig vc + WHERE ito.shipped BETWEEN vDated AND util.dayEnd(vDated) + AND wh.code = 'VNH' + GROUP BY it.workerFk; + CALL item_calculateStock(vDated); - INSERT INTO stockBought(workerFk, bought, dated) + CREATE OR REPLACE TEMPORARY TABLE tStockBought SELECT it.workerFk, - ROUND(SUM( - (ti.quantity / b.packing) * - buy_getVolume(b.id) - ) / vc.palletM3 / 1000000, 1) bought, - vDated + SUM((ti.quantity / b.packing) * + buy_getVolume(b.id) + ) / vc.palletM3 / 1000000 bought FROM itemType it JOIN item i ON i.typeFk = it.id LEFT JOIN tmp.item ti ON ti.itemFk = i.id @@ -70274,245 +70833,34 @@ proc: BEGIN GROUP BY it.workerFk HAVING bought; + + INSERT INTO stockBought(workerFk, bought, dated) + SELECT tb.workerFk, + ROUND(GREATEST(tb.bought - IFNULL(ts.sold, 0), 0), 1), + vDated + FROM tStockBought tb + LEFT JOIN tStockSold ts ON ts.workerFk = tb.workerFk; + UPDATE stockBought s - JOIN tStockBought ts ON ts.workerFk = s.workerFk + JOIN tCurrentData ts ON ts.workerFk = s.workerFk SET s.reserve = ts.reserve WHERE s.dated = vDated; INSERT INTO stockBought (workerFk, reserve, dated) SELECT ts.workerFk, ts.reserve, vDated - FROM tStockBought ts + FROM tCurrentData ts WHERE ts.workerFk NOT IN ( SELECT workerFk FROM stockBought WHERE dated = vDated ); - DROP TEMPORARY TABLE tStockBought, tmp.item, tmp.buyUltimate; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `stockBuyedByWorker` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `stockBuyedByWorker`( - vDated DATE, - vWorker INT -) -BEGIN -/** - * Inserta el volumen de compra de un comprador - * en stockBuyed de acuerdo con la fecha. - * - * @param vDated Fecha de compra - * @param vWorker Id de trabajador - */ - CREATE OR REPLACE TEMPORARY TABLE tStockBuyed - (INDEX (userFk)) - ENGINE = MEMORY - SELECT requested, reserved, userFk - FROM stockBuyed - WHERE dated = vDated - AND userFk = vWorker; - - DELETE FROM stockBuyed - WHERE dated = vDated - AND userFk = vWorker; - - CALL stockTraslation(vDated); - - INSERT INTO stockBuyed(userFk, buyed, `dated`, reserved, requested, description) - SELECT it.workerFk, - SUM((ti.quantity / b.packing) * buy_getVolume(b.id)) / vc.palletM3 / 1000000, - vDated, - sb.reserved, - sb.requested, - u.name - FROM itemType it - JOIN item i ON i.typeFk = it.id - LEFT JOIN tmp.item ti ON ti.itemFk = i.id - JOIN itemCategory ic ON ic.id = it.categoryFk - JOIN warehouse wh ON wh.code = 'VNH' - JOIN tmp.buyUltimate bu ON bu.itemFk = i.id - AND bu.warehouseFk = wh.id - JOIN buy b ON b.id = bu.buyFk - JOIN volumeConfig vc - JOIN account.`user` u ON u.id = it.workerFk - LEFT JOIN tStockBuyed sb ON sb.userFk = it.workerFk - WHERE ic.display - AND it.workerFk = vWorker; - - SELECT b.entryFk Id_Entrada, - i.id Id_Article, - i.name Article, - ti.quantity Cantidad, - (ac.conversionCoefficient * (ti.quantity / b.packing) * buy_getVolume(b.id)) - / (vc.trolleyM3 * 1000000) buyed, - b.packagingFk id_cubo, - b.packing - FROM tmp.item ti - JOIN item i ON i.id = ti.itemFk - JOIN itemType it ON i.typeFk = it.id - JOIN itemCategory ic ON ic.id = it.categoryFk - JOIN worker w ON w.id = it.workerFk - JOIN auctionConfig ac - JOIN tmp.buyUltimate bu ON bu.itemFk = i.id - AND bu.warehouseFk = ac.warehouseFk - JOIN buy b ON b.id = bu.buyFk - JOIN volumeConfig vc - WHERE ic.display - AND w.id = vWorker; - - DROP TEMPORARY TABLE tmp.buyUltimate, - tmp.item, - tStockBuyed; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `stockBuyed_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `stockBuyed_add`( - vDated DATE -) -BEGIN -/** - * Inserta el volumen de compra por comprador - * en stockBuyed de acuerdo con la fecha. - * - * @param vDated Fecha de compra - */ - CREATE OR REPLACE TEMPORARY TABLE tStockBuyed - (INDEX (userFk)) - ENGINE = MEMORY - SELECT requested, reserved, userFk - FROM stockBuyed - WHERE dated = vDated; - - DELETE FROM stockBuyed WHERE dated = vDated; - - CALL stockTraslation(vDated); - - INSERT INTO stockBuyed(userFk, buyed, `dated`, description) - SELECT it.workerFk, - SUM((ti.quantity / b.packing) * buy_getVolume(b.id)) / vc.palletM3 / 1000000, - vDated, - u.name - FROM itemType it - JOIN item i ON i.typeFk = it.id - LEFT JOIN tmp.item ti ON ti.itemFk = i.id - JOIN itemCategory ic ON ic.id = it.categoryFk - JOIN warehouse wh ON wh.code = 'VNH' - JOIN tmp.buyUltimate bu ON bu.itemFk = i.id AND bu.warehouseFk = wh.id - JOIN buy b ON b.id = bu.buyFk - JOIN volumeConfig vc - JOIN account.`user` u ON u.id = it.workerFk - JOIN workerDepartment wd ON wd.workerFk = u.id - JOIN department d ON d.id = wd.departmentFk - WHERE ic.display - AND d.code IN ('shopping', 'logistic', 'franceTeam') - GROUP BY it.workerFk; - - INSERT INTO stockBuyed(buyed, dated, description) - SELECT SUM(ic.cm3 * ito.quantity / vc.palletM3 / 1000000), - vDated, - IF(c.code = 'ES', p.name, c.name) destiny - FROM itemTicketOut ito - JOIN ticket t ON t.id = ito.ticketFk - JOIN `address` a ON a.id = t.addressFk - JOIN province p ON p.id = a.provinceFk - JOIN country c ON c.id = p.countryFk - JOIN warehouse wh ON wh.id = t.warehouseFk - JOIN itemCost ic ON ic.itemFk = ito.itemFk - AND ic.warehouseFk = t.warehouseFk - JOIN volumeConfig vc - WHERE ito.shipped BETWEEN vDated AND util.dayend(vDated) - AND wh.code = 'VNH' - GROUP BY destiny; - - UPDATE stockBuyed s - JOIN tStockBuyed ts ON ts.userFk = s.userFk - SET s.requested = ts.requested, - s.reserved = ts.reserved + UPDATE stockBought s + JOIN tStockSold ts ON ts.workerFk = s.workerFk + SET s.bought = IF(s.bought < ts.sold, ROUND(s.bought - ts.sold, 1), 0) WHERE s.dated = vDated; - DROP TEMPORARY TABLE tmp.buyUltimate, - tmp.item, - tStockBuyed; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `stockTraslation` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `stockTraslation`( - vDated DATE -) -BEGIN -/** - * Calcula el stock del almacén de subasta desde FechaInventario hasta vDated - * sin tener en cuenta las salidas del mismo dia vDated - * para ver el transporte a reservar - * - * @param vDated Fecha hasta la cual calcula el stock - * @return tmp.item - */ - DECLARE vAuctionWarehouseFk INT; - - SELECT warehouseFk INTO vAuctionWarehouseFk - FROM auctionConfig; - - CREATE OR REPLACE TEMPORARY TABLE tmp.item - (UNIQUE INDEX i USING HASH (itemFk)) - ENGINE = MEMORY - SELECT itemFk, SUM(quantity) quantity - FROM itemEntryIn - WHERE landed = vDated - AND vDated >= util.VN_CURDATE() - AND warehouseInFk = vAuctionWarehouseFk - AND NOT isVirtualStock - GROUP BY itemFk - HAVING quantity; - - CALL `cache`.stock_refresh(FALSE); - - INSERT INTO tmp.item (itemFk, quantity) - SELECT item_id, amount - FROM `cache`.stock - WHERE warehouse_id = vAuctionWarehouseFk - ON DUPLICATE KEY UPDATE quantity = tmp.item.quantity + VALUES(quantity); - - CALL buy_getUltimate(NULL, vAuctionWarehouseFk, vDated); + DROP TEMPORARY TABLE tCurrentData, tmp.item, tmp.buyUltimate, tStockSold; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72250,6 +72598,44 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketRefund_upsert` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`vn`@`localhost` PROCEDURE `ticketRefund_upsert`( + vRefundTicketFk INT, + vOriginalTicketFk INT +) + READS SQL DATA +BEGIN +/** + * Common code for ticketRefund triggers + * + * @param vRefundTicketFk + * @param vOriginalTicketFk + */ + DECLARE vIsDeleted BOOL; + + SELECT COUNT(*) INTO vIsDeleted + FROM ticket + WHERE id IN (vRefundTicketFk, vOriginalTicketFk) + AND isDeleted; + + IF vIsDeleted THEN + CALL util.throw('The refund ticket cannot be deleted tickets'); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `ticketStateToday_setState` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -72655,7 +73041,8 @@ BEGIN origin.companyFk futureCompanyFk, IFNULL(dest.nickname, origin.nickname) nickname, dest.landed, - dest.preparation + dest.preparation, + origin.departmentFk FROM ( SELECT s.ticketFk, c.salesPersonFk workerFk, @@ -72675,9 +73062,11 @@ BEGIN t.addressFk, t.warehouseFk, t.companyFk, - t.agencyModeFk + t.agencyModeFk, + wd.departmentFk FROM ticket t JOIN client c ON c.id = t.clientFk + JOIN workerDepartment wd ON wd.workerFk = c.salesPersonFk JOIN sale s ON s.ticketFk = t.id JOIN saleVolume sv ON sv.saleFk = s.id JOIN item i ON i.id = s.itemFk @@ -73394,7 +73783,7 @@ BEGIN c.isTaxDataChecked, t.companyFk, t.shipped, - IFNULL(a.hasDailyInvoice, co.hasDailyInvoice), + c.hasDailyInvoice, w.isManaged, c.hasToInvoice INTO vClientFk, @@ -73406,9 +73795,6 @@ BEGIN vHasToInvoice FROM ticket t JOIN `client` c ON c.id = t.clientFk - JOIN province p ON p.id = c.provinceFk - LEFT JOIN autonomy a ON a.id = p.autonomyFk - JOIN country co ON co.id = p.countryFk JOIN warehouse w ON w.id = t.warehouseFk WHERE t.id = vCurTicketFk; @@ -73436,7 +73822,7 @@ BEGIN IF(vHasDailyInvoice) AND vHasToInvoice THEN SELECT invoiceSerial(vClientFk, vCompanyFk, 'quick') INTO vSerial; - IF vSerial IS NULL THEN + IF vSerial IS NULL THEN CALL util.throw('Cannot booking without a serial'); END IF; @@ -73787,62 +74173,62 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `ticket_DelayTruckSplit`( - vTicketFk INT +CREATE DEFINER=`vn`@`localhost` PROCEDURE `ticket_DelayTruckSplit`( + vTicketFk INT ) -BEGIN -/** - * Splita las lineas de ticket que no estan ubicadas - * - * @param vTicketFk Id ticket - */ - DECLARE vNewTicketFk INT; - DECLARE vTotalLines INT; - DECLARE vLinesToSplit INT; - - DROP TEMPORARY TABLE IF EXISTS tmp.SalesToSplit; - - SELECT COUNT(*) INTO vTotalLines - FROM sale - WHERE ticketFk = vTicketFk; - - CREATE TEMPORARY TABLE tmp.SalesToSplit - SELECT s.id saleFk - FROM ticket t - JOIN sale s ON t.id = s.ticketFk - LEFT JOIN ( - SELECT ish.itemFk itemFk, - SUM(ish.visible) visible, - s.warehouseFk warehouseFk - FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON p.id = sh.parkingFk - JOIN sector s ON s.id = p.sectorFk - GROUP BY ish.itemFk, - s.warehouseFk - ) issw ON issw.itemFk = s.itemFk - AND issw.warehouseFk = t.warehouseFk - WHERE s.quantity > IFNULL(issw.visible, 0) - AND s.quantity > 0 - AND NOT s.isPicked - AND NOT s.reserved - AND t.id = vTicketFk; - - SELECT COUNT(*) INTO vLinesToSplit - FROM tmp.SalesToSplit; - - IF vLinesToSplit = vTotalLines AND vLinesToSplit > 0 THEN - SET vNewTicketFk = vTicketFk; - ELSE - CALL ticket_Clone(vTicketFk, vNewTicketFk); - UPDATE sale s - JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id - SET s.ticketFk = vNewTicketFk; - END IF; - - CALL ticket_setState(vNewTicketFk, 'FIXING'); - - DROP TEMPORARY TABLE tmp.SalesToSplit; +BEGIN +/** + * Splita las lineas de ticket que no estan ubicadas + * + * @param vTicketFk Id ticket + */ + DECLARE vNewTicketFk INT; + DECLARE vTotalLines INT; + DECLARE vLinesToSplit INT; + + DROP TEMPORARY TABLE IF EXISTS tmp.SalesToSplit; + + SELECT COUNT(*) INTO vTotalLines + FROM sale + WHERE ticketFk = vTicketFk; + + CREATE TEMPORARY TABLE tmp.SalesToSplit + SELECT s.id saleFk + FROM ticket t + JOIN sale s ON t.id = s.ticketFk + LEFT JOIN ( + SELECT ish.itemFk itemFk, + SUM(ish.visible) visible, + s.warehouseFk warehouseFk + FROM itemShelving ish + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON p.id = sh.parkingFk + JOIN sector s ON s.id = p.sectorFk + GROUP BY ish.itemFk, + s.warehouseFk + ) issw ON issw.itemFk = s.itemFk + AND issw.warehouseFk = t.warehouseFk + WHERE s.quantity > IFNULL(issw.visible, 0) + AND s.quantity > 0 + AND NOT s.isPicked + AND NOT s.reserved + AND t.id = vTicketFk; + + SELECT COUNT(*) INTO vLinesToSplit + FROM tmp.SalesToSplit; + + IF vLinesToSplit = vTotalLines AND vLinesToSplit > 0 THEN + SET vNewTicketFk = vTicketFk; + ELSE + CALL ticket_Clone(vTicketFk, vNewTicketFk); + UPDATE sale s + JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id + SET s.ticketFk = vNewTicketFk; + END IF; + + CALL ticket_setState(vNewTicketFk, 'FIXING'); + + DROP TEMPORARY TABLE tmp.SalesToSplit; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73860,84 +74246,84 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`vn`@`localhost` PROCEDURE `ticket_doCmr`(vSelf INT) -BEGIN -/** -* Crea u actualiza la información del CMR asociado con -* un ticket específico en caso de que sea necesario. -* -* @param vSelf El id del ticket -*/ - DECLARE vCmrFk INT; - SELECT cmrFk INTO vCmrFk - FROM ticket - WHERE id = vSelf; - - CREATE OR REPLACE TEMPORARY TABLE tTicket - SELECT wo.firstName, - v.numberPlate, - com.id companyFk, - a.id addressFk, - c2.defaultAddressFk, - IFNULL(sat.supplierFk, su.id) supplierFk, - t.landed - FROM ticket t - JOIN ticketState ts ON ts.ticketFk = t.id - JOIN `state` s ON s.id = ts.stateFk - JOIN alertLevel al ON al.id = s.alertLevel - JOIN client c ON c.id = t.clientFk - JOIN `address` a ON a.id = t.addressFk - JOIN province p ON p.id = a.provinceFk - JOIN country co ON co.id = p.countryFk - JOIN warehouse w ON w.id = t.warehouseFk - JOIN company com ON com.id = t.companyFk - JOIN client c2 ON c2.id = com.clientFk - JOIN supplierAccount sa ON sa.id = com.supplierAccountFk - JOIN supplier su ON su.id = sa.supplierFk - LEFT JOIN route r ON r.id = t.routeFk - LEFT JOIN worker wo ON wo.id = r.workerFk - LEFT JOIN vehicle v ON v.id = r.vehicleFk - LEFT JOIN agencyMode am ON am.id = r.agencyModeFk - LEFT JOIN agency ag ON ag.id = am.agencyFk - LEFT JOIN supplierAgencyTerm sat ON sat.agencyFk = ag.id - AND wo.isFreelance - WHERE al.code IN ('PACKED', 'DELIVERED') - AND co.code <> 'ES' - AND am.name <> 'ABONO' - AND w.code = 'ALG' - AND t.id = vSelf - GROUP BY t.id; - - IF vCmrFk THEN - UPDATE cmr c - JOIN tTicket t - SET c.senderInstruccions = t.firstName, - c.truckPlate = t.numberPlate, - c.companyFk = t.companyFk, - c.addressToFk = t.addressFk, - c.addressFromFk = t.defaultAddressFk, - c.supplierFk = t.supplierFk, - c.ead = t.landed - WHERE id = vCmrFk; - ELSE - INSERT INTO cmr ( - senderInstruccions, - truckPlate, - companyFk, - addressToFk, - addressFromFk, - supplierFk, - ead - ) - SELECT * FROM tTicket; - - IF (SELECT EXISTS(SELECT * FROM tTicket)) THEN - UPDATE ticket - SET cmrFk = LAST_INSERT_ID() - WHERE id = vSelf; - END IF; - END IF; - - DROP TEMPORARY TABLE tTicket; +BEGIN +/** +* Crea u actualiza la información del CMR asociado con +* un ticket específico en caso de que sea necesario. +* +* @param vSelf El id del ticket +*/ + DECLARE vCmrFk INT; + SELECT cmrFk INTO vCmrFk + FROM ticket + WHERE id = vSelf; + + CREATE OR REPLACE TEMPORARY TABLE tTicket + SELECT wo.firstName, + v.numberPlate, + com.id companyFk, + a.id addressFk, + c2.defaultAddressFk, + IFNULL(sat.supplierFk, su.id) supplierFk, + t.landed + FROM ticket t + JOIN ticketState ts ON ts.ticketFk = t.id + JOIN `state` s ON s.id = ts.stateFk + JOIN alertLevel al ON al.id = s.alertLevel + JOIN client c ON c.id = t.clientFk + JOIN `address` a ON a.id = t.addressFk + JOIN province p ON p.id = a.provinceFk + JOIN country co ON co.id = p.countryFk + JOIN warehouse w ON w.id = t.warehouseFk + JOIN company com ON com.id = t.companyFk + JOIN client c2 ON c2.id = com.clientFk + JOIN supplierAccount sa ON sa.id = com.supplierAccountFk + JOIN supplier su ON su.id = sa.supplierFk + LEFT JOIN route r ON r.id = t.routeFk + LEFT JOIN worker wo ON wo.id = r.workerFk + LEFT JOIN vehicle v ON v.id = r.vehicleFk + LEFT JOIN agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN agency ag ON ag.id = am.agencyFk + LEFT JOIN supplierAgencyTerm sat ON sat.agencyFk = ag.id + AND wo.isFreelance + WHERE al.code IN ('PACKED', 'DELIVERED') + AND co.code <> 'ES' + AND am.name <> 'ABONO' + AND w.code = 'ALG' + AND t.id = vSelf + GROUP BY t.id; + + IF vCmrFk THEN + UPDATE cmr c + JOIN tTicket t + SET c.senderInstruccions = t.firstName, + c.truckPlate = t.numberPlate, + c.companyFk = t.companyFk, + c.addressToFk = t.addressFk, + c.addressFromFk = t.defaultAddressFk, + c.supplierFk = t.supplierFk, + c.ead = t.landed + WHERE id = vCmrFk; + ELSE + INSERT INTO cmr ( + senderInstruccions, + truckPlate, + companyFk, + addressToFk, + addressFromFk, + supplierFk, + ead + ) + SELECT * FROM tTicket; + + IF (SELECT EXISTS(SELECT * FROM tTicket)) THEN + UPDATE ticket + SET cmrFk = LAST_INSERT_ID() + WHERE id = vSelf; + END IF; + END IF; + + DROP TEMPORARY TABLE tTicket; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -74401,7 +74787,9 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `ticket_getTax`(IN vTaxArea VARCHAR(25)) +CREATE DEFINER=`vn`@`localhost` PROCEDURE `ticket_getTax`( + vTaxArea VARCHAR(25) +) BEGIN /** * Calcula la base imponible, el IVA y el recargo de equivalencia para @@ -74435,30 +74823,39 @@ BEGIN CREATE OR REPLACE TEMPORARY TABLE tmp.ticketTax (PRIMARY KEY (ticketFk, code, rate)) ENGINE = MEMORY - SELECT * FROM ( - SELECT tmpTicket.ticketFk, - bp.pgcFk, - SUM(s.quantity * s.price * (100 - s.discount) / 100 ) taxableBase, - pgc.rate, - tc.code, - bp.priority - FROM tmp.ticket tmpTicket - JOIN sale s ON s.ticketFk = tmpTicket.ticketFk - JOIN item i ON i.id = s.itemFk - JOIN ticket t ON t.id = tmpTicket.ticketFk - JOIN supplier su ON su.id = t.companyFk + WITH sales AS ( + SELECT s.ticketFk, + s.itemFk, + s.quantity * s.price * (100 - s.discount) / 100 total, + t.companyFk, + t.addressFk, + su.countryFk, + ata.areaFk, + itc.taxClassFk + FROM vn.sale s + JOIN tmp.ticket tmp ON tmp.ticketFk = s.ticketFk + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.supplier su ON su.id = t.companyFk JOIN tmp.addressTaxArea ata ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk - JOIN itemTaxCountry itc ON itc.itemFk = i.id + JOIN vn.itemTaxCountry itc ON itc.itemFk = s.itemFk AND itc.countryFk = su.countryFk - JOIN bookingPlanner bp ON bp.countryFk = su.countryFk - AND bp.taxAreaFk = ata.areaFk - AND bp.taxClassFk = itc.taxClassFk - JOIN pgc ON pgc.code = bp.pgcFk - JOIN taxClass tc ON tc.id = bp.taxClassFk - GROUP BY tmpTicket.ticketFk, pgc.code, pgc.rate - HAVING taxableBase - ) t3 + HAVING total + ) + SELECT s.ticketFk, + bp.pgcFk, + SUM(s.total) taxableBase, + pgc.rate, + tc.code, + bp.priority + FROM sales s + JOIN vn.bookingPlanner bp ON bp.countryFk = s.countryFk + AND bp.taxAreaFk = s.areaFk + AND bp.taxClassFk = s.taxClassFk + JOIN vn.pgc ON pgc.code = bp.pgcFk + JOIN vn.taxClass tc ON tc.id = bp.taxClassFk + GROUP BY s.ticketFk, pgc.code, pgc.rate + HAVING taxableBase ORDER BY priority; CREATE OR REPLACE TEMPORARY TABLE tmp.ticketServiceTax @@ -74681,12 +75078,25 @@ CREATE DEFINER=`vn`@`localhost` PROCEDURE `ticket_mergeSales`( vSelf INT ) BEGIN +/** + * Para un ticket se agrupa las diferentes líneas de venta de un mismo artículo en una sola + * siempre y cuando tengan el mismo precio y dto. + * + * @param vSelf Id de ticket + */ + DECLARE vHasSalesToMerge BOOL; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN ROLLBACK; RESIGNAL; END; + START TRANSACTION; + + SELECT id INTO vSelf + FROM ticket + WHERE id = vSelf FOR UPDATE; + CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve (PRIMARY KEY (id)) ENGINE = MEMORY @@ -74696,26 +75106,24 @@ BEGIN JOIN itemType it ON it.id = i.typeFk WHERE s.ticketFk = vSelf AND it.isMergeable - GROUP BY s.itemFk, s.price, s.discount; + GROUP BY s.itemFk, s.price, s.discount + HAVING COUNT(*) > 1; - START TRANSACTION; + SELECT COUNT(*) INTO vHasSalesToMerge FROM tSalesToPreserve; - UPDATE sale s - JOIN tSalesToPreserve stp ON stp.id = s.id - SET s.quantity = newQuantity - WHERE s.ticketFk = vSelf; + IF vHasSalesToMerge THEN + UPDATE sale s + JOIN tSalesToPreserve stp ON stp.id = s.id + SET s.quantity = newQuantity; - DELETE s.* - FROM sale s - LEFT JOIN tSalesToPreserve stp ON stp.id = s.id - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - WHERE s.ticketFk = vSelf - AND stp.id IS NULL - AND it.isMergeable; + DELETE s + FROM sale s + JOIN tSalesToPreserve stp ON stp.itemFk = s.itemFk + WHERE s.ticketFk = vSelf + AND s.id <> stp.id; + END IF; COMMIT; - DROP TEMPORARY TABLE tSalesToPreserve; END ;; DELIMITER ; @@ -75856,125 +76264,88 @@ CREATE DEFINER=`vn`@`localhost` PROCEDURE `ticket_splitItemPackingType`( vSelf INT, vOriginalItemPackingTypeFk VARCHAR(1) ) -BEGIN +proc:BEGIN /** - * Clona y reparte las ventas de un ticket en funcion del tipo de empaquetado. - * Respeta el id inicial para el tipo propuesto. + * Clona y reparte las líneas de ventas de un ticket en funcion del tipo de empaquetado. + * Respeta el id de ticket original para el tipo de empaquetado propuesto. * * @param vSelf Id ticket - * @param vOriginalItemPackingTypeFk Tipo para el que se reserva el número de ticket original + * @param vOriginalItemPackingTypeFk Tipo empaquetado que se mantiene el ticket original * @return table tmp.ticketIPT(ticketFk, itemPackingTypeFk) */ - DECLARE vItemPackingTypeFk VARCHAR(1) DEFAULT 'H'; - DECLARE vNewTicketFk INT; - DECLARE vPackingTypesToSplit INT; DECLARE vDone INT DEFAULT FALSE; + DECLARE vHasItemPackingType BOOL; + DECLARE vItemPackingTypeFk INT; + DECLARE vNewTicketFk INT; - DECLARE vSaleGroup CURSOR FOR - SELECT itemPackingTypeFk - FROM tSaleGroup - WHERE itemPackingTypeFk IS NOT NULL - ORDER BY (itemPackingTypeFk = vOriginalItemPackingTypeFk) DESC; + DECLARE vItemPackingTypes CURSOR FOR + SELECT DISTINCT itemPackingTypeFk + FROM tSalesToMove; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - START TRANSACTION; - - SELECT id - FROM sale - WHERE ticketFk = vSelf - AND NOT quantity - FOR UPDATE; - - DELETE FROM sale - WHERE NOT quantity - AND ticketFk = vSelf; - - CREATE OR REPLACE TEMPORARY TABLE tSale - (PRIMARY KEY (id)) - ENGINE = MEMORY - SELECT s.id, i.itemPackingTypeFk, IFNULL(sv.litros, 0) litros - FROM sale s - JOIN item i ON i.id = s.itemFk - LEFT JOIN saleVolume sv ON sv.saleFk = s.id - WHERE s.ticketFk = vSelf; - - CREATE OR REPLACE TEMPORARY TABLE tSaleGroup - ENGINE = MEMORY - SELECT itemPackingTypeFk, SUM(litros) totalLitros - FROM tSale - GROUP BY itemPackingTypeFk; - - SELECT COUNT(*) INTO vPackingTypesToSplit - FROM tSaleGroup - WHERE itemPackingTypeFk IS NOT NULL; + SELECT COUNT(*) INTO vHasItemPackingType + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + WHERE t.id = vSelf + AND i.itemPackingTypeFk = vOriginalItemPackingTypeFk; CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT( ticketFk INT, itemPackingTypeFk VARCHAR(1) - ) ENGINE = MEMORY; + ) ENGINE=MEMORY + SELECT vSelf ticketFk, vOriginalItemPackingTypeFk itemPackingTypeFk; - CASE vPackingTypesToSplit - WHEN 0 THEN - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - VALUES(vSelf, vItemPackingTypeFk); - WHEN 1 THEN - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - SELECT vSelf, itemPackingTypeFk - FROM tSaleGroup - WHERE itemPackingTypeFk IS NOT NULL; - ELSE - OPEN vSaleGroup; - FETCH vSaleGroup INTO vItemPackingTypeFk; + IF NOT vHasItemPackingType THEN + LEAVE proc; + END IF; - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - VALUES(vSelf, vItemPackingTypeFk); + CREATE OR REPLACE TEMPORARY TABLE tSalesToMove ( + ticketFk INT, + saleFk INT, + itemPackingTypeFk INT + ) ENGINE=MEMORY; - l: LOOP - SET vDone = FALSE; - FETCH vSaleGroup INTO vItemPackingTypeFk; + INSERT INTO tSalesToMove (saleFk, itemPackingTypeFk) + SELECT s.id, i.itemPackingTypeFk + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + WHERE t.id = vSelf + AND i.itemPackingTypeFk <> vOriginalItemPackingTypeFk; - IF vDone THEN - LEAVE l; - END IF; + OPEN vItemPackingTypes; - CALL ticket_Clone(vSelf, vNewTicketFk); + l: LOOP + SET vDone = FALSE; + FETCH vItemPackingTypes INTO vItemPackingTypeFk; - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - VALUES(vNewTicketFk, vItemPackingTypeFk); - END LOOP; + IF vDone THEN + LEAVE l; + END IF; - CLOSE vSaleGroup; + CALL ticket_Clone(vSelf, vNewTicketFk); - SELECT s.id - FROM sale s - JOIN tSale ts ON ts.id = s.id - JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk - FOR UPDATE; + UPDATE tSalesToMove + SET ticketFk = vNewTicketFk + WHERE itemPackingTypeFk = vItemPackingTypeFk; - UPDATE sale s - JOIN tSale ts ON ts.id = s.id - JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk - SET s.ticketFk = t.ticketFk; + END LOOP; - SELECT itemPackingTypeFk INTO vItemPackingTypeFk - FROM tSaleGroup sg - WHERE sg.itemPackingTypeFk IS NOT NULL - ORDER BY sg.itemPackingTypeFk - LIMIT 1; + CLOSE vItemPackingTypes; - UPDATE sale s - JOIN tSale ts ON ts.id = s.id - JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = vItemPackingTypeFk - SET s.ticketFk = t.ticketFk - WHERE ts.itemPackingTypeFk IS NULL; - END CASE; + UPDATE sale s + JOIN tSalesToMove stm ON stm.saleFk = s.id + SET s.ticketFk = stm.ticketFk + WHERE stm.ticketFk; - COMMIT; + INSERT INTO tmp.ticketIPT (ticketFk, itemPackingTypeFk) + SELECT ticketFk, itemPackingTypeFk + FROM tSalesToMove + GROUP BY ticketFk; - DROP TEMPORARY TABLE - tSale, - tSaleGroup; + DROP TEMPORARY TABLE tSalesToMove; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -80405,6 +80776,8 @@ BEGIN SET businessFk = vNewBusinessFk WHERE id = vSelf; + CALL queueMember_updateQueue(vNewBusinessFk); + IF vOldBusinessFk IS NULL THEN CALL account.account_enable(vSelf); @@ -81606,126 +81979,126 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `zone_getLeaves`( - vSelf INT, - vParentFk INT, - vSearch VARCHAR(255), - vHasInsert BOOL +CREATE DEFINER=`vn`@`localhost` PROCEDURE `zone_getLeaves`( + vSelf INT, + vParentFk INT, + vSearch VARCHAR(255), + vHasInsert BOOL ) -BEGIN -/** - * Devuelve las ubicaciones incluidas 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 - * @param vHasInsert Indica si inserta en tmp.zoneNodes - * Optional @table tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - */ - DECLARE vIsNumber BOOL; - DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch <> ''; - - CREATE OR REPLACE 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 - CREATE OR REPLACE TEMPORARY TABLE tChilds - (INDEX(id)) - ENGINE = MEMORY - SELECT id FROM tNodes; - - CREATE OR REPLACE TEMPORARY TABLE tParents - (INDEX(id)) - 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 NOT ROW_COUNT() 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 NOT vIsSearch THEN - INSERT IGNORE INTO tNodes - SELECT id - FROM zoneGeo - WHERE parentFk <=> vParentFk; - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tZones - SELECT g.id, - g.name, - g.parentFk, - g.sons, - NOT g.sons OR `type` = 'country' isChecked, - i.isIncluded selected, - g.`depth`, - 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 - ORDER BY g.`depth`, selected DESC, g.name; - - IF vHasInsert THEN - INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - SELECT id, - name, - parentFk, - sons, - isChecked, - vSelf - FROM tZones - WHERE selected - OR (selected IS NULL AND vParentFk IS NOT NULL); - ELSE - SELECT id, - name, - parentFk, - sons, - selected - FROM tZones - ORDER BY `depth`, selected DESC, name; - END IF; - - DROP TEMPORARY TABLE tNodes, tZones; +BEGIN +/** + * Devuelve las ubicaciones incluidas 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 + * @param vHasInsert Indica si inserta en tmp.zoneNodes + * Optional @table tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + */ + DECLARE vIsNumber BOOL; + DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch <> ''; + + CREATE OR REPLACE 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 + CREATE OR REPLACE TEMPORARY TABLE tChilds + (INDEX(id)) + ENGINE = MEMORY + SELECT id FROM tNodes; + + CREATE OR REPLACE TEMPORARY TABLE tParents + (INDEX(id)) + 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 NOT ROW_COUNT() 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 NOT vIsSearch THEN + INSERT IGNORE INTO tNodes + SELECT id + FROM zoneGeo + WHERE parentFk <=> vParentFk; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tZones + SELECT g.id, + g.name, + g.parentFk, + g.sons, + NOT g.sons OR `type` = 'country' isChecked, + i.isIncluded selected, + g.`depth`, + 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 + ORDER BY g.`depth`, selected DESC, g.name; + + IF vHasInsert THEN + INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + SELECT id, + name, + parentFk, + sons, + isChecked, + vSelf + FROM tZones + WHERE selected + OR (selected IS NULL AND vParentFk IS NOT NULL); + ELSE + SELECT id, + name, + parentFk, + sons, + selected + FROM tZones + ORDER BY `depth`, selected DESC, name; + END IF; + + DROP TEMPORARY TABLE tNodes, tZones; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -81908,48 +82281,48 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`vn`@`localhost` PROCEDURE `zone_getPostalCode`(vSelf INT) -BEGIN -/** - * Devuelve los códigos postales incluidos en una zona - */ - DECLARE vGeoFk INT DEFAULT NULL; - - CREATE OR REPLACE TEMPORARY TABLE tmp.zoneNodes ( - geoFk INT, - name VARCHAR(100), - parentFk INT, - sons INT, - isChecked BOOL DEFAULT 0, - zoneFk INT, - PRIMARY KEY zoneNodesPk (zoneFk, geoFk), - INDEX(geoFk)) - ENGINE = MEMORY; - - CALL zone_getLeaves(vSelf, NULL , NULL, TRUE); - - UPDATE tmp.zoneNodes - SET isChecked = 0 - WHERE parentFk IS NULL; - - myLoop: LOOP - SET vGeoFk = NULL; - SELECT geoFk INTO vGeoFk - FROM tmp.zoneNodes - WHERE NOT isChecked - LIMIT 1; - - CALL zone_getLeaves(vSelf, vGeoFk, NULL, TRUE); - UPDATE tmp.zoneNodes - SET isChecked = TRUE - WHERE geoFk = vGeoFk; - - IF vGeoFk IS NULL THEN - LEAVE myLoop; - END IF; - END LOOP; - - DELETE FROM tmp.zoneNodes - WHERE sons > 0; +BEGIN +/** + * Devuelve los códigos postales incluidos en una zona + */ + DECLARE vGeoFk INT DEFAULT NULL; + + CREATE OR REPLACE TEMPORARY TABLE tmp.zoneNodes ( + geoFk INT, + name VARCHAR(100), + parentFk INT, + sons INT, + isChecked BOOL DEFAULT 0, + zoneFk INT, + PRIMARY KEY zoneNodesPk (zoneFk, geoFk), + INDEX(geoFk)) + ENGINE = MEMORY; + + CALL zone_getLeaves(vSelf, NULL , NULL, TRUE); + + UPDATE tmp.zoneNodes + SET isChecked = 0 + WHERE parentFk IS NULL; + + myLoop: LOOP + SET vGeoFk = NULL; + SELECT geoFk INTO vGeoFk + FROM tmp.zoneNodes + WHERE NOT isChecked + LIMIT 1; + + CALL zone_getLeaves(vSelf, vGeoFk, NULL, TRUE); + UPDATE tmp.zoneNodes + SET isChecked = TRUE + WHERE geoFk = vGeoFk; + + IF vGeoFk IS NULL THEN + LEAVE myLoop; + END IF; + END LOOP; + + DELETE FROM tmp.zoneNodes + WHERE sons > 0; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -82245,7 +82618,6 @@ SET character_set_client = utf8; 1 AS `send_mail`, 1 AS `tpv`, 1 AS `code`, - 1 AS `show_AgencyName`, 1 AS `isRiskFree` */; SET character_set_client = @saved_cs_client; @@ -82416,7 +82788,6 @@ SET character_set_client = utf8; 1 AS `credito`, 1 AS `Id_Pais`, 1 AS `activo`, - 1 AS `gestdoc_id`, 1 AS `calidad`, 1 AS `pay_met_id`, 1 AS `created`, @@ -82496,21 +82867,6 @@ SET character_set_client = utf8; 1 AS `itemOriginalFk` */; SET character_set_client = @saved_cs_client; --- --- Temporary table structure for view `Compres_mark` --- - -DROP TABLE IF EXISTS `Compres_mark`; -/*!50001 DROP VIEW IF EXISTS `Compres_mark`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `Compres_mark` AS SELECT - 1 AS `Id_Compra`, - 1 AS `comment`, - 1 AS `mark`, - 1 AS `odbc_date` */; -SET character_set_client = @saved_cs_client; - -- -- Temporary table structure for view `Consignatarios` -- @@ -88082,7 +88438,7 @@ USE `vn2008`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `Agencias` AS select `am`.`id` AS `Id_Agencia`,`am`.`name` AS `Agencia`,`am`.`description` AS `description`,`am`.`deliveryMethodFk` AS `Vista`,`am`.`m3` AS `m3`,`am`.`web` AS `web`,`am`.`agencyFk` AS `agency_id`,`am`.`inflation` AS `inflacion`,`am`.`isVolumetric` AS `is_volumetric`,`am`.`reportMail` AS `send_mail`,`am`.`isActive` AS `tpv`,`am`.`code` AS `code`,`am`.`showAgencyName` AS `show_AgencyName`,`am`.`isRiskFree` AS `isRiskFree` from `vn`.`agencyMode` `am` */; +/*!50001 VIEW `Agencias` AS select `am`.`id` AS `Id_Agencia`,`am`.`name` AS `Agencia`,`am`.`description` AS `description`,`am`.`deliveryMethodFk` AS `Vista`,`am`.`m3` AS `m3`,`am`.`web` AS `web`,`am`.`agencyFk` AS `agency_id`,`am`.`inflation` AS `inflacion`,`am`.`isVolumetric` AS `is_volumetric`,`am`.`reportMail` AS `send_mail`,`am`.`isActive` AS `tpv`,`am`.`code` AS `code`,`am`.`isRiskFree` AS `isRiskFree` from `vn`.`agencyMode` `am` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -88172,7 +88528,7 @@ USE `vn2008`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `Clientes` AS select `c`.`id` AS `id_cliente`,`c`.`name` AS `cliente`,`c`.`fi` AS `if`,`c`.`socialName` AS `razonSocial`,`c`.`contact` AS `contacto`,`c`.`street` AS `domicilio`,`c`.`city` AS `poblacion`,`c`.`postcode` AS `codPostal`,`c`.`phone` AS `telefono`,`c`.`mobile` AS `movil`,`c`.`isRelevant` AS `real`,`c`.`email` AS `e-mail`,`c`.`iban` AS `iban`,`c`.`dueDay` AS `vencimiento`,`c`.`accountingAccount` AS `Cuenta`,`c`.`isEqualizated` AS `RE`,`c`.`provinceFk` AS `province_id`,`c`.`hasToInvoice` AS `invoice`,`c`.`credit` AS `credito`,`c`.`countryFk` AS `Id_Pais`,`c`.`isActive` AS `activo`,`c`.`gestdocFk` AS `gestdoc_id`,`c`.`quality` AS `calidad`,`c`.`payMethodFk` AS `pay_met_id`,`c`.`created` AS `created`,`c`.`isToBeMailed` AS `mail`,`c`.`contactChannelFk` AS `chanel_id`,`c`.`hasSepaVnl` AS `sepaVnl`,`c`.`hasCoreVnl` AS `coreVnl`,`c`.`hasCoreVnh` AS `coreVnh`,`c`.`hasLcr` AS `hasLcr`,`c`.`defaultAddressFk` AS `default_address`,`c`.`riskCalculated` AS `risk_calculated`,`c`.`hasToInvoiceByAddress` AS `invoiceByAddress`,`c`.`isTaxDataChecked` AS `contabilizado`,`c`.`isFreezed` AS `congelado`,`c`.`creditInsurance` AS `creditInsurance`,`c`.`isCreatedAsServed` AS `isCreatedAsServed`,`c`.`hasInvoiceSimplified` AS `hasInvoiceSimplified`,`c`.`salesPersonFk` AS `Id_Trabajador`,`c`.`isVies` AS `vies`,`c`.`bankEntityFk` AS `bankEntityFk`,`c`.`typeFk` AS `typeFk` from `vn`.`client` `c` */; +/*!50001 VIEW `Clientes` AS select `c`.`id` AS `id_cliente`,`c`.`name` AS `cliente`,`c`.`fi` AS `if`,`c`.`socialName` AS `razonSocial`,`c`.`contact` AS `contacto`,`c`.`street` AS `domicilio`,`c`.`city` AS `poblacion`,`c`.`postcode` AS `codPostal`,`c`.`phone` AS `telefono`,`c`.`mobile` AS `movil`,`c`.`isRelevant` AS `real`,`c`.`email` AS `e-mail`,`c`.`iban` AS `iban`,`c`.`dueDay` AS `vencimiento`,`c`.`accountingAccount` AS `Cuenta`,`c`.`isEqualizated` AS `RE`,`c`.`provinceFk` AS `province_id`,`c`.`hasToInvoice` AS `invoice`,`c`.`credit` AS `credito`,`c`.`countryFk` AS `Id_Pais`,`c`.`isActive` AS `activo`,`c`.`quality` AS `calidad`,`c`.`payMethodFk` AS `pay_met_id`,`c`.`created` AS `created`,`c`.`isToBeMailed` AS `mail`,`c`.`contactChannelFk` AS `chanel_id`,`c`.`hasSepaVnl` AS `sepaVnl`,`c`.`hasCoreVnl` AS `coreVnl`,`c`.`hasCoreVnh` AS `coreVnh`,`c`.`hasLcr` AS `hasLcr`,`c`.`defaultAddressFk` AS `default_address`,`c`.`riskCalculated` AS `risk_calculated`,`c`.`hasToInvoiceByAddress` AS `invoiceByAddress`,`c`.`isTaxDataChecked` AS `contabilizado`,`c`.`isFreezed` AS `congelado`,`c`.`creditInsurance` AS `creditInsurance`,`c`.`isCreatedAsServed` AS `isCreatedAsServed`,`c`.`hasInvoiceSimplified` AS `hasInvoiceSimplified`,`c`.`salesPersonFk` AS `Id_Trabajador`,`c`.`isVies` AS `vies`,`c`.`bankEntityFk` AS `bankEntityFk`,`c`.`typeFk` AS `typeFk` from `vn`.`client` `c` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -88213,24 +88569,6 @@ USE `vn2008`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; --- --- Final view structure for view `Compres_mark` --- - -/*!50001 DROP VIEW IF EXISTS `Compres_mark`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_unicode_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `Compres_mark` AS select `bm`.`id` AS `Id_Compra`,`bm`.`comment` AS `comment`,`bm`.`mark` AS `mark`,`bm`.`odbcDate` AS `odbc_date` from `vn`.`buyMark` `bm` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - -- -- Final view structure for view `Consignatarios` -- @@ -90472,4 +90810,4 @@ USE `vn2008`; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2024-10-03 7:42:53 +-- Dump completed on 2024-11-12 7:06:20 diff --git a/db/dump/.dump/triggers.sql b/db/dump/.dump/triggers.sql index 74190df36..7152187bb 100644 --- a/db/dump/.dump/triggers.sql +++ b/db/dump/.dump/triggers.sql @@ -1128,6 +1128,28 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`orderRow_afterInsert` + AFTER INSERT ON `orderRow` + FOR EACH ROW +BEGIN + UPDATE `order` + SET rowUpdated = util.VN_NOW() + WHERE id = NEW.orderFk; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; -- -- Current Database: `pbx` @@ -2432,11 +2454,21 @@ DELIMITER ;; AFTER UPDATE ON `business` FOR EACH ROW BEGIN + DECLARE vIsActive BOOL; + DECLARE vExtension VARCHAR(10); + CALL worker_updateBusiness(NEW.workerFk); IF NOT (OLD.workerFk <=> NEW.workerFk) THEN CALL worker_updateBusiness(OLD.workerFk); END IF; + + IF NOT (OLD.departmentFk <=> NEW.departmentFk) THEN + SELECT COUNT(*) INTO vIsActive FROM worker WHERE businessFk = NEW.id; + IF vIsActive THEN + CALL queueMember_updateQueue(NEW.id); + END IF; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6554,6 +6586,9 @@ BEGIN SET NEW.userFk = account.myUser_getId(); END IF; + IF NEW.shelvingFk <> OLD.shelvingFk THEN + SET NEW.movingState = NULL; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6654,11 +6689,11 @@ DELIMITER ;; AFTER INSERT ON `itemShelvingSale` FOR EACH ROW BEGIN - UPDATE sale s JOIN operator o ON o.workerFk = account.myUser_getId() - SET s.isPicked = IF(o.isOnReservationMode, s.isPicked, TRUE) - WHERE id = NEW.saleFk; + JOIN sector se ON se.id = o.sectorFk + SET s.isPicked = IF(IFNULL(se.isOnReservationMode, o.isOnReservationMode), s.isPicked, TRUE) + WHERE s.id = NEW.saleFk; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -9988,6 +10023,8 @@ DELIMITER ;; BEFORE INSERT ON `ticketRefund` FOR EACH ROW BEGIN + CALL ticketRefund_upsert(NEW.refundTicketFk, NEW.originalTicketFk); + SET NEW.editorFk = account.myUser_getId(); END */;; DELIMITER ; @@ -10008,6 +10045,8 @@ DELIMITER ;; BEFORE UPDATE ON `ticketRefund` FOR EACH ROW BEGIN + CALL ticketRefund_upsert(NEW.refundTicketFk, NEW.originalTicketFk); + SET NEW.editorFk = account.myUser_getId(); END */;; DELIMITER ; @@ -10678,6 +10717,15 @@ DELIMITER ;; FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); + + IF NEW.travelFk IS NULL AND + (SELECT COUNT(*) FROM travelThermograph + WHERE thermographFk = NEW.thermographFk + AND travelFk IS NULL + AND id <> NEW.id) > 0 + THEN + CALL util.throw('Duplicate thermographFk without travelFk not allowed.'); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10698,6 +10746,15 @@ DELIMITER ;; FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); + + IF NEW.travelFk IS NULL AND + (SELECT COUNT(*) FROM travelThermograph + WHERE thermographFk = NEW.thermographFk + AND travelFk IS NULL + AND id <> NEW.id) > 0 + THEN + CALL util.throw('Duplicate thermographFk without travelFk not allowed.'); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -11469,4 +11526,4 @@ USE `vn2008`; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2024-10-03 7:43:14 +-- Dump completed on 2024-11-12 7:06:44 diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index bb620ac49..e5d5f53dc 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -400,11 +400,11 @@ INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city (1108, 'Charles Xavier', '22641921P', 'PROFESSOR X', 'Beast', '3800 VICTORY PKWY, CINCINNATI, OH 45207, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'CharlesXavier@mydomain.com', NULL, 0, 1234567890, 0, 5, 1, 300, 13, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, NULL, 0, 0, 19, 0, 'florist','normal'), (1109, 'Bruce Banner', '16104829E', 'HULK', 'Black widow', 'SOMEWHERE IN NEW YORK', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceBanner@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 0, 0, NULL, 0, 0, 9, 0, 'florist','normal'), (1110, 'Jessica Jones', '58282869H', 'JESSICA JONES', 'Luke Cage', 'NYCC 2015 POSTER', 'Gotham', 46460, 1111111111, 222222222, 1, 'JessicaJones@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, NULL, 0, 0, NULL, 1, 'florist','normal'), - (1111, 'Missing', NULL, 'MISSING MAN', 'Anton', 'THE SPACE, UNIVERSE FAR AWAY', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 0, 1, 0, NULL, 1, 0, NULL, 0, 'others','loses'), - (1112, 'Trash', NULL, 'GARBAGE MAN', 'Unknown name', 'NEW YORK CITY, UNDERGROUND', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 0, 1, 0, NULL, 1, 0, NULL, 0, 'others','loses'); + (1111, 'Missing', NULL, 'MISSING MAN', 'Anton', 'THE SPACE, UNIVERSE FAR AWAY', 'Gotham', 46460, 1111111111, 222222222, 0, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 0, 1, 0, NULL, 1, 0, NULL, 0, 'others','loses'), + (1112, 'Trash', NULL, 'GARBAGE MAN', 'Unknown name', 'NEW YORK CITY, UNDERGROUND', 'Gotham', 46460, 1111111111, 222222222, 0, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 0, 1, 0, NULL, 1, 0, NULL, 0, 'others','loses'); INSERT INTO `vn`.`client`(`id`, `name`, `fi`, `socialName`, `contact`, `street`, `city`, `postcode`, `isRelevant`, `email`, `iban`,`dueDay`,`accountingAccount`, `isEqualizated`, `provinceFk`, `hasToInvoice`, `credit`, `countryFk`, `isActive`, `quality`, `payMethodFk`,`created`, `isTaxDataChecked`) - SELECT id, name, CONCAT(RPAD(CONCAT(id,9),8,id),'A'), UPPER(CONCAT(name, 'Social')), CONCAT(name, 'Contact'), UPPER(CONCAT(name, 'Street')), 'GOTHAM', 46460, 1, CONCAT(name,'@mydomain.com'), NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1 + SELECT id, name, CONCAT(RPAD(CONCAT(id,9),8,id),'A'), UPPER(CONCAT(name, 'Social')), CONCAT(name, 'Contact'), UPPER(CONCAT(name, 'Street')), 'GOTHAM', 46460, 0, CONCAT(name,'@mydomain.com'), NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, 10, 5, util.VN_CURDATE(), 1 FROM `account`.`role` `r` WHERE `r`.`hasLogin` = 1; @@ -1254,9 +1254,9 @@ INSERT INTO `vn`.`saleComponent`(`saleFk`, `componentFk`, `value`) INSERT INTO `vn`.`itemShelving` (`itemFk`, `shelvingFk`, `visible`, `grouping`, `packing`,`buyFk`, `userFk`) VALUES - (2, 'GVC', 1, 1, 1, 2,1106), - (4, 'HEJ', 1, 1, 1, NULL,1106), - (1, 'UXN', 2, 12, 12, NULL,1106); + (2, 11, 1, 1, 1, 2,1106), + (4, 12, 1, 1, 1, NULL,1106), + (1, 13, 2, 12, 12, NULL,1106); INSERT INTO `vn`.`itemShelvingSale` (`itemShelvingFk`, `saleFk`, `quantity`, `created`, `userFk`) VALUES @@ -1505,32 +1505,32 @@ INSERT INTO `vn`.`awb` (id, code, package, weight, created, amount, transitoryFk (9, '99610289193', 302, 2972, util.VN_CURDATE(), 3871, 442, 1), (10, '07546500856', 185, 2364, util.VN_CURDATE(), 5321, 442, 1); -INSERT INTO `vn`.`travel`(`id`,`shipped`, `landed`, `warehouseInFk`, `warehouseOutFk`, `agencyModeFk`, `m3`, `kg`,`ref`, `totalEntries`, `cargoSupplierFk`, `awbFK`, `daysInForward`) - VALUES (1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), 1, 2, 1, 100.00, 1000, 'first travel', 1, 1, 1, NULL), - (2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 2, 1, 150.00, 2000, 'second travel', 2, 2, 2, NULL), - (3, util.VN_CURDATE(), util.VN_CURDATE(), 1, 2, 1, 0.00, 0.00, 'third travel', 1, 1, 3, NULL), - (4, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 3, 1, 50.00, 500, 'fourth travel', 0, 2, 4, NULL), - (5, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 3, 3, 1, 50.00, 500, 'fifth travel', 1, 1, 5, NULL), - (6, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 4, 4, 1, 50.00, 500, 'sixth travel', 1, 2, 6, NULL), - (7, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 4, 1, 50.00, 500, 'seventh travel', 2, 1, 7, 2), - (8, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 1, 1, 50.00, 500, 'eight travel', 1, 2, 10, NULL), - (10, DATE_ADD(util.VN_CURDATE(), INTERVAL +5 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL +5 DAY), 5, 1, 1, 50.00, 500, 'nineth travel', 1, 2, 10, 2), - (11, util.VN_CURDATE() - INTERVAL 1 DAY , util.VN_CURDATE(), 6, 3, 0, 50.00, 500, 'eleventh travel', 1, 2, 4, NULL), - (12, util.VN_CURDATE() , util.VN_CURDATE() + INTERVAL 1 DAY, 6, 3, 0, 50.00, 500, 'eleventh travel', 1, 2, 4, NULL); +INSERT INTO `vn`.`travel`(`id`,`shipped`, `landed`, `warehouseInFk`, `warehouseOutFk`, `agencyModeFk`, `m3`, `kg`,`ref`, `totalEntries`, `cargoSupplierFk`, `awbFK`, `isRaid`, `daysInForward`) + VALUES (1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), 1, 2, 1, 100.00, 1000, 'first travel', 1, 1, 1, FALSE, NULL), + (2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 2, 1, 150.00, 2000, 'second travel', 2, 2, 2, FALSE, NULL), + (3, util.VN_CURDATE(), util.VN_CURDATE(), 1, 2, 1, 0.00, 0.00, 'third travel', 1, 1, 3, FALSE, NULL), + (4, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 3, 1, 50.00, 500, 'fourth travel', 0, 2, 4, FALSE, NULL), + (5, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 3, 3, 1, 50.00, 500, 'fifth travel', 1, 1, 5, FALSE, NULL), + (6, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 4, 4, 1, 50.00, 500, 'sixth travel', 1, 2, 6, FALSE,NULL), + (7, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 4, 1, 50.00, 500, 'seventh travel', 2, 1, 7, TRUE, 2), + (8, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 1, 1, 50.00, 500, 'eight travel', 1, 2, 10, FALSE, NULL), + (10, DATE_ADD(util.VN_CURDATE(), INTERVAL +5 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL +5 DAY), 5, 1, 1, 50.00, 500, 'nineth travel', 1, 2, 10, TRUE, 2), + (11, util.VN_CURDATE() - INTERVAL 1 DAY , util.VN_CURDATE(), 6, 3, 0, 50.00, 500, 'eleventh travel', 1, 2, 4, FALSE, NULL), + (12, util.VN_CURDATE() , util.VN_CURDATE() + INTERVAL 1 DAY, 6, 3, 0, 50.00, 500, 'eleventh travel', 1, 2, 4, FALSE, NULL); -INSERT INTO `vn`.`entry`(`id`, `supplierFk`, `created`, `travelFk`, `isConfirmed`, `companyFk`, `invoiceNumber`, `reference`, `isExcludedFromAvailable`, `evaNotes`) - VALUES - (1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 1, 442, 'IN2001', 'Movement 1', 0, ''), - (2, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2, 0, 442, 'IN2002', 'Movement 2', 0, 'observation two'), - (3, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 3, 0, 442, 'IN2003', 'Movement 3', 0, 'observation three'), - (4, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2, 0, 69, 'IN2004', 'Movement 4', 0, 'observation four'), - (5, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 0, 442, 'IN2005', 'Movement 5', 0, 'observation five'), - (6, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 6, 0, 442, 'IN2006', 'Movement 6', 0, 'observation six'), - (7, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2007', 'Movement 7', 0, 'observation seven'), - (8, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2008', 'Movement 8', 1,''), - (9, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL +2 DAY), 10, 0, 442, 'IN2009', 'Movement 9', 1, ''), - (10, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL +2 DAY), 10, 0, 442, 'IN2009', 'Movement 10', 1, ''), - (99, 69, '2000-12-01 00:00:00.000', 11, 0, 442, 'IN2009', 'Movement 99', 0, ''); +INSERT INTO `vn`.`entry`(`id`, `supplierFk`, `created`, `travelFk`, `isConfirmed`, `companyFk`, `invoiceNumber`, `reference`, `isExcludedFromAvailable`, `evaNotes`, `typeFk`) + VALUES + (1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 1, 442, 'IN2001', 'Movement 1', 0, '', 'packaging'), + (2, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2, 0, 442, 'IN2002', 'Movement 2', 0, 'observation two', 'product'), + (3, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 3, 0, 442, 'IN2003', 'Movement 3', 0, 'observation three', 'product'), + (4, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2, 0, 69, 'IN2004', 'Movement 4', 0, 'observation four', 'product'), + (5, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 0, 442, 'IN2005', 'Movement 5', 0, 'observation five', 'product'), + (6, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 6, 0, 442, 'IN2006', 'Movement 6', 0, 'observation six', 'product'), + (7, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2007', 'Movement 7', 0, 'observation seven', 'product'), + (8, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2008', 'Movement 8', 1, '', 'product'), + (9, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL +2 DAY), 10, 0, 442, 'IN2009', 'Movement 9', 1, '', 'product'), + (10, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL +2 DAY), 10, 0, 442, 'IN2009', 'Movement 10', 1, '', 'product'), + (99, 69, util.VN_CURDATE() - INTERVAL 1 MONTH, 11, 0, 442, 'IN2009', 'Movement 99', 0, '', 'product'); INSERT INTO `vn`.`entryConfig` (`defaultEntry`, `inventorySupplierFk`, `defaultSupplierFk`) VALUES (2, 4, 1); @@ -2521,10 +2521,6 @@ INSERT INTO `vn`.`queuePriority`(`id`, `priority`, `code`) (2, 'Normal', 'normal'), (3, 'Baja', 'low'); -INSERT INTO `vn`.`workerTimeControlParams` (`id`, `dayBreak`, `weekBreak`, `weekScope`, `dayWorkMax`, `dayStayMax`, `weekMaxBreak`, `weekMaxScope`, `askInOut`) - VALUES - (1, 43200, 129600, 734400, 43200, 50400, 259200, 1296000, 36000); - INSERT IGNORE INTO `vn`.`greugeConfig` (`id`, `freightPickUpPrice`) VALUES ('1', '11'); INSERT INTO `vn`.`thermograph`(`id`, `model`) @@ -3425,7 +3421,7 @@ INSERT INTO vn.buy INSERT INTO vn.itemShelving SET id = 9931, itemFk = 999993, - shelvingFk = 'NCC', + shelvingFk = 16, visible = 10, `grouping` = 5, packing = 10; @@ -3752,7 +3748,7 @@ INSERT vn.sale USE vn; DELETE ish.* FROM vn.itemShelving ish - JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.shelving sh ON sh.id = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector s ON s.id = p.sectorFk JOIN vn.warehouse w ON w.id = s.warehouseFk @@ -3761,22 +3757,22 @@ DELETE ish.* FROM vn.itemShelving ish INSERT INTO vn.itemShelving (itemFk, shelvingFk, visible, created, `grouping`, packing, packagingFk, userFk, isChecked) VALUES - (999991, 'NAA', 8, '2023-09-20', 1, 20, NULL, 103, NULL), - (999998, 'NAA', 80, '2023-09-20', 10, 30, NULL, 103, NULL), - (1000001, 'NAA', 6, '2023-09-20', 3, 50, NULL, 103, NULL), - (1000000, 'NBB', 50, '2023-09-18', 25, 500, NULL, 103, NULL), - (999993, 'NBB', 25, '2023-09-18', NULL, 10, NULL, 103, NULL), - (999999, 'NBB', 30, '2023-09-18', 10, 500, NULL, 103, NULL), - (999993, 'NCC', 25, '2023-09-20', 5, 10, NULL, 103, NULL), - (999997, 'NCC', 10, '2023-09-20', NULL, 100, NULL, 103, NULL), - (999999, 'NCC', 40, '2023-09-20', 10, 500, NULL, 103, NULL), - (999995, 'NDD', 10, '2023-09-19', NULL, 20, NULL, 103, NULL), - (999994, 'NDD', 48, '2023-09-19', 4, 20, NULL, 103, NULL), - (1000001, 'NEE', 6, '2023-09-21', 3, 50, NULL, 103, NULL), - (999992, 'NEE', 50, '2023-09-21', NULL, 1, NULL, 103, NULL), - (1000000, 'NEE', 25, '2023-09-21', 25, 500, NULL, 103, NULL), - (999996, 'PAA', 5, '2023-09-27', 1, 5, NULL, 103, NULL), - (999997, 'PCC', 10, '2023-09-27', 5, 100, NULL, 103, NULL); + (999991, 14, 8, '2023-09-20', 1, 20, NULL, 103, NULL), + (999998, 14, 80, '2023-09-20', 10, 30, NULL, 103, NULL), + (1000001, 14, 6, '2023-09-20', 3, 50, NULL, 103, NULL), + (1000000, 15, 50, '2023-09-18', 25, 500, NULL, 103, NULL), + (999993, 15, 25, '2023-09-18', NULL, 10, NULL, 103, NULL), + (999999, 15, 30, '2023-09-18', 10, 500, NULL, 103, NULL), + (999993, 16, 25, '2023-09-20', 5, 10, NULL, 103, NULL), + (999997, 16, 10, '2023-09-20', NULL, 100, NULL, 103, NULL), + (999999, 16, 40, '2023-09-20', 10, 500, NULL, 103, NULL), + (999995, 17, 10, '2023-09-19', NULL, 20, NULL, 103, NULL), + (999994, 17, 48, '2023-09-19', 4, 20, NULL, 103, NULL), + (1000001, 18, 6, '2023-09-21', 3, 50, NULL, 103, NULL), + (999992, 18, 50, '2023-09-21', NULL, 1, NULL, 103, NULL), + (1000000, 18, 25, '2023-09-21', 25, 500, NULL, 103, NULL), + (999996, 19, 5, '2023-09-27', 1, 5, NULL, 103, NULL), + (999997, 21, 10, '2023-09-27', 5, 100, NULL, 103, NULL); -- Previous for Bolas de madera INSERT IGNORE INTO vn.sectorCollection @@ -4008,4 +4004,32 @@ INSERT IGNORE INTO pbx.queueMember UPDATE vn.department SET pbxQueue = '1000' WHERE name = "CAMARA"; UPDATE vn.department SET pbxQueue = '2000' WHERE name = "VENTAS"; +INSERT INTO vn.workerRelatives (workerFk, isDescendant, disabilityGradeFk, birthed, adoptionYear, isDependend, isJointCustody, updated) + VALUES + (1106, 1, NULL, 0, NULL, 0, 0, '2024-10-29 08:42:44.000'); +INSERT INTO vn.routeAction (id, name, price, isMainlineDelivered) VALUES(1, 'Pintar traje', 50.00, 0); +INSERT INTO vn.routeComplement (id, dated, workerFk, price, routeActionFk) VALUES(1, util.VN_CURDATE(), 9, 50.00, 1); + +INSERT INTO srt.buffer (id, x, y, `size`, `length`, stateFk, typeFk, isActive, code, stratus, hasWorkerWaiting, reserve, routeFk, dayMinute, lastUnloaded, hasStrapper, typeDefaultFk, motors, editorFk) + VALUES (0, 0, 0, 0, NULL, 3, 1, 0, 'ENT', 0, 0, NULL, NULL, NULL, NULL, 0, 1, 1, NULL), + (1, 0, 9900, 0, NULL, 1, 0, 0, 'NOK', 0, 0, NULL, NULL, NULL, NULL, 0, 1, 1, NULL), + (2, 0, 0, 450, 13000, 1, 0, 1, '01A', 1, 1, NULL, NULL, NULL, NULL, 0, 1, 1, NULL), + (3, 1400, 0, 450, 13000, 1, 0, 1, '01B', 1, 0, NULL, NULL, NULL, NULL, 0, 1, 1, NULL), + (4, 0, 500, 500, 13000, 1, 4, 1, '02A', 2, 1, NULL, NULL, NULL, NULL, 1, 4, 13, NULL), + (5, 1400, 500, 500, 13000, 1, 4, 1, '02B', 2, 1, NULL, NULL, NULL, NULL, 1, 4, 13, NULL), + (6, 0, 1000, 500, 13000, 1, 1, 1, '03A', 3, 0, NULL, NULL, NULL, NULL, 0, 1, 1, NULL), + (7, 1400, 1000, 500, 13000, 1, 1, 1, '03B', 3, 0, NULL, NULL, NULL, NULL, 0, 1, 1, NULL), + (8, 0, 1500, 500, 13000, 1, 0, 1, '04A', 4, 0, NULL, NULL, NULL, NULL, 0, 1, 1, NULL), + (9, 1400, 1500, 500, 13000, 1, 1, 1, '04B', 4, 0, NULL, NULL, NULL, NULL, 0, 1, 1, NULL), + (10, 0, 2000, 500, 13000, 1, 1, 1, '05A', 5, 0, NULL, NULL, NULL, NULL, 0, 1, 1, NULL); + +INSERT IGNORE INTO vn.saySimpleCountry (countryFk, channel) + VALUES (19, '1169'), + (8, '1183'); + +INSERT IGNORE INTO vn.saySimpleConfig (url, defaultChannel) + VALUES ('saysimle-url-mock', 1320); + +INSERT INTO vn.workerIrpf (workerFk,spouseNif, geographicMobilityDate) + VALUES (1106,'26493101E','2019-09-20'); diff --git a/db/routines/account/views/myUser.sql b/db/routines/account/views/myUser.sql index f520d893b..8d927dc0f 100644 --- a/db/routines/account/views/myUser.sql +++ b/db/routines/account/views/myUser.sql @@ -7,8 +7,7 @@ AS SELECT `u`.`id` AS `id`, `u`.`email` AS `email`, `u`.`nickname` AS `nickname`, `u`.`lang` AS `lang`, - `u`.`role` AS `role`, - `u`.`recoverPass` AS `recoverPass` + `u`.`role` AS `role` FROM `account`.`user` `u` WHERE `u`.`name` = `myUser_getName`() WITH CASCADED CHECK OPTION diff --git a/db/routines/bs/procedures/inventoryDiscrepancyDetail_replace.sql b/db/routines/bs/procedures/inventoryDiscrepancyDetail_replace.sql index 863005373..b698f0e3e 100644 --- a/db/routines/bs/procedures/inventoryDiscrepancyDetail_replace.sql +++ b/db/routines/bs/procedures/inventoryDiscrepancyDetail_replace.sql @@ -32,7 +32,7 @@ BEGIN CREATE OR REPLACE TEMPORARY TABLE tVisible SELECT itemFk, SUM(visible) totalVisible FROM vn.itemShelving ish - JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.shelving sh ON sh.id = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector sc ON sc.id = p.sectorFk WHERE sc.warehouseFk = vWarehouseFk diff --git a/db/routines/cache/procedures/availableNoRaids_refresh.sql b/db/routines/cache/procedures/availableNoRaids_refresh.sql index efbbf6a13..447300305 100644 --- a/db/routines/cache/procedures/availableNoRaids_refresh.sql +++ b/db/routines/cache/procedures/availableNoRaids_refresh.sql @@ -53,7 +53,7 @@ proc: BEGIN WHERE t.landed BETWEEN vInventoryDate AND vStartDate AND t.warehouseInFk = vWarehouse AND s.name != 'INVENTARIO' - AND NOT t.daysInForward + AND NOT t.isRaid GROUP BY b.itemFk ) c JOIN vn.item i ON i.id = c.itemFk diff --git a/db/routines/edi/triggers/supplyResponse_afterUpdate.sql b/db/routines/edi/triggers/supplyResponse_afterUpdate.sql index 28a8c9466..f3e5aaefd 100644 --- a/db/routines/edi/triggers/supplyResponse_afterUpdate.sql +++ b/db/routines/edi/triggers/supplyResponse_afterUpdate.sql @@ -14,7 +14,7 @@ BEGIN b.stickers = NEW.NumberOfUnits WHERE i.supplyResponseFk = NEW.ID AND am.name = 'LOGIFLORA' - AND tr.daysInForward + AND tr.isRaid AND tr.landed >= util.VN_CURDATE(); END$$ diff --git a/db/routines/hedera/procedures/item_getVisible.sql b/db/routines/hedera/procedures/item_getVisible.sql index 365161bdf..d5bbe9d76 100644 --- a/db/routines/hedera/procedures/item_getVisible.sql +++ b/db/routines/hedera/procedures/item_getVisible.sql @@ -59,7 +59,7 @@ BEGIN JOIN vn.travel t ON t.id = e.travelFk WHERE t.landed BETWEEN vDateInv AND vDate AND t.warehouseInFk = vWarehouse - AND NOT t.daysInForward + AND NOT t.isRaid UNION ALL SELECT b.itemFk, -b.quantity FROM vn.buy b @@ -67,7 +67,7 @@ BEGIN JOIN vn.travel t ON t.id = e.travelFk WHERE t.shipped BETWEEN vDateInv AND util.VN_CURDATE() AND t.warehouseOutFk = vWarehouse - AND NOT t.daysInForward + AND NOT t.isRaid AND t.isDelivered UNION ALL SELECT m.itemFk, -m.quantity diff --git a/db/routines/hedera/procedures/order_getTax.sql b/db/routines/hedera/procedures/order_getTax.sql index d24ffe7ef..371416c29 100644 --- a/db/routines/hedera/procedures/order_getTax.sql +++ b/db/routines/hedera/procedures/order_getTax.sql @@ -9,45 +9,54 @@ BEGIN * @param vOrder El identificador del pedido * @return tmp.orderTax Bases imponibles, IVA y recargo de equivalencia */ + -- No poner create or replace, ya que da problemas DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; CREATE TEMPORARY TABLE tmp.addressCompany (INDEX (addressFk, companyFk)) ENGINE = MEMORY SELECT DISTINCT o.address_id addressFk, o.company_id companyFk FROM tmp.`order` tmpOrder - JOIN hedera.`order` o ON o.id = tmpOrder.orderFk; + JOIN `order` o ON o.id = tmpOrder.orderFk; - CALL vn.addressTaxArea; + CALL vn.addressTaxArea(); -- Calcula el IVA y el recargo desglosado. - - DROP TEMPORARY TABLE IF EXISTS tmp.orderTax; - CREATE TEMPORARY TABLE tmp.orderTax - (INDEX (orderFk)) + CREATE OR REPLACE TEMPORARY TABLE tmp.orderTax + (PRIMARY KEY (orderFk, code, rate)) ENGINE = MEMORY - SELECT o.id orderFk, + WITH orders AS ( + SELECT tor.orderFk, + oro.amount * oro.price total, + s.countryFk, + ata.areaFk, + itc.taxClassFk + FROM hedera.orderRow oro + JOIN tmp.order tor ON tor.orderFk = oro.orderFk + JOIN hedera.`order` o ON o.id = tor.orderFk + JOIN vn.item i ON i.id = oro.itemFk + JOIN vn.`client` c ON c.id = o.customer_id + JOIN vn.supplier s ON s.id = o.company_id + JOIN tmp.addressTaxArea ata ON ata.addressFk = o.address_id + AND ata.companyFk = o.company_id + JOIN vn.itemTaxCountry itc ON itc.itemFk = i.id + AND itc.countryFk = s.countryFk + HAVING total + ) + SELECT o.orderFk, tc.code, - SUM(m.amount * m.price) taxableBase, + SUM(o.total) taxableBase, pgc.rate - FROM tmp.`order` tmpOrder - JOIN `order` o ON o.id = tmpOrder.orderFk - JOIN orderRow m ON m.orderFk = o.id - JOIN vn.item i ON i.id = m.itemFk - JOIN vn.`client` c ON c.id = o.customer_id - JOIN vn.supplier s ON s.id = o.company_id - JOIN tmp.addressTaxArea ata - ON ata.addressFk = o.address_id AND ata.companyFk = o.company_id - JOIN vn.itemTaxCountry itc - ON itc.itemFk = i.id AND itc.countryFk = s.countryFk - JOIN vn.bookingPlanner bp - ON bp.countryFk = s.countryFk - AND bp.taxAreaFk = ata.areaFk - AND bp.taxClassFk = itc.taxClassFk - JOIN vn.pgc ON pgc.`code` = bp.pgcFk + FROM orders o + JOIN vn.bookingPlanner bp ON bp.countryFk = o.countryFk + AND bp.taxAreaFk = o.areaFk + AND bp.taxClassFk = o.taxClassFk + JOIN vn.pgc ON pgc.code = bp.pgcFk JOIN vn.taxClass tc ON tc.id = bp.taxClassFk - GROUP BY tmpOrder.orderFk, pgc.`code`, pgc.rate - HAVING taxableBase != 0; + GROUP BY o.orderFk, pgc.code, pgc.rate + HAVING taxableBase + ORDER BY bp.priority; + -- No poner create or replace, ya que da problemas DROP TEMPORARY TABLE IF EXISTS tmp.orderAmount; CREATE TEMPORARY TABLE tmp.orderAmount (INDEX (orderFk)) diff --git a/db/routines/stock/procedures/log_refreshBuy.sql b/db/routines/stock/procedures/log_refreshBuy.sql index d8e727f17..874e14072 100644 --- a/db/routines/stock/procedures/log_refreshBuy.sql +++ b/db/routines/stock/procedures/log_refreshBuy.sql @@ -6,12 +6,11 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tValues; CREATE TEMPORARY TABLE tValues ENGINE = MEMORY - SELECT - b.id buyFk, + SELECT b.id buyFk, e.id entryFk, t.id travelFk, b.itemFk, - t.daysInForward, + t.isRaid, ADDTIME(t.shipped, IFNULL(t.shipmentHour, '00:00:00')) shipped, t.warehouseOutFk, @@ -50,7 +49,7 @@ BEGIN itemFk, TIMESTAMPADD(DAY, life, @dated), quantity, - IF(isIn, isReceived, isDelivered) AND NOT daysInForward + IF(isIn, isReceived, isDelivered) AND NOT isRaid FROM tValues WHERE isIn OR !lessThanInventory; @@ -65,7 +64,7 @@ BEGIN itemFk, created, quantity, - IF(isIn, isDelivered, isReceived) AND NOT daysInForward + IF(isIn, isDelivered, isReceived) AND NOT isRaid FROM tValues WHERE !isIn OR !lessThanInventory; diff --git a/db/routines/vn/functions/address_getGeo.sql b/db/routines/vn/functions/address_getGeo.sql index 04155c30c..213eb91c3 100644 --- a/db/routines/vn/functions/address_getGeo.sql +++ b/db/routines/vn/functions/address_getGeo.sql @@ -14,9 +14,12 @@ BEGIN SELECT p.geoFk INTO vGeoFk FROM address a JOIN town t ON t.provinceFk = a.provinceFk - JOIN postCode p ON p.townFk = t.id AND p.`code` = a.postalCode + JOIN postCode p ON p.townFk = t.id + AND (p.code = a.postalCode OR a.postalCode IS NULL) + JOIN zoneGeo zg ON zg.id = p.geoFk WHERE a.id = vSelf - ORDER BY (a.city SOUNDS LIKE t.`name`) DESC + ORDER BY (a.city SOUNDS LIKE t.name) DESC, + (p.code = a.postalCode) DESC LIMIT 1; RETURN vGeoFk; diff --git a/db/routines/vn/functions/client_getGeo.sql b/db/routines/vn/functions/client_getGeo.sql new file mode 100644 index 000000000..9c2e3212e --- /dev/null +++ b/db/routines/vn/functions/client_getGeo.sql @@ -0,0 +1,27 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`client_getGeo`(vSelf INT) + RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * Returns the geo for the passed client. + * + * @param vSelf The address id + * @return The geo id + */ + DECLARE vGeoFk INT; + + SELECT p.geoFk INTO vGeoFk + FROM client c + JOIN town t ON t.provinceFk = c.provinceFk + JOIN postCode p ON p.townFk = t.id + AND (p.code = c.postcode OR c.postcode IS NULL) + JOIN zoneGeo zg ON zg.id = p.geoFk + WHERE c.id = vSelf + ORDER BY (c.city SOUNDS LIKE t.name) DESC, + (p.code = c.postcode) DESC + LIMIT 1; + + RETURN vGeoFk; +END$$ +DELIMITER ; diff --git a/db/routines/vn/functions/entry_getCommission.sql b/db/routines/vn/functions/entry_getCommission.sql index 4a19f4e63..a4afdabd4 100644 --- a/db/routines/vn/functions/entry_getCommission.sql +++ b/db/routines/vn/functions/entry_getCommission.sql @@ -1,58 +1,51 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`entry_getCommission`(vTravelFk INT, - vCurrencyFk INT, - vSupplierFk INT + vCurrencyFk INT, + vSupplierFk INT ) RETURNS int(11) NOT DETERMINISTIC READS SQL DATA BEGIN - DECLARE vCommission INT; - DECLARE vCurrentCommission INT; - DECLARE vIsCurrencyUsd INT; - DECLARE vLastEntryFk INT; - - SELECT count(*) INTO vIsCurrencyUsd - FROM currency c - WHERE c.code = 'USD' AND id = vCurrencyFk; - - IF NOT vIsCurrencyUsd THEN - - SELECT e.id INTO vLastEntryFk - FROM vn.entry e - JOIN vn.travel tr ON tr.id = e.travelFk - WHERE e.supplierFk = vSupplierFk - ORDER BY tr.landed DESC - LIMIT 1; - - IF vLastEntryFk THEN - - SELECT commission INTO vCurrentCommission - FROM vn.entry - WHERE id = vLastEntryFk; - - ELSE - - SELECT commission INTO vCurrentCommission - FROM supplier s - WHERE s.id = vSupplierFk; - - END IF; - - RETURN vCurrentCommission; - - ELSE + DECLARE vCommission INT; + DECLARE vCurrentCommission INT; + DECLARE vIsNotEUR INT; + DECLARE vLastEntryFk INT; + SELECT count(*) INTO vIsNotEUR + FROM currency c + WHERE c.code <> 'EUR' AND id = vCurrencyFk; + + IF vIsNotEUR THEN SELECT ROUND(-100 * (1 - (1 / r.value))) INTO vCommission FROM travel t LEFT JOIN referenceCurrent r ON r.currencyFk = vCurrencyFk AND r.`dated` <= t.shipped WHERE t.id = vTravelFk ORDER BY r.`dated` DESC LIMIT 1; - + RETURN IFNULL(vCommission, 0); - - END IF; - + ELSE + SELECT e.id INTO vLastEntryFk + FROM `entry` e + JOIN travel tr ON tr.id = e.travelFk + WHERE e.supplierFk = vSupplierFk + ORDER BY tr.landed DESC + LIMIT 1; + + IF vLastEntryFk THEN + SELECT commission INTO vCurrentCommission + FROM `entry` + WHERE id = vLastEntryFk; + + ELSE + SELECT commission INTO vCurrentCommission + FROM supplier s + WHERE s.id = vSupplierFk; + + END IF; + + RETURN vCurrentCommission; + END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/functions/hasItemsInSector.sql b/db/routines/vn/functions/hasItemsInSector.sql index 7a5c4cf60..faf9e8a90 100644 --- a/db/routines/vn/functions/hasItemsInSector.sql +++ b/db/routines/vn/functions/hasItemsInSector.sql @@ -9,7 +9,7 @@ BEGIN SELECT count(*) INTO vItemCount FROM vn.sale s JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk - JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.shelving sh ON sh.id = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk WHERE s.ticketFk = vTicketFk AND p.sectorFk = vSectorFk; diff --git a/db/routines/vn/functions/itemsInSector_get.sql b/db/routines/vn/functions/itemsInSector_get.sql index 254ebe1b5..9043e55cb 100644 --- a/db/routines/vn/functions/itemsInSector_get.sql +++ b/db/routines/vn/functions/itemsInSector_get.sql @@ -10,7 +10,7 @@ BEGIN SELECT count(*) INTO vItemCount FROM vn.sale s JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk - JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.shelving sh ON sh.id = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk WHERE s.ticketFk = vTicketFk AND p.sectorFk = vSectorFk; diff --git a/db/routines/vn/functions/supplier_getGeo.sql b/db/routines/vn/functions/supplier_getGeo.sql new file mode 100644 index 000000000..86984272c --- /dev/null +++ b/db/routines/vn/functions/supplier_getGeo.sql @@ -0,0 +1,29 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`supplier_getGeo`(vSelf INT) + RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * Returns the geo for the passed supplier. + * + * @param vSelf The address id + * @return The geo id + */ + DECLARE vGeoFk INT; + + SELECT p.geoFk INTO vGeoFk + FROM supplier s + JOIN town t ON t.provinceFk = s.provinceFk + JOIN postCode p ON p.townFk = t.id + AND (p.code = s.postCode OR s.postCode IS NULL) + LEFT JOIN supplierAddress sad ON sad.supplierFk = s.id + JOIN zoneGeo zg ON zg.id = p.geoFk + WHERE s.id = vSelf + ORDER BY (s.city SOUNDS LIKE t.name) DESC, + (p.code = s.postCode) DESC, + (p.code = sad.postalCode) DESC + LIMIT 1; + + RETURN vGeoFk; +END$$ +DELIMITER ; diff --git a/db/routines/vn/functions/timeWorkerControl_getDirection.sql b/db/routines/vn/functions/timeWorkerControl_getDirection.sql deleted file mode 100644 index c0f1e67ea..000000000 --- a/db/routines/vn/functions/timeWorkerControl_getDirection.sql +++ /dev/null @@ -1,65 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`timeWorkerControl_getDirection`(vUserFk INT, vTimed DATETIME) - RETURNS varchar(6) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci - NOT DETERMINISTIC - READS SQL DATA -BEGIN -/** - * Verifica la dirección de la fichada - * @param vUserFk Identificador del trabajador - * @param vTimed Hora de la fichada - * @return Retorna sentido de la fichada 'in, out, middle' - */ - - DECLARE vPrevious DATETIME ; - DECLARE vNext DATETIME ; - DECLARE vPreviousDirection VARCHAR(3) ; - DECLARE vNextDirection VARCHAR(3) ; - DECLARE vDayStayMax INT; - DECLARE vTimedSeconds INT; - DECLARE vLastTimeIn INT; - - SELECT UNIX_TIMESTAMP(vTimed) INTO vTimedSeconds; - - SELECT dayStayMax INTO vDayStayMax - FROM vn.workerTimeControlParams; - - SELECT timed, direction INTO vNext,vNextDirection - FROM vn.workerTimeControl - WHERE userFk = vUserFk - AND direction IN ('in','out') - AND timed > vTimed - ORDER BY timed ASC - LIMIT 1; - - SELECT timed, direction INTO vPrevious, vPreviousDirection - FROM vn.workerTimeControl - WHERE userFk = vUserFk - AND direction IN ('in','out') - AND timed < vTimed - ORDER BY timed DESC - LIMIT 1; - - IF (vTimedSeconds - UNIX_TIMESTAMP(vPrevious) + UNIX_TIMESTAMP(vNext) - vTimedSeconds)<= vDayStayMax AND vPreviousDirection = 'in' AND vNextDirection = 'out' THEN - RETURN 'middle'; - END IF; - - - IF (vTimedSeconds> UNIX_TIMESTAMP(vPrevious)) THEN - IF vPreviousDirection = 'in' THEN - RETURN 'out'; - ELSE - SELECT UNIX_TIMESTAMP(MAX(timed)) INTO vLastTimeIn - FROM vn.workerTimeControl - WHERE userFk = vUserFk - AND direction ='in' - AND timed < vPrevious; - IF vTimedSeconds - vLastTimeIn <= vDayStayMax THEN - RETURN 'out'; - END IF; - END IF; - END IF; - - RETURN 'in'; -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/absoluteInventoryHistory.sql b/db/routines/vn/procedures/absoluteInventoryHistory.sql index 3ea8cf4de..d0d9ffac2 100644 --- a/db/routines/vn/procedures/absoluteInventoryHistory.sql +++ b/db/routines/vn/procedures/absoluteInventoryHistory.sql @@ -39,7 +39,7 @@ BEGIN AND vWarehouseFk IN (tr.warehouseInFk, 0) AND b.itemFk = vItemFk AND NOT e.isExcludedFromAvailable - AND NOT tr.daysInForward + AND NOT tr.isRaid UNION ALL SELECT tr.shipped, NULL, @@ -58,7 +58,7 @@ BEGIN AND s.id <> (SELECT supplierFk FROM inventoryConfig) AND b.itemFk = vItemFk AND NOT e.isExcludedFromAvailable - AND NOT tr.daysInForward + AND NOT tr.isRaid UNION ALL SELECT t.shipped, NULL, diff --git a/db/routines/vn/procedures/available_traslate.sql b/db/routines/vn/procedures/available_traslate.sql index 513f58e36..bfd5b34c8 100644 --- a/db/routines/vn/procedures/available_traslate.sql +++ b/db/routines/vn/procedures/available_traslate.sql @@ -42,7 +42,7 @@ proc: BEGIN WHERE t.landed BETWEEN vDatedInventory AND vDatedFrom AND t.warehouseInFk = vWarehouseLanding AND NOT e.isExcludedFromAvailable - AND NOT t.daysInForward + AND NOT t.isRaid GROUP BY c.itemFk; -- Tabla con el ultimo dia de last_buy para cada producto @@ -57,7 +57,7 @@ proc: BEGIN JOIN travel tr ON tr.id = e.travelFk LEFT JOIN tItemRange i ON t.itemFk = i.itemFk WHERE t.warehouseFk = vWarehouseShipment - AND NOT tr.daysInForward + AND NOT tr.isRaid ON DUPLICATE KEY UPDATE tItemRange.dated = GREATEST(tItemRange.dated, tr.landed); @@ -94,7 +94,7 @@ proc: BEGIN JOIN tItemRangeLive ir ON ir.itemFk = b.itemFk WHERE NOT e.isExcludedFromAvailable AND b.quantity <> 0 - AND NOT t.daysInForward + AND NOT t.isRaid AND t.warehouseInFk = vWarehouseLanding AND t.landed >= vDatedFrom AND (ir.dated IS NULL OR t.landed <= ir.dated) diff --git a/db/routines/vn/procedures/collectionPlacement_get.sql b/db/routines/vn/procedures/collectionPlacement_get.sql index 239dbd3a2..8d2301e1e 100644 --- a/db/routines/vn/procedures/collectionPlacement_get.sql +++ b/db/routines/vn/procedures/collectionPlacement_get.sql @@ -83,7 +83,7 @@ BEGIN AND s.semaphore = 1 GROUP BY st.saleFk) st ON st.saleFk = ts.saleFk JOIN itemShelving ish ON ish.itemFk = ts.itemFk - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk JOIN sector sc ON sc.id = p.sectorFk JOIN sectorType st ON st.id = sc.typeFk diff --git a/db/routines/vn/procedures/entry_getTransfer.sql b/db/routines/vn/procedures/entry_getTransfer.sql index 9527e0bf2..873827db2 100644 --- a/db/routines/vn/procedures/entry_getTransfer.sql +++ b/db/routines/vn/procedures/entry_getTransfer.sql @@ -166,7 +166,7 @@ BEGIN LEFT JOIN tmp.buyUltimateFromInterval bufi ON bufi.itemFk = i.id LEFT JOIN buy b3 ON b3.id = bufi.buyFk WHERE ic.display - AND NOT tr.daysInForward + AND NOT tr.isRaid AND (ti.visible OR ti.available) ORDER BY i.typeFk, i.name, i.id, i.size, i.category, o.name; diff --git a/db/routines/vn/procedures/entry_isEditable.sql b/db/routines/vn/procedures/entry_isEditable.sql index 12b6d0ef6..c417f6789 100644 --- a/db/routines/vn/procedures/entry_isEditable.sql +++ b/db/routines/vn/procedures/entry_isEditable.sql @@ -9,16 +9,18 @@ BEGIN * * @param vSelf Id de entrada */ - DECLARE vIsEditable BOOL; + DECLARE vIsNotEditable BOOL DEFAULT FALSE; - SELECT e.isBooked INTO vIsEditable + SELECT TRUE INTO vIsNotEditable FROM `entry` e - JOIN entryType et ON et.code = e.typeFk - WHERE NOT et.isInformal - AND e.id = vSelf; + LEFT JOIN entryType et ON et.code = e.typeFk + WHERE e.id = vSelf + AND e.isBooked + AND (e.typeFk IS NULL OR NOT et.isInformal); - IF vIsEditable AND NOT IFNULL(@isModeInventory, FALSE) THEN + IF vIsNotEditable AND NOT IFNULL(@isModeInventory, FALSE) THEN CALL util.throw(CONCAT('Entry ', vSelf, ' is not editable')); END IF; + END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/entry_splitByShelving.sql b/db/routines/vn/procedures/entry_splitByShelving.sql index fbf0cef90..3201900e6 100644 --- a/db/routines/vn/procedures/entry_splitByShelving.sql +++ b/db/routines/vn/procedures/entry_splitByShelving.sql @@ -1,10 +1,15 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`entry_splitByShelving`(vShelvingFk VARCHAR(3), vFromEntryFk INT, vToEntryFk INT) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`entry_splitByShelving`( + vShelvingCode VARCHAR(10), + vFromEntryFk INT, + vToEntryFk INT +) BEGIN /** - * Divide las compras entre dos entradas de acuerdo con lo ubicado en una matr�cula + * Divide las compras entre dos entradas de + * acuerdo con lo ubicado en una matricula. * - * @param vShelvingFk Identificador de vn.shelving + * @param vShelvingCode Código de vn.shelving * @param vFromEntryFk Entrada origen * @param vToEntryFk Entrada destino */ @@ -14,7 +19,7 @@ BEGIN DECLARE vDone BOOLEAN DEFAULT FALSE; DECLARE cur CURSOR FOR - SELECT bb.id buyFk, + SELECT bb.id buyFk, LEAST(bb.stickers, FLOOR(ish.visible / ish.packing)) ishStickers, bb.stickers buyStickers FROM itemShelving ish @@ -23,7 +28,7 @@ BEGIN WHERE b.entryFk = vFromEntryFk ORDER BY b.stickers DESC LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk - WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci + WHERE ish.shelvingFk = vShelvingCode COLLATE utf8_general_ci AND NOT ish.isSplit GROUP BY ish.id; @@ -107,9 +112,10 @@ BEGIN UPDATE buy SET printedStickers = vIshStickers WHERE id = LAST_INSERT_ID(); END IF; - UPDATE itemShelving - SET isSplit = TRUE - WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci; + UPDATE itemShelving ish + JOIN shelving sh ON sh.id = ish.shelvingFk + SET ish.isSplit = TRUE + WHERE sh.code = vShelvingCode COLLATE utf8_general_ci; END LOOP; CLOSE cur; END$$ diff --git a/db/routines/vn/procedures/entry_updateComission.sql b/db/routines/vn/procedures/entry_updateComission.sql index e2de2a4a5..8db28f97d 100644 --- a/db/routines/vn/procedures/entry_updateComission.sql +++ b/db/routines/vn/procedures/entry_updateComission.sql @@ -22,7 +22,7 @@ BEGIN FROM vn.entry e JOIN vn.travel t ON t.id = e.travelFk JOIN vn.warehouse w ON w.id = t.warehouseInFk - WHERE t.shipped >= util.VN_CURDATE() + WHERE t.landed >= util.VN_CURDATE() AND e.currencyFk = vCurrency AND NOT e.isBooked; @@ -33,7 +33,7 @@ BEGIN SET e.commission = vComission; SELECT `name` INTO vCurrencyName - FROM currency + FROM currency WHERE id = vCurrency; CALL entry_recalc(); diff --git a/db/routines/vn/procedures/inventoryMake.sql b/db/routines/vn/procedures/inventoryMake.sql index 65dceef3d..316083db0 100644 --- a/db/routines/vn/procedures/inventoryMake.sql +++ b/db/routines/vn/procedures/inventoryMake.sql @@ -137,7 +137,7 @@ BEGIN JOIN travel tr ON tr.id = e.travelFk WHERE tr.warehouseInFk = vWarehouseFk AND tr.landed BETWEEN vDateLastInventory AND vDateYesterday - AND NOT tr.daysInForward + AND NOT tr.isRaid GROUP BY b.itemFk; -- Transfers @@ -150,7 +150,7 @@ BEGIN JOIN travel tr ON tr.id = e.travelFk WHERE tr.warehouseOutFk = vWarehouseFk AND tr.shipped BETWEEN vDateLastInventory AND vDateYesterday - AND NOT tr.daysInForward + AND NOT tr.isRaid GROUP BY b.itemFk ) sub ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity, 0) + sub.quantityOut; diff --git a/db/routines/vn/procedures/itemPlacementSupplyAiming.sql b/db/routines/vn/procedures/itemPlacementSupplyAiming.sql index b96860623..ae0890564 100644 --- a/db/routines/vn/procedures/itemPlacementSupplyAiming.sql +++ b/db/routines/vn/procedures/itemPlacementSupplyAiming.sql @@ -1,5 +1,9 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyAiming`(vShelvingFk VARCHAR(10), quantity INT, vItemFk INT) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyAiming`( + vShelvingCode VARCHAR(10), + vQuantity INT, + vItemFk INT +) BEGIN SELECT ish.itemFk, @@ -9,21 +13,21 @@ BEGIN ish.itemShelvingFk, ish.shelving, ish.stock, - LEAST(ish.stock,quantity) as total, + LEAST(ish.stock,vQuantity) total, CONCAT( - CAST(FLOOR(LEAST(ish.stock,quantity) / ish.packing) AS DECIMAL(10,0)), + CAST(FLOOR(LEAST(ish.stock, vQuantity) / ish.packing) AS DECIMAL(10,0)), ' x ', ish.packing, IF ( - LEAST(ish.stock,quantity) MOD ish.packing, - CONCAT(' + ',CAST(LEAST(ish.stock,quantity) MOD ish.packing AS DECIMAL(10,0))), + LEAST(ish.stock, vQuantity) MOD ish.packing, + CONCAT(' + ',CAST(LEAST(ish.stock, vQuantity) MOD ish.packing AS DECIMAL(10,0))), '' ), ' = ', - LEAST(ish.stock,quantity) - ) as proposal - FROM vn.itemShelvingPlacementSupplyStock ish - WHERE ish.shelving = vShelvingFk COLLATE utf8_general_ci + LEAST(ish.stock, vQuantity) + ) proposal + FROM itemShelvingPlacementSupplyStock ish + WHERE ish.shelving = vShelvingCode COLLATE utf8_general_ci AND ish.itemFk = vItemFk; END$$ diff --git a/db/routines/vn/procedures/itemPlacementSupplyGetOrder.sql b/db/routines/vn/procedures/itemPlacementSupplyGetOrder.sql index 958dc7e78..d2648ca6c 100644 --- a/db/routines/vn/procedures/itemPlacementSupplyGetOrder.sql +++ b/db/routines/vn/procedures/itemPlacementSupplyGetOrder.sql @@ -1,5 +1,7 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyGetOrder`(vSector INT ) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyGetOrder`( + vSectorFk INT +) BEGIN DECLARE vId INT; @@ -7,31 +9,35 @@ BEGIN DECLARE vNextParkingFk INT; SELECT sh.parkingFk INTO vLastParkingFk - FROM vn.itemShelvingPlacementSupply isps - JOIN vn.itemShelving ish ON ish.id = isps.itemShelvingFk - JOIN vn.shelving sh ON sh.code = ish.shelvingFk + FROM itemShelvingPlacementSupply isps + JOIN itemShelving ish ON ish.id = isps.itemShelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk WHERE isps.userFk = getUser() ORDER BY isps.created DESC LIMIT 1; - SET vNextParkingFk = vn.itemShelvingPlacementSupply_ClosestGet(vLastParkingFk); + SET vNextParkingFk = itemShelvingPlacementSupply_ClosestGet(vLastParkingFk); SELECT ipsl.id INTO vId - FROM vn.itemPlacementSupplyList ipsl - JOIN vn.itemShelvingPlacementSupplyStock ispss ON ispss.itemFk = ipsl.itemFk + FROM itemPlacementSupplyList ipsl + JOIN itemShelvingPlacementSupplyStock ispss ON ispss.itemFk = ipsl.itemFk WHERE ipsl.saldo > 0 AND (ipsl.repoUserFk is NULL OR ipsl.repoUserFk = getUser()) - AND ipsl.sectorFk = vSector - ORDER BY ipsl.repoUserFk DESC, ipsl.priority DESC, (ispss.parkingFk = vNextParkingFk) DESC, ispss.parking DESC, ipsl.created + AND ipsl.sectorFk = vSectorFk + ORDER BY ipsl.repoUserFk DESC, + ipsl.priority DESC, + (ispss.parkingFk = vNextParkingFk) DESC, + ispss.parking DESC, + ipsl.created LIMIT 1; - UPDATE vn.itemPlacementSupply + UPDATE itemPlacementSupply SET repoUserFk = getUser() WHERE id = vId; - SELECT * FROM vn.itemPlacementSupplyList + SELECT * FROM itemPlacementSupplyList WHERE id = vId - AND sectorFk = vSector; + AND sectorFk = vSectorFk; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql b/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql index cefa64d13..92c17b82f 100644 --- a/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql +++ b/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql @@ -1,5 +1,8 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyStockGetTargetList`(vItemFk INT,vSectorFk INT) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyStockGetTargetList`( + vItemFk INT, + vSectorFk INT +) BEGIN /** * Devuelve la lista de ubicaciones para itemFk en ese sector. Se utiliza en la preparación previa. @@ -13,11 +16,11 @@ BEGIN SUM(ish.visible) stockTotal, ish.created, p.pickingOrder - FROM vn.itemShelving ish - JOIN vn.shelving sh ON sh.code = ish.shelvingFk - JOIN vn.parking p ON p.id = sh.parkingFk - JOIN vn.sector sc ON sc.id = p.sectorFk - JOIN vn.warehouse w ON w.id = sc.warehouseFk + FROM itemShelving ish + JOIN shelving sh ON sh.id = ish.shelvingFk + JOIN parking p ON p.id = sh.parkingFk + JOIN sector sc ON sc.id = p.sectorFk + JOIN warehouse w ON w.id = sc.warehouseFk WHERE ish.visible > 0 AND ish.itemFk = vItemFk GROUP BY ish.id diff --git a/db/routines/vn/procedures/itemShelvingLog_get.sql b/db/routines/vn/procedures/itemShelvingLog_get.sql index 52e7a273f..5a943e867 100644 --- a/db/routines/vn/procedures/itemShelvingLog_get.sql +++ b/db/routines/vn/procedures/itemShelvingLog_get.sql @@ -1,14 +1,14 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelvingLog_get`(vShelvingFk VARCHAR(10) ) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelvingLog_get`( + vShelvingCode VARCHAR(10) +) BEGIN - /** * Devuelve el log de los item en cada carro * - * @param vShelvingFk Matrícula del carro + * @param vShelvingCode Matrícula del carro * */ - SELECT isl.itemShelvingFk, isl.created, isl.accion, @@ -28,8 +28,9 @@ BEGIN FROM item JOIN itemShelvingLog isl ON item.id = isl.itemFk JOIN worker ON isl.workerFk = worker.id - WHERE shelvingFk = vShelvingFk OR isl.itemFk = vShelvingFk - ORDER BY isl.created DESC; - + JOIN shelving sh ON sh.id = isl.shelvingFk + WHERE sh.code = vShelvingCode COLLATE utf8mb3_unicode_ci + OR isl.itemFk = vShelvingCode -- ?? Respeto porque ya estaba + ORDER BY isl.created DESC; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/itemShelvingMatch.sql b/db/routines/vn/procedures/itemShelvingMatch.sql index 850c7907b..4ffa66fcb 100644 --- a/db/routines/vn/procedures/itemShelvingMatch.sql +++ b/db/routines/vn/procedures/itemShelvingMatch.sql @@ -20,7 +20,7 @@ BEGIN LEFT JOIN ( SELECT itemFk, sum(cast(visible / packing AS DECIMAL(10,0))) AS etiquetas FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk LEFT JOIN parking pk ON pk.id = sh.parkingFk WHERE ish.created BETWEEN vFromTimed AND vToTimed GROUP BY itemFk diff --git a/db/routines/vn/procedures/itemShelvingSale_addBySale.sql b/db/routines/vn/procedures/itemShelvingSale_addBySale.sql index 06736732a..eeec60248 100644 --- a/db/routines/vn/procedures/itemShelvingSale_addBySale.sql +++ b/db/routines/vn/procedures/itemShelvingSale_addBySale.sql @@ -27,7 +27,7 @@ proc: BEGIN ish.available FROM sale s JOIN itemShelving ish ON ish.itemFk = s.itemFk - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk JOIN sector sc ON sc.id = p.sectorFk JOIN productionConfig pc @@ -61,7 +61,7 @@ proc: BEGIN FROM sale s LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk - LEFT JOIN shelving sh ON sh.code = ish.shelvingFk + LEFT JOIN shelving sh ON sh.id = ish.shelvingFk LEFT JOIN parking p ON p.id = sh.parkingFk WHERE s.id = vSaleFk; diff --git a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql index cde1b6872..1975180d1 100644 --- a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql +++ b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql @@ -3,7 +3,8 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelvingSale_setQ vItemShelvingSaleFk INT(10), vQuantity DECIMAL(10,0), vIsItemShelvingSaleEmpty BOOLEAN, - vSectorFk INT + vSectorFk INT, + vShelvingFk VARCHAR(10) ) BEGIN /** @@ -24,6 +25,7 @@ BEGIN DECLARE vItemFk INT; DECLARE vTotalQuantity INT; DECLARE vStateCode VARCHAR(45); + DECLARE vCurrentShelvingFk VARCHAR(10); DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN @@ -45,18 +47,26 @@ BEGIN iss.saleFk, iss.itemShelvingFk, SUM(IFNULL(iss.quantity,0)), - IF(sgd.id, 'PREVIOUS_PREPARATION', 'PREPARED') + IF(sgd.id, 'PREVIOUS_PREPARATION', 'PREPARED'), + sh.code INTO vItemFk, vSaleFk, vItemShelvingFk, vReservedQuantity, - vStateCode + vStateCode, + vCurrentShelvingFk FROM itemShelvingSale iss JOIN sale s ON s.id = iss.saleFk - LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleFk = iss.saleFk + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = iss.saleFk + LEFT JOIN shelving sh ON sh.id = ish.shelvingFk WHERE iss.id = vItemShelvingSaleFk AND NOT iss.isPicked; + IF NOT (vCurrentShelvingFk <=> vShelvingFk) THEN + CALL util.throw('The shelving can not be different from the shelving reserved'); + END IF; + IF vQuantity > vReservedQuantity OR (vQuantity < vReservedQuantity AND NOT vIsItemShelvingSaleEmpty) OR (vQuantity = vReservedQuantity AND vIsItemShelvingSaleEmpty) THEN diff --git a/db/routines/vn/procedures/itemShelving_add.sql b/db/routines/vn/procedures/itemShelving_add.sql index 92d1609e4..a8f0b5250 100644 --- a/db/routines/vn/procedures/itemShelving_add.sql +++ b/db/routines/vn/procedures/itemShelving_add.sql @@ -1,6 +1,6 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_add`( - vShelvingFk VARCHAR(8), + vShelvingCode VARCHAR(10), vBarcode VARCHAR(22), vQuantity INT, vPackagingFk VARCHAR(10), @@ -12,7 +12,7 @@ BEGIN /** * Añade registro o lo actualiza si ya existe. * - * @param vShelvingFk matrícula del carro + * @param vShelvingCode matrícula del carro * @param vBarcode el id del registro * @param vQuantity indica la cantidad del producto * @param vPackagingFk el packaging del producto en itemShelving, NULL para coger el de la ultima compra @@ -23,10 +23,15 @@ BEGIN **/ DECLARE vItemFk INT; DECLARE vBuyFk INT; + DECLARE vShelvingFk INT; SELECT id INTO vBuyFk FROM buy WHERE id = vBarcode; + SELECT id INTO vShelvingFk + FROM shelving + WHERE code COLLATE utf8_unicode_ci = vShelvingCode; + SELECT barcodeToItem(vBarcode) INTO vItemFk; IF vBuyFk IS NULL THEN @@ -40,7 +45,7 @@ BEGIN END IF; IF (SELECT COUNT(*) FROM itemShelving - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + WHERE shelvingFk = vShelvingFk AND itemFk = vItemFk AND packing = vPacking AND buyFk = vBuyFk) THEN @@ -48,7 +53,9 @@ BEGIN UPDATE itemShelving SET visible = visible + vQuantity, available = available + vQuantity - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; + WHERE shelvingFk = vShelvingFk + AND itemFk = vItemFk + AND packing = vPacking; ELSE diff --git a/db/routines/vn/procedures/itemShelving_addByClaim.sql b/db/routines/vn/procedures/itemShelving_addByClaim.sql index 5e7cdf3fc..55ac3e337 100644 --- a/db/routines/vn/procedures/itemShelving_addByClaim.sql +++ b/db/routines/vn/procedures/itemShelving_addByClaim.sql @@ -1,29 +1,38 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_addByClaim`(vClaimFk INT, vShelvingFk VARCHAR(3)) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_addByClaim`( + vClaimFk INT, + vShelvingCode VARCHAR(10) +) BEGIN /** * Insert items of claim into itemShelving. * * @param vClaimFk The claim - * @param vShelvingFk The shelving + * @param vShelvingCode The shelving code * @table tmp.buyUltimate */ DECLARE vWarehouseFk INT; + DECLARE vShelvingFk INT; SELECT t.warehouseFk INTO vWarehouseFk FROM claim c JOIN ticket t ON t.id = c.ticketFk WHERE c.id = vClaimFk; + SELECT id INTO vShelvingFk + FROM shelving + WHERE code COLLATE utf8_unicode_ci = vShelvingCode; + CALL buy_getUltimate(NULL, vWarehouseFk, util.VN_CURDATE()); INSERT INTO itemShelving (itemFk, shelvingFk, packing, `grouping`, visible) - SELECT s.itemFk, vShelvingFk, b.packing, b.`grouping`, cb.quantity AS visible + SELECT s.itemFk, vShelvingFk, b.packing, b.`grouping`, cb.quantity visible FROM claim c JOIN claimBeginning cb ON c.id = cb.claimFk JOIN sale s ON s.id = cb.saleFk JOIN ticket t ON t.id = s.ticketFk - JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk AND bu.warehouseFk = t.warehouseFk + JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + AND bu.warehouseFk = t.warehouseFk JOIN buy b ON b.id = bu.buyFk WHERE c.id = vClaimFk; END$$ diff --git a/db/routines/vn/procedures/itemShelving_addList.sql b/db/routines/vn/procedures/itemShelving_addList.sql index ade92b9fd..04fa1e10c 100644 --- a/db/routines/vn/procedures/itemShelving_addList.sql +++ b/db/routines/vn/procedures/itemShelving_addList.sql @@ -1,6 +1,6 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_addList`( - vShelvingFk VARCHAR(3), + vShelvingCode VARCHAR(10), vList TEXT, vIsChecking BOOL, vWarehouseFk INT @@ -13,7 +13,7 @@ BEGIN * Cuando es TRUE sólo inserta los elementos de la colección que no están ya en * ese shelving, actualizando los valores del campo itemShelving.isChecked * - * @param vShelvingFk Identificador de shelving + * @param vShelvingCode Código de shelving * @param vList JSON array con esta estructura: '[value1, value2, ...]' * @param vIsChecking Define si hay que añadir o comprobar los items * @param vWarehouseFk Identificador de warehouse @@ -24,6 +24,11 @@ BEGIN DECLARE vPath VARCHAR(6); DECLARE vItemFk INT; DECLARE vIsChecked BOOL; + DECLARE vShelvingFk INT; + + SELECT id INTO vShelvingFk + FROM shelving + WHERE code COLLATE utf8_unicode_ci = vShelvingCode; WHILE vCounter < vListLength DO SET vPath = CONCAT('$[', vCounter, ']'); @@ -34,17 +39,17 @@ BEGIN SELECT IF(COUNT(*), TRUE, FALSE) INTO vIsChecked FROM itemShelving - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + WHERE shelvingFk = vShelvingFk AND itemFk = vItemFk; END IF; IF NOT vIsChecking OR NOT vIsChecked THEN - CALL itemShelving_add(vShelvingFk, vBarcode, 1, NULL, NULL, NULL, vWarehouseFk); + CALL itemShelving_add(vShelvingCode, vBarcode, 1, NULL, NULL, NULL, vWarehouseFk); END IF; UPDATE itemShelving SET isChecked = vIsChecked - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + WHERE shelvingFk = vShelvingFk AND itemFk = vItemFk AND isChecked IS NULL; diff --git a/db/routines/vn/procedures/itemShelving_get.sql b/db/routines/vn/procedures/itemShelving_get.sql index 07384b721..0038257c2 100644 --- a/db/routines/vn/procedures/itemShelving_get.sql +++ b/db/routines/vn/procedures/itemShelving_get.sql @@ -1,10 +1,12 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_get`(IN vSelf VARCHAR(8)) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_get`( + vShelvingCode VARCHAR(10) +) BEGIN /** -* Lista artículos de itemshelving +* Lista artículos de itemShelving. * -* @param vSelf matrícula del carro +* @param vShelvingCode Matrícula del carro **/ SELECT ish.itemFk item, i.name, @@ -19,12 +21,13 @@ BEGIN ish.isChecked, ic.url, ish.available, - ish.buyFk + ish.buyFk, + ish.shelvingFk FROM itemShelving ish JOIN item i ON i.id = ish.itemFk - JOIN shelving s ON vSelf = s.code COLLATE utf8_unicode_ci - LEFT JOIN parking p ON s.parkingFk = p.id + JOIN shelving s ON s.id = ish.shelvingFk + LEFT JOIN parking p ON p.id = s.parkingFk JOIN hedera.imageConfig ic - WHERE ish.shelvingFk COLLATE utf8_unicode_ci = vSelf; + WHERE s.code COLLATE utf8_unicode_ci = vShelvingCode; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/itemShelving_getAlternatives.sql b/db/routines/vn/procedures/itemShelving_getAlternatives.sql index 89176c4f5..3eff3254b 100644 --- a/db/routines/vn/procedures/itemShelving_getAlternatives.sql +++ b/db/routines/vn/procedures/itemShelving_getAlternatives.sql @@ -1,21 +1,31 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_getAlternatives`(vShelvingFk VARCHAR(10)) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_getAlternatives`( + vShelvingCode VARCHAR(10) +) BEGIN /** - * Devuelve un listado de posibles ubicaciones alternativas a ubicar los item de la matricula - * del carro que se le ha pasado. + * Devuelve un listado de posibles ubicaciones alternativas a ubicar + * los item de la matricula del carro que se le ha pasado. * - * @param vShelvingFk matricula del carro + * @param vShelvingCode Matricula del carro */ - SELECT is2.id,is2.shelvingFk , p.code, is2.itemFk , is2.visible, p.pickingOrder + DECLARE vShelvingFk INT; + + SELECT id INTO vShelvingFk + FROM shelving + WHERE code COLLATE utf8_unicode_ci = vShelvingCode; + + SELECT is2.id,is2.shelvingFk, p.code, is2.itemFk , is2.visible, p.pickingOrder FROM itemShelving is2 - JOIN shelving sh ON sh.code = is2.shelvingFk + JOIN shelving sh ON sh.id = is2.shelvingFk JOIN parking p ON p.id = sh.parkingFk JOIN sector s ON s.id = p.sectorFk - LEFT JOIN operator o ON o.sectorFk = s.id AND o.workerFk = account.myUser_getId() + LEFT JOIN operator o ON o.sectorFk = s.id + AND o.workerFk = account.myUser_getId() JOIN warehouse wh ON wh.id = s.warehouseFk - JOIN itemShelving is3 ON is3.itemFk = is2.itemFk AND is3.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci - WHERE is2.shelvingFk <> vShelvingFk COLLATE utf8_unicode_ci + JOIN itemShelving is3 ON is3.itemFk = is2.itemFk + AND is3.shelvingFk = vShelvingFk + WHERE is2.shelvingFk <> vShelvingFk GROUP BY is2.id ORDER BY p.pickingOrder DESC; END$$ diff --git a/db/routines/vn/procedures/itemShelving_getInfo.sql b/db/routines/vn/procedures/itemShelving_getInfo.sql index f02100e8b..f4c8c5b35 100644 --- a/db/routines/vn/procedures/itemShelving_getInfo.sql +++ b/db/routines/vn/procedures/itemShelving_getInfo.sql @@ -16,7 +16,7 @@ BEGIN ish.itemFk itemFk, sh.priority FROM vn.itemShelving ish - JOIN vn.shelving sh ON sh.`code` = ish.shelvingFk + JOIN vn.shelving sh ON sh.id = ish.shelvingFk JOIN vn.parking pk ON pk.id = sh.parkingFk WHERE ish.itemFk = vItemFk ORDER BY sh.priority DESC, created ASC; diff --git a/db/routines/vn/procedures/itemShelving_getItemDetails.sql b/db/routines/vn/procedures/itemShelving_getItemDetails.sql index 4e641ca72..36f9830f0 100644 --- a/db/routines/vn/procedures/itemShelving_getItemDetails.sql +++ b/db/routines/vn/procedures/itemShelving_getItemDetails.sql @@ -1,14 +1,14 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_getItemDetails`( vBarcodeItem INT, - vShelvingFK VARCHAR(10) + vShelvingCode VARCHAR(10) ) BEGIN /** * Obtiene el precio y visible de un item * * @param vBarcodeItem barcode de artículo - * @param vShelvingFK Ubicación actual del artículo + * @param vShelvingCode Ubicación actual del artículo */ DECLARE vIsItem BOOL; DECLARE vBuyFk INT; @@ -38,18 +38,19 @@ BEGIN WITH visible AS( SELECT itemFk, IFNULL(buyingValue, 0) + - IFNULL(freightValue, 0) + - IFNULL(comissionValue, 0) + - IFNULL(packageValue, 0) itemCost - FROM vn.buy b + IFNULL(freightValue, 0) + + IFNULL(comissionValue, 0) + + IFNULL(packageValue, 0) itemCost + FROM vn.buy b WHERE b.id = vBuyFk ) SELECT v.itemFk, - vShelvingFK, + vShelvingCode, v.itemCost, SUM(ish.visible) visible FROM vn.itemShelving ish + JOIN vn.shelving sh ON sh.id = ish.shelvingFK JOIN visible v - WHERE ish.shelvingFK = vShelvingFK COLLATE utf8mb3_general_ci - AND ish.itemFk = v.itemFk; + WHERE sh.code = vShelvingCode COLLATE utf8mb3_general_ci + AND ish.itemFk = v.itemFk; END$$ DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelving_getSaleDate.sql b/db/routines/vn/procedures/itemShelving_getSaleDate.sql index d8ab6ed0c..fad4d5abc 100644 --- a/db/routines/vn/procedures/itemShelving_getSaleDate.sql +++ b/db/routines/vn/procedures/itemShelving_getSaleDate.sql @@ -1,14 +1,20 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_getSaleDate`(vShelvingFk VARCHAR(3)) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_getSaleDate`( + vShelvingCode VARCHAR(10) +) BEGIN - - /* Devuelve la mínima fecha en que se necesita cada producto en esa matrícula. - * - * @param vShelvingFk Matrícula del carro o pallet - */ - +/** + * Devuelve la mínima fecha en que se necesita cada producto en esa matrícula. + * + * @param vShelvingCode Matrícula del carro o pallet + */ DECLARE vWarehouseFk INT; DECLARE vStockScopeDays INT; + DECLARE vShelvingFk INT; + + SELECT id INTO vShelvingFk + FROM shelving + WHERE code COLLATE utf8_unicode_ci = vShelvingCode; SELECT s.warehouseFk, stockScopeDays INTO vWarehouseFk, vStockScopeDays @@ -30,7 +36,7 @@ BEGIN ENGINE = MEMORY SELECT itemFk, SUM(visible) visible FROM itemShelving - WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci + WHERE shelvingFk = vShelvingFk GROUP BY itemFk; CREATE OR REPLACE TEMPORARY TABLE tmp.tStockByDay @@ -52,7 +58,7 @@ BEGIN SELECT ish.itemFk, - SUM(ish.visible), util.VN_CURDATE() FROM itemShelving ish JOIN tmp.tItems i ON i.itemFk = ish.itemFk - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON sh.parkingFk = p.id JOIN sector s ON s.id = p.sectorFk WHERE s.isReserve @@ -110,7 +116,7 @@ BEGIN UPDATE tmp.tStockByDay sbd JOIN (SELECT ish.itemFK, SUM(ish.visible) amount FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk JOIN sector s ON s.id = p.sectorFk WHERE s.warehouseFk = vWarehouseFk @@ -150,10 +156,10 @@ BEGIN p.sectorFk, ish.shelvingFk FROM itemShelving ish - JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.shelving sh ON sh.id = ish.shelvingFk LEFT JOIN parking p ON p.id = parkingFk LEFT JOIN vn.sector s ON s.id = p.sectorFk - WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci + WHERE ish.shelvingFk = vShelvingFk ) sub4 ON sub4.itemFk = ts.itemFk LEFT JOIN sector s ON s.id = sub4.sectorFk LEFT JOIN item i ON i.id = ts.itemFk diff --git a/db/routines/vn/procedures/itemShelving_inventory.sql b/db/routines/vn/procedures/itemShelving_inventory.sql index b57df02e0..9ae96c7a8 100644 --- a/db/routines/vn/procedures/itemShelving_inventory.sql +++ b/db/routines/vn/procedures/itemShelving_inventory.sql @@ -42,7 +42,7 @@ BEGIN JOIN item i ON i.id = ish.itemFk JOIN itemType it ON it.id = i.typeFk JOIN tmp.stockMisfit sm ON sm.itemFk = ish.itemFk - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk LEFT JOIN ( SELECT s.itemFk, sum(s.quantity) notPrepared diff --git a/db/routines/vn/procedures/itemShelving_selfConsumption.sql b/db/routines/vn/procedures/itemShelving_selfConsumption.sql index 083d8d74c..5820b9d28 100644 --- a/db/routines/vn/procedures/itemShelving_selfConsumption.sql +++ b/db/routines/vn/procedures/itemShelving_selfConsumption.sql @@ -1,6 +1,6 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_selfConsumption`( - vShelvingFk VARCHAR(10) COLLATE utf8_general_ci, + vShelvingCode VARCHAR(10) COLLATE utf8_general_ci, vItemFk INT, vQuantity INT ) @@ -9,9 +9,9 @@ BEGIN * Leave the indicated amount on the shelve * and create a ticket with the difference. * - * @param vShelvingFk id of the shelve where the item is located. - * @param vItemFk article of which the self-consumption ticket is to be created. - * @param vQuantity amount that will stay on the shelve + * @param vShelvingCode Code of the shelve where the item is located + * @param vItemFk Item of which the self-consumption ticket is to be created + * @param vQuantity Amount that will stay on the shelve */ DECLARE vVisible INT; DECLARE vClientFk INT; @@ -21,6 +21,11 @@ BEGIN DECLARE vAgencyModeFk INT; DECLARE vItemShelvingFk INT; DECLARE vAddressFk INT; + DECLARE vShelvingFk INT; + + SELECT id INTO vShelvingFk + FROM shelving + WHERE code = vShelvingCode; SELECT c.id, pc.clientSelfConsumptionFk, @@ -37,7 +42,7 @@ BEGIN JOIN parking p ON p.sectorFk = s.id JOIN shelving s2 ON s2.parkingFk = p.id JOIN productionConfig pc - WHERE s2.code = vShelvingFk; + WHERE s2.id = vShelvingFk; IF vClientFk IS NULL THEN CALL util.throw('The company does not have a customer assigned'); @@ -47,7 +52,7 @@ BEGIN CALL util.throw('The shelf cannot have NULL or negative quantities'); END IF; - IF vShelvingFk IS NULL THEN + IF vShelvingCode IS NULL THEN CALL util.throw('The shelf is necessary'); END IF; diff --git a/db/routines/vn/procedures/itemShelving_transfer.sql b/db/routines/vn/procedures/itemShelving_transfer.sql index 95d70227f..e0e6af110 100644 --- a/db/routines/vn/procedures/itemShelving_transfer.sql +++ b/db/routines/vn/procedures/itemShelving_transfer.sql @@ -1,7 +1,7 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_transfer`( vItemShelvingFk INT, - vShelvingFk VARCHAR(10) + vShelvingCode VARCHAR(10) ) BEGIN /** @@ -9,9 +9,14 @@ BEGIN * fusionando si coincide el packing y la fecha. * * @param vItemShelvingFk Identificador de itemShelving - * @param vShelvingFk Identificador de shelving + * @param vShelvingCode Código de shelving */ DECLARE vNewItemShelvingFk INT; + DECLARE vShelvingFk INT; + + SELECT id INTO vShelvingFk + FROM shelving + WHERE code COLLATE utf8_unicode_ci = vShelvingCode; SELECT MAX(ish.id) INTO vNewItemShelvingFk FROM itemShelving ish @@ -26,7 +31,7 @@ BEGIN AND ish2.packing = ish.packing AND DATE(ish2.created) = DATE(ish.created) AND ish2.buyFk = ish.buyFk - WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci; + WHERE ish.shelvingFk = vShelvingFk; IF vNewItemShelvingFk THEN UPDATE itemShelving ish @@ -38,9 +43,7 @@ BEGIN DELETE FROM itemShelving WHERE id = vItemShelvingFk; ELSE - IF (SELECT EXISTS(SELECT id FROM shelving - WHERE code = vShelvingFk COLLATE utf8_unicode_ci)) THEN - + IF (SELECT EXISTS(SELECT id FROM shelving WHERE id = vShelvingFk)) THEN UPDATE itemShelving SET shelvingFk = vShelvingFk WHERE id = vItemShelvingFk; diff --git a/db/routines/vn/procedures/item_devalueA2.sql b/db/routines/vn/procedures/item_devalueA2.sql index d0178f6a7..3264165a6 100644 --- a/db/routines/vn/procedures/item_devalueA2.sql +++ b/db/routines/vn/procedures/item_devalueA2.sql @@ -1,7 +1,7 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`item_devalueA2`( vSelf INT, - vShelvingFK VARCHAR(10), + vShelvingCode VARCHAR(10) COLLATE utf8mb3_general_ci, vBuyingValue DECIMAL(10,4), vQuantity INT ) @@ -12,7 +12,7 @@ BEGIN * de almacén y shelvings correspondientes * * @param vSelf Id de artículo a devaluar - * @param vShelvingFK Ubicación actual del artículo + * @param vShelvingCode Código de shelving / ubicación * @param vBuyingValue Nuevo precio de coste * @param vQuantity Cantidad del ítem a pasar a A2 */ @@ -109,10 +109,11 @@ BEGIN CALL util.throw ('The item has not a buy'); END IF; - SELECT id,visible INTO vTargetItemShelvingFk, vCurrentVisible - FROM itemShelving - WHERE shelvingFk = vShelvingFK COLLATE utf8mb3_general_ci - AND itemFk = vSelf + SELECT ish.id, ish.visible INTO vTargetItemShelvingFk, vCurrentVisible + FROM itemShelving ish + JOIN shelving sh ON sh.id = ish.shelvingFk + WHERE sh.code = vShelvingCode + AND ish.itemFk = vSelf LIMIT 1; IF vCurrentVisible IS NULL THEN @@ -388,16 +389,17 @@ BEGIN userFk, isChecked) SELECT vItemA2Fk, - shelvingFk, + ish.shelvingFk, vQuantity , - `grouping`, - packing, - packagingFk, + ish.`grouping`, + ish.packing, + ish.packagingFk, account.myUser_getId(), - isChecked - FROM itemShelving - WHERE itemFK = vSelf - AND shelvingFk = vShelvingFK COLLATE utf8mb3_general_ci + ish.isChecked + FROM itemShelving ish + JOIN shelving sh ON sh.id = ish.shelvingFk + WHERE ish.itemFK = vSelf + AND sh.code = vShelvingCode ON DUPLICATE KEY UPDATE visible = vQuantity + VALUES(visible); diff --git a/db/routines/vn/procedures/item_getBalance.sql b/db/routines/vn/procedures/item_getBalance.sql index 260f0a527..c4974491c 100644 --- a/db/routines/vn/procedures/item_getBalance.sql +++ b/db/routines/vn/procedures/item_getBalance.sql @@ -59,7 +59,7 @@ BEGIN AND (s.id <> vSupplierInventoryFk OR vDated IS NULL) AND b.itemFk = vItemFk AND NOT e.isExcludedFromAvailable - AND NOT tr.daysInForward + AND NOT tr.isRaid ), entriesOut AS ( SELECT 'entry', @@ -95,7 +95,7 @@ BEGIN AND b.itemFk = vItemFk AND NOT e.isExcludedFromAvailable AND NOT w.isFeedStock - AND NOT tr.daysInForward + AND NOT tr.isRaid ), sales AS ( WITH itemSales AS ( diff --git a/db/routines/vn/procedures/item_getInfo.sql b/db/routines/vn/procedures/item_getInfo.sql index 341142892..bd59728f7 100644 --- a/db/routines/vn/procedures/item_getInfo.sql +++ b/db/routines/vn/procedures/item_getInfo.sql @@ -42,7 +42,6 @@ BEGIN i.minimum `min`, p.name producer, o.code origin, - v.visible - IFNULL(vVisibleItemShelving, 0) unlocated, a.available, vVisibleItemShelving, v.visible, diff --git a/db/routines/vn/procedures/item_getMinacum.sql b/db/routines/vn/procedures/item_getMinacum.sql index 8a42bd737..e3c915820 100644 --- a/db/routines/vn/procedures/item_getMinacum.sql +++ b/db/routines/vn/procedures/item_getMinacum.sql @@ -63,7 +63,7 @@ BEGIN AND NOT e.isExcludedFromAvailable AND b.quantity <> 0 AND (vItemFk IS NULL OR b.itemFk = vItemFk) - AND NOT t.daysInForward + AND NOT t.isRaid UNION ALL SELECT r.itemFk, r.shipment, diff --git a/db/routines/vn/procedures/item_multipleBuyByDate.sql b/db/routines/vn/procedures/item_multipleBuyByDate.sql index 7bd809312..04d3f1855 100644 --- a/db/routines/vn/procedures/item_multipleBuyByDate.sql +++ b/db/routines/vn/procedures/item_multipleBuyByDate.sql @@ -30,7 +30,7 @@ BEGIN AND NOT s.name = 'INVENTARIO' AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) AND w.isComparative - AND NOT t.daysInForward + AND NOT t.isRaid GROUP BY i.id; UPDATE tmp.itemInventory y diff --git a/db/routines/vn/procedures/item_valuateInventory.sql b/db/routines/vn/procedures/item_valuateInventory.sql index b6d687960..7e420be27 100644 --- a/db/routines/vn/procedures/item_valuateInventory.sql +++ b/db/routines/vn/procedures/item_valuateInventory.sql @@ -109,7 +109,7 @@ BEGIN JOIN warehouse w ON w.id = tr.warehouseInFk WHERE tr.landed BETWEEN vInventoried AND vDateDayEnd AND IF(tr.landed = util.VN_CURDATE(), tr.isReceived, TRUE) - AND NOT tr.daysInForward + AND NOT tr.isRaid AND w.valuatedInventory AND t.isInventory AND e.supplierFk <> vInventorySupplierFk @@ -131,7 +131,7 @@ BEGIN JOIN itemCategory ic ON ic.id = t.categoryFk JOIN warehouse w ON w.id = tr.warehouseOutFk WHERE tr.shipped BETWEEN vInventoried AND vDateDayEnd - AND NOT tr.daysInForward + AND NOT tr.isRaid AND w.valuatedInventory AND t.isInventory AND (t.id = vItemTypeFk OR vItemTypeFk IS NULL) @@ -196,7 +196,7 @@ BEGIN JOIN warehouse wIn ON wIn.id = tr.warehouseInFk JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk WHERE vDated >= tr.shipped AND vDated < tr.landed - AND NOT tr.daysInForward + AND NOT tr.isRaid AND wIn.valuatedInventory AND t.isInventory AND e.isConfirmed diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index 6b26e456f..ee18bbe96 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -60,7 +60,7 @@ proc: BEGIN AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk AND w.isComparative AND NOT e.isExcludedFromAvailable - AND NOT t.daysInForward + AND NOT t.isRaid UNION ALL SELECT b.itemFk, - b.quantity FROM buy b @@ -71,7 +71,7 @@ proc: BEGIN AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk AND w.isComparative AND NOT e.isExcludedFromAvailable - AND NOT t.daysInForward + AND NOT t.isRaid ) sub GROUP BY itemFk; @@ -121,7 +121,7 @@ proc: BEGIN AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk AND w.isComparative AND NOT e.isExcludedFromAvailable - AND NOT t.daysInForward + AND NOT t.isRaid UNION ALL SELECT b.itemFk, t.shipped, - b.quantity FROM buy b @@ -132,7 +132,7 @@ proc: BEGIN AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk AND w.isComparative AND NOT e.isExcludedFromAvailable - AND NOT t.daysInForward + AND NOT t.isRaid ) sub GROUP BY sub.itemFk, sub.dated; diff --git a/db/routines/vn/procedures/productionControl.sql b/db/routines/vn/procedures/productionControl.sql index 1d206e20d..813c65ab2 100644 --- a/db/routines/vn/procedures/productionControl.sql +++ b/db/routines/vn/procedures/productionControl.sql @@ -217,7 +217,7 @@ proc: BEGIN st.code = 'previousPrepared' isPreviousPrepared, sc.itemPackingTypeFk FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk JOIN sector sc ON sc.id = p.sectorFk JOIN sectorType st ON st.id = sc.typeFk diff --git a/db/routines/vn/procedures/sale_boxPickingPrint.sql b/db/routines/vn/procedures/sale_boxPickingPrint.sql index 6bb954a78..f156ff8f8 100644 --- a/db/routines/vn/procedures/sale_boxPickingPrint.sql +++ b/db/routines/vn/procedures/sale_boxPickingPrint.sql @@ -27,7 +27,7 @@ BEGIN DECLARE vQuantity INT; DECLARE vRemainder INT DEFAULT 0; DECLARE vRemainderSaleFk INT; - DECLARE vShelving VARCHAR(10); + DECLARE vShelvingFk VARCHAR(10); DECLARE vTicketFk INT; SELECT s.quantity, @@ -74,7 +74,7 @@ w1: WHILE vQuantity >= vPacking DO p.pickingOrder, ish.created FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk LEFT JOIN itemShelvingSale iss ON iss.itemShelvingFk = ish.id @@ -262,9 +262,9 @@ w1: WHILE vQuantity >= vPacking DO CALL dipole.expedition_Add(vExpeditionFk,vPrinterFk, TRUE); SELECT shelvingFk, p.code - INTO vShelving, vParkingCode + INTO vShelvingFk, vParkingCode FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk WHERE ish.id = vItemShelvingFk; @@ -273,7 +273,7 @@ w1: WHILE vQuantity >= vPacking DO itemFk = vItemFk, quantity = vPacking, longName = vConcept, - shelvingFk = vShelving, + shelvingFk = vShelvingFk, parkingCode = vParkingCode, phone = RIGHT(phone,vMaxPhoneLength), street = RIGHT(street, vMAxStreetLength) diff --git a/db/routines/vn/procedures/sale_getBoxPickingList.sql b/db/routines/vn/procedures/sale_getBoxPickingList.sql index f343ab375..4f6a08083 100644 --- a/db/routines/vn/procedures/sale_getBoxPickingList.sql +++ b/db/routines/vn/procedures/sale_getBoxPickingList.sql @@ -41,7 +41,7 @@ BEGIN AND iss.created >= vDated GROUP BY iss.itemShelvingFk, s.itemFk) tISS ON tISS.itemFk = ish.itemFk AND tISS.itemShelvingFk = ish.id - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk JOIN tmp.productionBuffer pb ON pb.ticketFk = s.ticketFk JOIN agencyMode am ON am.id = pb.agencyModeFk diff --git a/db/routines/vn/procedures/sale_getProblems.sql b/db/routines/vn/procedures/sale_getProblems.sql index b50b4784d..e016f3ab4 100644 --- a/db/routines/vn/procedures/sale_getProblems.sql +++ b/db/routines/vn/procedures/sale_getProblems.sql @@ -87,7 +87,7 @@ BEGIN SUM(ish.visible) visible, s.warehouseFk warehouseFk FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk JOIN sector s ON s.id = p.sectorFk GROUP BY ish.itemFk, s.warehouseFk; @@ -127,7 +127,7 @@ BEGIN LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible, 0) < s.quantity - AND IFNULL(av.available, 0) < s.quantity + AND IFNULL(av.available, 0) < 0 AND IFNULL(issw.visible, 0) < s.quantity AND NOT s.isPicked AND NOT s.reserved @@ -190,7 +190,7 @@ BEGIN LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible, 0) < s.quantity - AND IFNULL(av.available, 0) >= s.quantity + AND IFNULL(av.available, 0) >= 0 AND IFNULL(issw.visible, 0) < s.quantity AND s.quantity > 0 AND NOT s.isPicked diff --git a/db/routines/vn/procedures/shelvingChange.sql b/db/routines/vn/procedures/shelvingChange.sql index 2e7e92082..901b1cf95 100644 --- a/db/routines/vn/procedures/shelvingChange.sql +++ b/db/routines/vn/procedures/shelvingChange.sql @@ -1,11 +1,13 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`shelvingChange`(IN `vShelvingO` VARCHAR(8), IN `vShelvingD` VARCHAR(8)) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`shelvingChange`( + `vShelvingO` VARCHAR(10), + `vShelvingD` VARCHAR(10) +) BEGIN - - UPDATE vn.itemShelving - SET shelvingFk = vShelvingD COLLATE utf8_unicode_ci - WHERE shelvingFk = vShelvingO COLLATE utf8_unicode_ci; - - + UPDATE itemShelving ish + JOIN shelving sh1 ON sh1.code = vShelvingD COLLATE utf8_unicode_ci + JOIN shelving sh2 ON sh2.code = vShelvingO COLLATE utf8_unicode_ci + SET ish.shelvingFk = sh1.id + WHERE ish.shelvingFk = sh2.id; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/shelvingParking_get.sql b/db/routines/vn/procedures/shelvingParking_get.sql index a9ed9f74a..c05e8afc3 100644 --- a/db/routines/vn/procedures/shelvingParking_get.sql +++ b/db/routines/vn/procedures/shelvingParking_get.sql @@ -1,8 +1,10 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`shelvingParking_get`(vShelvingFk VARCHAR(10), vWarehouseFk INT, vDayRange INT) -BEGIN - - +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`shelvingParking_get`( + vShelvingCode VARCHAR(10), + vWarehouseFk INT, + vDayRange INT +) +BEGIN SELECT s.itemFk, s.concept, CAST(SUM(s.quantity) AS DECIMAL(10,0)) as sinServir, @@ -10,14 +12,15 @@ SELECT s.itemFk, FROM vn.sale s LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id JOIN vn.ticket t ON t.id = s.ticketFk - LEFT JOIN vn.itemShelvingStock ist ON ist.itemFk = s.itemFk AND ist.warehouseFk = vWarehouseFk - JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk AND ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci + LEFT JOIN vn.itemShelvingStock ist ON ist.itemFk = s.itemFk + AND ist.warehouseFk = vWarehouseFk + JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk + JOIN shelving sh ON sh.id = ish.shelvingFk + AND sh.code = vShelvingCode COLLATE utf8_general_ci WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(TIMESTAMPADD(DAY, GREATEST(0,vDayRange), util.VN_CURDATE())) AND iss.saleFk IS NULL AND t.warehouseFk = vWarehouseFk GROUP BY s.itemFk HAVING sinServir > aparcado; - - END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/shelving_clean.sql b/db/routines/vn/procedures/shelving_clean.sql index 0b29968bc..155338827 100644 --- a/db/routines/vn/procedures/shelving_clean.sql +++ b/db/routines/vn/procedures/shelving_clean.sql @@ -12,12 +12,12 @@ BEGIN DELETE ish.* FROM itemShelving ish - JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.shelving sh ON sh.id = ish.shelvingFk WHERE sh.parkingFk IS NULL AND ish.created < TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); UPDATE shelving sh - LEFT JOIN itemShelving its ON its.shelvingFk = sh.`code` + LEFT JOIN itemShelving its ON its.shelvingFk = sh.id SET isPrinted = 0, parkingFk = NULL WHERE its.id IS NULL @@ -27,11 +27,11 @@ UPDATE shelving sh OR sh.parked < util.VN_CURDATE() - INTERVAL 2 WEEK ) - AND IF(code REGEXP '^[A-Za-z]{2}[0-9]', LEFT (code, 2) NOT IN ( - SELECT DISTINCT LEFT(its.shelvingFk, 2) + SELECT DISTINCT LEFT(sh.code, 2) FROM itemShelving its - WHERE its.shelvingFk REGEXP '^[A-Za-z]{2}[0-9]' + JOIN shelving sh ON sh.id = its.shelvingFk + WHERE sh.code REGEXP '^[A-Za-z]{2}[0-9]' ), TRUE); END$$ diff --git a/db/routines/vn/procedures/shelving_getSpam.sql b/db/routines/vn/procedures/shelving_getSpam.sql index cef407285..a80021cdf 100644 --- a/db/routines/vn/procedures/shelving_getSpam.sql +++ b/db/routines/vn/procedures/shelving_getSpam.sql @@ -25,7 +25,7 @@ BEGIN LEFT JOIN ( SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS reserva FROM vn.itemShelving ish - JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.shelving sh ON sh.id = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector s ON s.id = p.sectorFk WHERE s.code = 'FUENTES_PICASSE' @@ -68,7 +68,7 @@ BEGIN sh.isSpam FROM vn.itemShelving ish JOIN vn.item i ON i.id = ish.itemFk - JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.shelving sh ON sh.id = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector s ON s.id = p.sectorFk JOIN vn.warehouse w ON w.id = s.warehouseFk diff --git a/db/routines/vn/procedures/stockBought_calculate.sql b/db/routines/vn/procedures/stockBought_calculate.sql index 8b2a32e5d..c248d0deb 100644 --- a/db/routines/vn/procedures/stockBought_calculate.sql +++ b/db/routines/vn/procedures/stockBought_calculate.sql @@ -7,13 +7,13 @@ proc: BEGIN * Calculate the stock of the auction warehouse from the inventory date to vDated * without taking into account the outputs of the same day vDated * - * @param vDated Date to calculate the stock. + * @param vDated Date to calculate the stock */ IF vDated < util.VN_CURDATE() THEN LEAVE proc; END IF; - CREATE OR REPLACE TEMPORARY TABLE tStockBought + CREATE OR REPLACE TEMPORARY TABLE tCurrentData SELECT workerFk, reserve FROM stockBought WHERE dated = vDated @@ -21,15 +21,28 @@ proc: BEGIN DELETE FROM stockBought WHERE dated = vDated; + CREATE OR REPLACE TEMPORARY TABLE tStockSold + SELECT it.workerFk, + SUM(ic.cm3 * ito.quantity / vc.palletM3 / 1000000) sold + FROM itemTicketOut ito + JOIN item i ON i.id = ito.itemFk + JOIN itemType it ON it.id = i.typeFk + JOIN ticket t ON t.id = ito.ticketFk + JOIN warehouse wh ON wh.id = t.warehouseFk + JOIN itemCost ic ON ic.itemFk = ito.itemFk + AND ic.warehouseFk = t.warehouseFk + JOIN volumeConfig vc + WHERE ito.shipped BETWEEN vDated AND util.dayEnd(vDated) + AND wh.code = 'VNH' + GROUP BY it.workerFk; + CALL item_calculateStock(vDated); - INSERT INTO stockBought(workerFk, bought, dated) + CREATE OR REPLACE TEMPORARY TABLE tStockBought SELECT it.workerFk, - ROUND(SUM( - (ti.quantity / b.packing) * - buy_getVolume(b.id) - ) / vc.palletM3 / 1000000, 1) bought, - vDated + SUM((ti.quantity / b.packing) * + buy_getVolume(b.id) + ) / vc.palletM3 / 1000000 bought FROM itemType it JOIN item i ON i.typeFk = it.id LEFT JOIN tmp.item ti ON ti.itemFk = i.id @@ -43,20 +56,33 @@ proc: BEGIN GROUP BY it.workerFk HAVING bought; + + INSERT INTO stockBought(workerFk, bought, dated) + SELECT tb.workerFk, + ROUND(GREATEST(tb.bought - IFNULL(ts.sold, 0), 0), 2), + vDated + FROM tStockBought tb + LEFT JOIN tStockSold ts ON ts.workerFk = tb.workerFk; + UPDATE stockBought s - JOIN tStockBought ts ON ts.workerFk = s.workerFk + JOIN tCurrentData ts ON ts.workerFk = s.workerFk SET s.reserve = ts.reserve WHERE s.dated = vDated; INSERT INTO stockBought (workerFk, reserve, dated) SELECT ts.workerFk, ts.reserve, vDated - FROM tStockBought ts + FROM tCurrentData ts WHERE ts.workerFk NOT IN ( SELECT workerFk FROM stockBought WHERE dated = vDated ); - DROP TEMPORARY TABLE tStockBought, tmp.item, tmp.buyUltimate; + UPDATE stockBought s + JOIN tStockSold ts ON ts.workerFk = s.workerFk + SET s.bought = IF(s.bought < ABS(ts.sold), 0, ROUND(s.bought - ABS(ts.sold), 1)) + WHERE s.dated = vDated; + + DROP TEMPORARY TABLE tCurrentData, tmp.item, tmp.buyUltimate, tStockSold; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/stockBuyedByWorker.sql b/db/routines/vn/procedures/stockBuyedByWorker.sql new file mode 100644 index 000000000..536638770 --- /dev/null +++ b/db/routines/vn/procedures/stockBuyedByWorker.sql @@ -0,0 +1,74 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`stockBuyedByWorker`( + vDated DATE, + vWorker INT +) +BEGIN +/** + * Inserta el volumen de compra de un comprador + * en stockBuyed de acuerdo con la fecha. + * + * @param vDated Fecha de compra + * @param vWorker Id de trabajador + */ + CREATE OR REPLACE TEMPORARY TABLE tStockBuyed + (INDEX (userFk)) + ENGINE = MEMORY + SELECT requested, reserved, userFk + FROM stockBuyed + WHERE dated = vDated + AND userFk = vWorker; + + DELETE FROM stockBuyed + WHERE dated = vDated + AND userFk = vWorker; + + CALL item_calculateStock(vDated); + + INSERT INTO stockBuyed(userFk, buyed, `dated`, reserved, requested, description) + SELECT it.workerFk, + SUM((ti.quantity / b.packing) * buy_getVolume(b.id)) / vc.palletM3 / 1000000, + vDated, + sb.reserved, + sb.requested, + u.name + FROM itemType it + JOIN item i ON i.typeFk = it.id + LEFT JOIN tmp.item ti ON ti.itemFk = i.id + JOIN itemCategory ic ON ic.id = it.categoryFk + JOIN warehouse wh ON wh.code = 'VNH' + JOIN tmp.buyUltimate bu ON bu.itemFk = i.id + AND bu.warehouseFk = wh.id + JOIN buy b ON b.id = bu.buyFk + JOIN volumeConfig vc + JOIN account.`user` u ON u.id = it.workerFk + LEFT JOIN tStockBuyed sb ON sb.userFk = it.workerFk + WHERE ic.display + AND it.workerFk = vWorker; + + SELECT b.entryFk Id_Entrada, + i.id Id_Article, + i.name Article, + ti.quantity Cantidad, + (ac.conversionCoefficient * (ti.quantity / b.packing) * buy_getVolume(b.id)) + / (vc.trolleyM3 * 1000000) buyed, + b.packagingFk id_cubo, + b.packing + FROM tmp.item ti + JOIN item i ON i.id = ti.itemFk + JOIN itemType it ON i.typeFk = it.id + JOIN itemCategory ic ON ic.id = it.categoryFk + JOIN worker w ON w.id = it.workerFk + JOIN auctionConfig ac + JOIN tmp.buyUltimate bu ON bu.itemFk = i.id + AND bu.warehouseFk = ac.warehouseFk + JOIN buy b ON b.id = bu.buyFk + JOIN volumeConfig vc + WHERE ic.display + AND w.id = vWorker; + + DROP TEMPORARY TABLE tmp.buyUltimate, + tmp.item, + tStockBuyed; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/stockBuyed_add.sql b/db/routines/vn/procedures/stockBuyed_add.sql new file mode 100644 index 000000000..0491c2424 --- /dev/null +++ b/db/routines/vn/procedures/stockBuyed_add.sql @@ -0,0 +1,70 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`stockBuyed_add`( + vDated DATE +) +BEGIN +/** + * Inserta el volumen de compra por comprador + * en stockBuyed de acuerdo con la fecha. + * + * @param vDated Fecha de compra + */ + CREATE OR REPLACE TEMPORARY TABLE tStockBuyed + (INDEX (userFk)) + ENGINE = MEMORY + SELECT requested, reserved, userFk + FROM stockBuyed + WHERE dated = vDated; + + DELETE FROM stockBuyed WHERE dated = vDated; + + CALL item_calculateStock(vDated); + + INSERT INTO stockBuyed(userFk, buyed, `dated`, description) + SELECT it.workerFk, + SUM((ti.quantity / b.packing) * buy_getVolume(b.id)) / vc.palletM3 / 1000000, + vDated, + u.name + FROM itemType it + JOIN item i ON i.typeFk = it.id + LEFT JOIN tmp.item ti ON ti.itemFk = i.id + JOIN itemCategory ic ON ic.id = it.categoryFk + JOIN warehouse wh ON wh.code = 'VNH' + JOIN tmp.buyUltimate bu ON bu.itemFk = i.id AND bu.warehouseFk = wh.id + JOIN buy b ON b.id = bu.buyFk + JOIN volumeConfig vc + JOIN account.`user` u ON u.id = it.workerFk + JOIN workerDepartment wd ON wd.workerFk = u.id + JOIN department d ON d.id = wd.departmentFk + WHERE ic.display + AND d.code IN ('shopping', 'logistic', 'franceTeam') + GROUP BY it.workerFk; + + INSERT INTO stockBuyed(buyed, dated, description) + SELECT SUM(ic.cm3 * ito.quantity / vc.palletM3 / 1000000), + vDated, + IF(c.code = 'ES', p.name, c.name) destiny + FROM itemTicketOut ito + JOIN ticket t ON t.id = ito.ticketFk + JOIN `address` a ON a.id = t.addressFk + JOIN province p ON p.id = a.provinceFk + JOIN country c ON c.id = p.countryFk + JOIN warehouse wh ON wh.id = t.warehouseFk + JOIN itemCost ic ON ic.itemFk = ito.itemFk + AND ic.warehouseFk = t.warehouseFk + JOIN volumeConfig vc + WHERE ito.shipped BETWEEN vDated AND util.dayend(vDated) + AND wh.code = 'VNH' + GROUP BY destiny; + + UPDATE stockBuyed s + JOIN tStockBuyed ts ON ts.userFk = s.userFk + SET s.requested = ts.requested, + s.reserved = ts.reserved + WHERE s.dated = vDated; + + DROP TEMPORARY TABLE tmp.buyUltimate, + tmp.item, + tStockBuyed; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/ticketDown_PrintableSelection.sql b/db/routines/vn/procedures/ticketDown_PrintableSelection.sql index 082a890a6..8f448d647 100644 --- a/db/routines/vn/procedures/ticketDown_PrintableSelection.sql +++ b/db/routines/vn/procedures/ticketDown_PrintableSelection.sql @@ -9,7 +9,7 @@ BEGIN JOIN vn.sale s ON s.ticketFk = t.id JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id JOIN vn.itemShelving ish ON ish.id = iss.itemShelvingFk - JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.shelving sh ON sh.id = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk WHERE p.sectorFk = vSectorFk ) sub ON sub.id = td.ticketFk diff --git a/db/routines/vn/procedures/ticket_DelayTruckSplit.sql b/db/routines/vn/procedures/ticket_DelayTruckSplit.sql index 1dc45d065..3d22207f3 100644 --- a/db/routines/vn/procedures/ticket_DelayTruckSplit.sql +++ b/db/routines/vn/procedures/ticket_DelayTruckSplit.sql @@ -27,7 +27,7 @@ BEGIN SUM(ish.visible) visible, s.warehouseFk warehouseFk FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk JOIN sector s ON s.id = p.sectorFk GROUP BY ish.itemFk, diff --git a/db/routines/vn/procedures/ticket_getSplitList.sql b/db/routines/vn/procedures/ticket_getSplitList.sql index 988bc2931..66e9bdb57 100644 --- a/db/routines/vn/procedures/ticket_getSplitList.sql +++ b/db/routines/vn/procedures/ticket_getSplitList.sql @@ -28,7 +28,7 @@ BEGIN SUM(ish.visible) visible, s.warehouseFk warehouseFk FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk JOIN sector s ON s.id = p.sectorFk GROUP BY ish.itemFk, diff --git a/db/routines/vn/procedures/ticket_splitItemPackingType.sql b/db/routines/vn/procedures/ticket_splitItemPackingType.sql index 9a4bc01eb..31e0c24e7 100644 --- a/db/routines/vn/procedures/ticket_splitItemPackingType.sql +++ b/db/routines/vn/procedures/ticket_splitItemPackingType.sql @@ -3,87 +3,124 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_splitItemPacki vSelf INT, vOriginalItemPackingTypeFk VARCHAR(1) ) -proc:BEGIN +BEGIN /** - * Clona y reparte las líneas de ventas de un ticket en funcion del tipo de empaquetado. - * Respeta el id de ticket original para el tipo de empaquetado propuesto. + * Separa en diferentes tickets según el tipo de empaquetado + * El ticket original conserva las líneas del tipo de empaquetado especificado + * Las líneas sin tipo de empaquetado se asignan al ticket del tipo por defecto. * - * @param vSelf Id ticket - * @param vOriginalItemPackingTypeFk Tipo empaquetado que se mantiene el ticket original + * @param vSelf Id del ticket original + * @param vOriginalItemPackingTypeFk Tipo de empaquetado a mantener en el ticket original * @return table tmp.ticketIPT(ticketFk, itemPackingTypeFk) */ - DECLARE vDone INT DEFAULT FALSE; - DECLARE vHasItemPackingType BOOL; - DECLARE vItemPackingTypeFk INT; + DECLARE vIsDone BOOLEAN DEFAULT FALSE; + DECLARE vCurrentPackingType VARCHAR(1); + DECLARE vDefaultPackingType VARCHAR(1); + DECLARE vHasOriginalPackingType BOOLEAN; DECLARE vNewTicketFk INT; + DECLARE vTicketFk INT; - DECLARE vItemPackingTypes CURSOR FOR - SELECT DISTINCT itemPackingTypeFk - FROM tSalesToMove; + DECLARE vItemPackingTypes CURSOR FOR + SELECT DISTINCT itemPackingTypeFk FROM tSalesToMove; - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE; - SELECT COUNT(*) INTO vHasItemPackingType - FROM ticket t - JOIN sale s ON s.ticketFk = t.id - JOIN item i ON i.id = s.itemFk - WHERE t.id = vSelf - AND i.itemPackingTypeFk = vOriginalItemPackingTypeFk; - - CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT( - ticketFk INT, - itemPackingTypeFk VARCHAR(1) - ) ENGINE=MEMORY - SELECT vSelf ticketFk, vOriginalItemPackingTypeFk itemPackingTypeFk; - - IF NOT vHasItemPackingType THEN - LEAVE proc; - END IF; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; CREATE OR REPLACE TEMPORARY TABLE tSalesToMove ( ticketFk INT, saleFk INT, - itemPackingTypeFk INT + itemPackingTypeFk VARCHAR(1) ) ENGINE=MEMORY; + SELECT COALESCE(MAX(ic.defaultPackingTypeFk), MAX(i.itemPackingTypeFk)) INTO vDefaultPackingType + FROM vn.sale s + JOIN item i ON i.id = s.itemFk + LEFT JOIN itemConfig ic ON ic.defaultPackingTypeFk = i.itemPackingTypeFk + WHERE s.ticketFk = vSelf + GROUP BY s.ticketFk; + + SELECT EXISTS ( + SELECT TRUE + FROM sale s + JOIN item i ON i.id = s.itemFk + WHERE s.ticketFk = vSelf + AND i.itemPackingTypeFk = vOriginalItemPackingTypeFk + ) INTO vHasOriginalPackingType; + + IF vOriginalItemPackingTypeFk IS NULL OR NOT vHasOriginalPackingType THEN + SET vOriginalItemPackingTypeFk = vDefaultPackingType; + END IF; + + START TRANSACTION; + + SELECT t.id INTO vTicketFk + FROM ticket t + JOIN sale s ON s.id = t.id + WHERE t.id = vSelf + FOR UPDATE; + INSERT INTO tSalesToMove (saleFk, itemPackingTypeFk) - SELECT s.id, i.itemPackingTypeFk - FROM ticket t - JOIN sale s ON s.ticketFk = t.id - JOIN item i ON i.id = s.itemFk - WHERE t.id = vSelf + SELECT s.id, i.itemPackingTypeFk + FROM sale s + JOIN item i ON i.id = s.itemFk + WHERE s.ticketFk = vSelf AND i.itemPackingTypeFk <> vOriginalItemPackingTypeFk; OPEN vItemPackingTypes; - l: LOOP - SET vDone = FALSE; - FETCH vItemPackingTypes INTO vItemPackingTypeFk; + SET vIsDone = FALSE; + FETCH vItemPackingTypes INTO vCurrentPackingType; - IF vDone THEN + IF vIsDone THEN LEAVE l; END IF; CALL ticket_Clone(vSelf, vNewTicketFk); + SELECT id INTO vTicketFk + FROM ticket t + WHERE t.id = vNewTicketFk + FOR UPDATE; + UPDATE tSalesToMove SET ticketFk = vNewTicketFk - WHERE itemPackingTypeFk = vItemPackingTypeFk; + WHERE itemPackingTypeFk = vCurrentPackingType; + + IF vCurrentPackingType = vDefaultPackingType THEN + INSERT INTO tSalesToMove (ticketFk, saleFk, itemPackingTypeFk) + SELECT vNewTicketFk, s.id, i.itemPackingTypeFk + FROM sale s + JOIN item i ON i.id = s.itemFk + WHERE s.ticketFk = vSelf + AND i.itemPackingTypeFk IS NULL; + END IF; END LOOP; - CLOSE vItemPackingTypes; UPDATE sale s - JOIN tSalesToMove stm ON stm.saleFk = s.id - SET s.ticketFk = stm.ticketFk - WHERE stm.ticketFk; + JOIN tSalesToMove t ON t.saleFk = s.id + SET s.ticketFk = t.ticketFk; - INSERT INTO tmp.ticketIPT (ticketFk, itemPackingTypeFk) - SELECT ticketFk, itemPackingTypeFk + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT + ENGINE=MEMORY + SELECT s.ticketFk, MAX(i.itemPackingTypeFk) itemPackingTypeFk + FROM sale s + JOIN item i ON i.id = s.itemFk + WHERE s.ticketFk = vSelf + GROUP BY s.ticketFk + UNION + SELECT ticketFk, MAX(itemPackingTypeFk) FROM tSalesToMove GROUP BY ticketFk; + COMMIT; + DROP TEMPORARY TABLE tSalesToMove; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/travelVolume_get.sql b/db/routines/vn/procedures/travelVolume_get.sql index bb98cacdf..ab24a6395 100644 --- a/db/routines/vn/procedures/travelVolume_get.sql +++ b/db/routines/vn/procedures/travelVolume_get.sql @@ -10,7 +10,7 @@ BEGIN JOIN vn.entry e ON e.travelFk = tr.id JOIN vn.buy b ON b.entryFk = e.id WHERE tr.landed BETWEEN vFromDated AND vToDated - AND NOT tr.daysInForward + AND NOT tr.isRaid AND tr.warehouseInFk = vWarehouseFk GROUP BY tr.landed , a.name ; END$$ diff --git a/db/routines/vn/procedures/travel_checkRaid.sql b/db/routines/vn/procedures/travel_checkRaid.sql new file mode 100644 index 000000000..64f3355e2 --- /dev/null +++ b/db/routines/vn/procedures/travel_checkRaid.sql @@ -0,0 +1,17 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`travel_checkRaid`( + vIsRaid BOOL, + vDaysInForward INT +) +BEGIN +/** + * Check if the values of isRaid and daysInforward are correct + * + * @param vIsRaid idRaid value + * @param vDaysInForward daysInForward value + */ + IF (NOT vIsRaid AND vDaysInForward IS NOT NULL) OR (vIsRaid AND vDaysInForward IS NULL) THEN + CALL util.throw('The raid information is not correct'); + END IF; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/travel_moveRaids.sql b/db/routines/vn/procedures/travel_moveRaids.sql index aa554a1a0..cf0fce23c 100644 --- a/db/routines/vn/procedures/travel_moveRaids.sql +++ b/db/routines/vn/procedures/travel_moveRaids.sql @@ -3,7 +3,7 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`travel_moveRaids`() BEGIN /** * Desplaza los travels en el futuro y avisa a los compradores - * + * */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vBuyerEmail VARCHAR(40); @@ -11,21 +11,21 @@ BEGIN DECLARE vMailBody TEXT DEFAULT ''; DECLARE vCur CURSOR FOR - SELECT GROUP_CONCAT(DISTINCT - CONCAT('https://salix.verdnatura.es/#!/travel/', - ttm.travelFk, + SELECT GROUP_CONCAT(DISTINCT + CONCAT('https://salix.verdnatura.es/#!/travel/', + ttm.travelFk, '/summary ') ORDER BY ttm.travelFk SEPARATOR '\n\r') travelLink, CONCAT(u.name, '@verdnatura.es') buyerEmail FROM tTravelToMove ttm - JOIN entry e ON e.travelFk = ttm.travelFk + JOIN entry e ON e.travelFk = ttm.travelFk JOIN buy b ON b.entryFk = e.id JOIN item i ON i.id = b.itemFk JOIN itemType it ON it.id = i.typeFk JOIN account.user u ON u.id = it.workerFk GROUP BY u.name; - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN @@ -34,10 +34,11 @@ BEGIN END; CREATE OR REPLACE TEMPORARY TABLE tTravelToMove - SELECT id travelFk, + SELECT id travelFk, util.VN_CURDATE() + INTERVAL daysInForward DAY newLanded FROM travel - WHERE daysInForward; + WHERE isRaid + AND daysInForward; START TRANSACTION; diff --git a/db/routines/vn/procedures/workerTimeControl_check.sql b/db/routines/vn/procedures/workerTimeControl_check.sql deleted file mode 100644 index 30cf5c639..000000000 --- a/db/routines/vn/procedures/workerTimeControl_check.sql +++ /dev/null @@ -1,168 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`workerTimeControl_check`(vUserFk INT, vDated DATE,vTabletFk VARCHAR(100)) -proc: BEGIN -/** - * Verifica si el empleado puede fichar en el momento actual, si puede fichar llama a workerTimeControlAdd - * - * @param vUserFk Identificador del trabajador - * @return Retorna si encuentra un problema 'odd','maxTimeWork','breakDay','breakWeek' ; - * En caso de tener algun problema retorna el primero que encuentra - */ - DECLARE vLastIn DATETIME ; - DECLARE vLastOut DATETIME ; - DECLARE vDayWorkMax INT; - DECLARE vDayBreak INT; - DECLARE vWeekBreak INT ; - DECLARE vWeekScope INT; - DECLARE vDayStayMax INT; - DECLARE vProblem VARCHAR(20) DEFAULT NULL; - DECLARE vTimedWorked INT; - DECLARE vCalendarStateType VARCHAR(20) DEFAULT NULL; - DECLARE vDepartmentFk INT; - DECLARE vTo VARCHAR(50) DEFAULT NULL; - DECLARE vUserName VARCHAR(50) DEFAULT NULL; - DECLARE vBody VARCHAR(255) DEFAULT NULL; - - SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax - INTO vDayBreak, vWeekBreak, vWeekScope, vDayWorkMax, vDayStayMax - FROM workerTimeControlParams; - - SELECT MAX(timed) INTO vLastIn - FROM workerTimeControl - WHERE userFk = vUserFk - AND direction = 'in'; - - SELECT MAX(timed) INTO vLastOut - FROM workerTimeControl - WHERE userFk = vUserFk - AND direction = 'out'; - - SELECT CONCAT(u.name,'@verdnatura.es') INTO vTo - FROM account.user u - WHERE u.id = (SELECT bossFk FROM worker WHERE id = vUserFk); - - SELECT CONCAT(firstName,' ',lastName) INTO vUserName - FROM worker w - WHERE w.id = vUserFk; - - - IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastIn) > vDayStayMax THEN -- NUEVA JORNADA - - -- VERIFICAR DESCANSO DIARIO - IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN - SELECT "Descansos 12 h" AS problem; - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 12 h") INTO vBody; - CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - END IF; - - -- VERIFICAR FICHADAS IMPARES DEL ÚLTIMO DÍA QUE SE FICHÓ - IF (SELECT MOD(COUNT(*),2) -- <>0 - FROM workerTimeControl - WHERE userFk = vUserFk - AND timed >= vLastIn - ) THEN - SELECT "Dias con fichadas impares" AS problem; - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Dias con fichadas impares") INTO vBody; - CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - END IF; - - -- VERIFICAR VACACIONES - SELECT at2.name INTO vCalendarStateType - FROM calendar c - JOIN business b ON b.id = c.businessFk - JOIN absenceType at2 ON at2.id = c.dayOffTypeFk - WHERE c.dated = util.VN_CURDATE() - AND at2.isAllowedToWork = FALSE - AND b.workerFk = vUserFk - LIMIT 1; - - IF(LENGTH(vCalendarStateType)) THEN - SELECT vCalendarStateType AS problem; - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Vacaciones") INTO vBody; - CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - - END IF; - - -- VERIFICAR CONTRATO EN VIGOR - IF (SELECT COUNT(*) - FROM business b - WHERE b.workerFk = vUserFk - AND b.started <= vDated - AND IFNULL(b.ended, vDated) >= vDated - ) = 0 THEN - SELECT "No hay un contrato en vigor" AS problem; - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"No hay un contrato en vigor") INTO vBody; - CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - - END IF; - - -- VERIFICAR DESCANSO SEMANAL - SET @vHasBreakWeek:= FALSE; - SET @vLastTimed:= UNIX_TIMESTAMP((util.VN_NOW() - INTERVAL vWeekScope SECOND)); - - DROP TEMPORARY TABLE IF EXISTS tmp.trash; - CREATE TEMPORARY TABLE tmp.trash - SELECT IF(vWeekBreak-(UNIX_TIMESTAMP(timed)-@vLastTimed) <= 0, @vHasBreakWeek:=TRUE, TRUE) alias, - @vLastTimed:= UNIX_TIMESTAMP(timed) - FROM workerTimeControl - WHERE timed>= (util.VN_NOW() - INTERVAL vWeekScope SECOND) - AND userFk= vUserFk - AND direction IN ('in','out') - ORDER BY timed ASC; - - IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA - SELECT "Descansos 36 h" AS problem; - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 36 h") INTO vBody; - CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - END IF; - - DROP TEMPORARY TABLE tmp.trash; - - ELSE -- DIA ACTUAL - - -- VERIFICA QUE EL TIEMPO EFECTIVO NO SUPERE EL MÁXIMO - SELECT IFNULL(SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))),0) - IF( MOD(COUNT(*),2), UNIX_TIMESTAMP(util.VN_NOW()), 0) INTO vTimedWorked - FROM workerTimeControl wtc - WHERE userFk = vUserFk - AND timed >= vLastIn - ORDER BY timed; - - IF vTimedWorked > vDayWorkMax THEN - SELECT "Jornadas" AS problem; - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Jornadas") INTO vBody; - CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - END IF; - - END IF; - - -- VERIFICAR DEPARTAMENTO - /* IF vTabletFk IS NOT NULL THEN - SELECT wtcu.departmentFk INTO vDepartmentFk - FROM workerTimeControlUserInfo wtcu - WHERE wtcu.userFk = vUserFk; - IF (SELECT COUNT(td.tabletFk) - FROM tabletDepartment td - WHERE td.tabletFk = vTabletFk AND td.departmentFk = vDepartmentFk - ) = 0 THEN - SELECT "No perteneces a este departamento." AS problem; - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No perteneces a este departamento.") INTO vBody; - CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - END IF; - END IF;*/ - -END$$ -DELIMITER ; diff --git a/db/routines/vn/triggers/address_beforeInsert.sql b/db/routines/vn/triggers/address_beforeInsert.sql index 56ef7aa51..a4f384f14 100644 --- a/db/routines/vn/triggers/address_beforeInsert.sql +++ b/db/routines/vn/triggers/address_beforeInsert.sql @@ -6,6 +6,7 @@ BEGIN DECLARE vIsEqualizated BOOL; SET NEW.editorFk = account.myUser_getId(); + SET NEW.geoFk = address_getGeo(NEW.id); IF (NEW.phone <> '') THEN CALL pbx.phone_isValid(NEW.phone); diff --git a/db/routines/vn/triggers/address_beforeUpdate.sql b/db/routines/vn/triggers/address_beforeUpdate.sql index 35887912c..0b19a6266 100644 --- a/db/routines/vn/triggers/address_beforeUpdate.sql +++ b/db/routines/vn/triggers/address_beforeUpdate.sql @@ -3,7 +3,6 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`address_beforeUpdate` BEFORE UPDATE ON `address` FOR EACH ROW BEGIN - SET NEW.editorFk = account.myUser_getId(); IF !(NEW.phone <=> OLD.phone) AND (NEW.phone <> '') THEN @@ -14,5 +13,10 @@ BEGIN CALL pbx.phone_isValid(NEW.mobile); END IF; + IF NOT (NEW.provinceFk <=> OLD.provinceFk) + OR (NEW.postalCode <=> OLD.postalCode) THEN + + SET NEW.geoFk = address_getGeo(NEW.id); + END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/client_beforeInsert.sql b/db/routines/vn/triggers/client_beforeInsert.sql index 45de107f1..b4038a2ba 100644 --- a/db/routines/vn/triggers/client_beforeInsert.sql +++ b/db/routines/vn/triggers/client_beforeInsert.sql @@ -3,8 +3,10 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`client_beforeInsert` BEFORE INSERT ON `client` FOR EACH ROW BEGIN - SET NEW.editorFk = account.myUser_getId(); + SET NEW.accountingAccount = 4300000000 + NEW.id; + SET NEW.lastSalesPersonFk = NEW.salesPersonFk; + SET NEW.geoFk = client_getGeo(NEW.id); IF (NEW.phone <> '') THEN CALL pbx.phone_isValid(NEW.phone); @@ -13,9 +15,5 @@ BEGIN IF (NEW.mobile <> '') THEN CALL pbx.phone_isValid(NEW.mobile); END IF; - - SET NEW.accountingAccount = 4300000000 + NEW.id; - - SET NEW.lastSalesPersonFk = NEW.salesPersonFk; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/client_beforeUpdate.sql b/db/routines/vn/triggers/client_beforeUpdate.sql index 7142d6604..00418a9e7 100644 --- a/db/routines/vn/triggers/client_beforeUpdate.sql +++ b/db/routines/vn/triggers/client_beforeUpdate.sql @@ -72,5 +72,11 @@ BEGIN IF NOT (NEW.businessTypeFk <=> OLD.businessTypeFk) AND (NEW.businessTypeFk = 'individual' OR OLD.businessTypeFk = 'individual') THEN SET NEW.isTaxDataChecked = 0; END IF; + + IF NOT (NEW.provinceFk <=> OLD.provinceFk) + OR (NEW.postcode <=> OLD.postcode) THEN + + SET NEW.geoFk = client_getGeo(NEW.id); + END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/entry_beforeUpdate.sql b/db/routines/vn/triggers/entry_beforeUpdate.sql index 3b999012f..4f2c5ed4a 100644 --- a/db/routines/vn/triggers/entry_beforeUpdate.sql +++ b/db/routines/vn/triggers/entry_beforeUpdate.sql @@ -3,7 +3,7 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`entry_beforeUpdate` BEFORE UPDATE ON `entry` FOR EACH ROW BEGIN - DECLARE vDaysInForward INT; + DECLARE vIsRaid BOOL; DECLARE vPrintedCount INT; DECLARE vHasDistinctWarehouses BOOL; DECLARE vTotalBuy INT; @@ -38,10 +38,10 @@ BEGIN CALL travel_throwAwb(NEW.travelFk); END IF; - SELECT daysInForward INTO vDaysInForward + SELECT t.isRaid INTO vIsRaid FROM travel t JOIN entry e ON e.travelFk = t.id - WHERE entryFk = NEW.id; + WHERE e.id = NEW.id; SELECT NOT (o.warehouseInFk <=> n.warehouseInFk) OR NOT (o.warehouseOutFk <=> n.warehouseOutFk) @@ -50,7 +50,7 @@ BEGIN WHERE o.id = OLD.travelFk AND n.id = NEW.travelFk; - IF vDaysInForward AND vHasDistinctWarehouses THEN + IF vIsRaid AND vHasDistinctWarehouses THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'A cloned entry cannot be moved to a travel with different warehouses'; END IF; diff --git a/db/routines/vn/triggers/route_afterUpdate.sql b/db/routines/vn/triggers/route_afterUpdate.sql index ec205090e..447608acc 100644 --- a/db/routines/vn/triggers/route_afterUpdate.sql +++ b/db/routines/vn/triggers/route_afterUpdate.sql @@ -2,18 +2,18 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`route_afterUpdate` AFTER UPDATE ON `route` FOR EACH ROW -BEGIN +BEGIN IF IFNULL(NEW.gestdocFk,0) <> IFNULL(OLD.gestdocFk,0) AND NEW.gestdocFk > 0 THEN -- JGF 09/09/14 cuando se añade un gestdoc a una ruta, se le asigna automagicamente a todos sus Tickets - + -- Inserta el gestdoc en todos los tickets de la ruta INSERT INTO ticketDms(ticketFk,dmsFk) SELECT id, NEW.gestdocFk FROM ticket WHERE routeFk = NEW.id ON DUPLICATE KEY UPDATE dmsFk = NEW.gestdocFk; - -- Update del firmado - UPDATE ticket t - JOIN ticketDms tg ON t.id = tg.ticketFk + -- Update del firmado + UPDATE ticket t + JOIN ticketDms tg ON t.id = tg.ticketFk SET isSigned = 1 WHERE t.routeFk = NEW.id; END IF; @@ -21,7 +21,8 @@ BEGIN OR !(NEW.kmEnd <=> OLD.kmEnd) OR !(NEW.workerFk <=> OLD.workerFk) OR !(NEW.m3 <=> OLD.m3) - OR !(NEW.agencyModeFk <=> OLD.agencyModeFk)THEN + OR !(NEW.agencyModeFk <=> OLD.agencyModeFk) + OR !(NEW.vehicleFk <=> OLD.vehicleFk)THEN CALL route_calcCommission(NEW.id); END IF; diff --git a/db/routines/vn/triggers/supplier_beforeInsert.sql b/db/routines/vn/triggers/supplier_beforeInsert.sql index b141ec8fb..5bbfc79a1 100644 --- a/db/routines/vn/triggers/supplier_beforeInsert.sql +++ b/db/routines/vn/triggers/supplier_beforeInsert.sql @@ -4,5 +4,6 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`supplier_beforeInsert` FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); + SET NEW.geoFk = supplier_getGeo(NEW.id); END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/supplier_beforeUpdate.sql b/db/routines/vn/triggers/supplier_beforeUpdate.sql index af730b49d..b502340a3 100644 --- a/db/routines/vn/triggers/supplier_beforeUpdate.sql +++ b/db/routines/vn/triggers/supplier_beforeUpdate.sql @@ -40,5 +40,10 @@ BEGIN SET NEW.isPayMethodChecked = FALSE; END IF; + IF NOT (NEW.provinceFk <=> OLD.provinceFk) + OR (NEW.postCode <=> OLD.postCode) THEN + + SET NEW.geoFk = supplier_getGeo(NEW.id); + END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/town_beforeUpdate.sql b/db/routines/vn/triggers/town_beforeUpdate.sql deleted file mode 100644 index fc1410d5c..000000000 --- a/db/routines/vn/triggers/town_beforeUpdate.sql +++ /dev/null @@ -1,10 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`town_beforeUpdate` - BEFORE UPDATE ON `town` - FOR EACH ROW -BEGIN - -- IF !(OLD.geoFk <=> NEW.geoFk) THEN - -- CALL zoneGeo_throwNotEditable; - -- END IF; -END$$ -DELIMITER ; diff --git a/db/routines/vn/triggers/travel_beforeInsert.sql b/db/routines/vn/triggers/travel_beforeInsert.sql index 4563c9a81..5356ed537 100644 --- a/db/routines/vn/triggers/travel_beforeInsert.sql +++ b/db/routines/vn/triggers/travel_beforeInsert.sql @@ -8,7 +8,11 @@ BEGIN CALL travel_checkDates(NEW.shipped, NEW.landed); CALL travel_checkWarehouseIsFeedStock(NEW.warehouseInFk); - + + IF NEW.isRaid IS NOT NULL OR NEW.daysInForward IS NOT NULL THEN + CALL travel_checkRaid(NEW.isRaid, NEW.daysInForward); + END IF; + IF NEW.awbFk IS NOT NULL THEN CALL travel_throwAwb(NEW.id); END IF; diff --git a/db/routines/vn/triggers/travel_beforeUpdate.sql b/db/routines/vn/triggers/travel_beforeUpdate.sql index 33578fea1..5a27b43b4 100644 --- a/db/routines/vn/triggers/travel_beforeUpdate.sql +++ b/db/routines/vn/triggers/travel_beforeUpdate.sql @@ -7,7 +7,7 @@ BEGIN SET NEW.editorFk = account.myUser_getId(); - IF NOT (NEW.landed <=> OLD.landed) + IF NOT (NEW.landed <=> OLD.landed) OR NOT (NEW.shipped <=> OLD.shipped) THEN CALL travel_checkDates(NEW.shipped, NEW.landed); END IF; @@ -20,19 +20,23 @@ BEGIN CALL travel_checkWarehouseIsFeedStock(NEW.warehouseInFk); END IF; + IF NOT (NEW.isRaid <=> OLD.isRaid) OR NOT (NEW.daysInForward <=> OLD.daysInForward) THEN + CALL travel_checkRaid(NEW.isRaid, NEW.daysInForward); + END IF; + IF NOT (NEW.awbFk <=> OLD.awbFk)THEN - SELECT COUNT(*) INTO vHasAnyInvoiceBooked + SELECT COUNT(*) INTO vHasAnyInvoiceBooked FROM travel t - JOIN entry e ON e.travelFk = t.id - JOIN invoiceIn ii ON ii.id = e.invoiceInFk + JOIN entry e ON e.travelFk = t.id + JOIN invoiceIn ii ON ii.id = e.invoiceInFk WHERE t.id = NEW.id - AND ii.isBooked; - + AND ii.isBooked; + IF vHasAnyInvoiceBooked THEN CALL util.throw('The travel has entries with booked invoices'); END IF; - END IF; - + END IF; + IF (NOT(NEW.awbFk <=> OLD.awbFk)) AND NEW.awbFk IS NOT NULL THEN CALL travel_throwAwb(NEW.id); END IF; diff --git a/db/routines/vn/views/itemEntryIn.sql b/db/routines/vn/views/itemEntryIn.sql index 6196e9396..60af585f2 100644 --- a/db/routines/vn/views/itemEntryIn.sql +++ b/db/routines/vn/views/itemEntryIn.sql @@ -6,7 +6,7 @@ AS SELECT `t`.`warehouseInFk` AS `warehouseInFk`, `b`.`itemFk` AS `itemFk`, `b`.`quantity` AS `quantity`, `t`.`isReceived` AS `isReceived`, - `t`.`daysInForward` AS `isVirtualStock`, + `t`.`isRaid` AS `isVirtualStock`, `e`.`id` AS `entryFk` FROM ( ( diff --git a/db/routines/vn/views/itemEntryOut.sql b/db/routines/vn/views/itemEntryOut.sql index f18116e61..4793ddbb8 100644 --- a/db/routines/vn/views/itemEntryOut.sql +++ b/db/routines/vn/views/itemEntryOut.sql @@ -15,5 +15,5 @@ FROM ( JOIN `vn`.`travel` `t` ON(`e`.`travelFk` = `t`.`id`) ) WHERE `e`.`isExcludedFromAvailable` = 0 - AND NOT `t`.`daysInForward` + AND NOT `t`.`isRaid` AND `b`.`quantity` <> 0 diff --git a/db/routines/vn/views/itemShelvingList.sql b/db/routines/vn/views/itemShelvingList.sql index 457d6f28a..f2cfeda58 100644 --- a/db/routines/vn/views/itemShelvingList.sql +++ b/db/routines/vn/views/itemShelvingList.sql @@ -15,7 +15,7 @@ FROM ( ( ( `vn`.`itemShelving` `ish` - JOIN `vn`.`shelving` `sh` ON(`sh`.`code` = `ish`.`shelvingFk`) + JOIN `vn`.`shelving` `sh` ON(`sh`.`id` = `ish`.`shelvingFk`) ) JOIN `vn`.`item` `i` ON(`i`.`id` = `ish`.`itemFk`) ) diff --git a/db/routines/vn/views/itemShelvingPlacementSupplyStock.sql b/db/routines/vn/views/itemShelvingPlacementSupplyStock.sql index fa1c11314..1ebb6410c 100644 --- a/db/routines/vn/views/itemShelvingPlacementSupplyStock.sql +++ b/db/routines/vn/views/itemShelvingPlacementSupplyStock.sql @@ -18,7 +18,7 @@ FROM ( ( ( `vn`.`itemShelving` `ish` - JOIN `vn`.`shelving` `sh` ON(`sh`.`code` = `ish`.`shelvingFk`) + JOIN `vn`.`shelving` `sh` ON(`sh`.`id` = `ish`.`shelvingFk`) ) LEFT JOIN `vn`.`parking` `p` ON(`p`.`id` = `sh`.`parkingFk`) ) diff --git a/db/routines/vn/views/itemShelvingSaleSum.sql b/db/routines/vn/views/itemShelvingSaleSum.sql index 9a402d6f4..60581faa9 100644 --- a/db/routines/vn/views/itemShelvingSaleSum.sql +++ b/db/routines/vn/views/itemShelvingSaleSum.sql @@ -13,7 +13,7 @@ FROM ( `vn`.`itemShelvingSale` `iss` JOIN `vn`.`itemShelving` `ish` ON(`ish`.`id` = `iss`.`itemShelvingFk`) ) - JOIN `vn`.`shelving` `sh` ON(`sh`.`code` = `ish`.`shelvingFk`) + JOIN `vn`.`shelving` `sh` ON(`sh`.`id` = `ish`.`shelvingFk`) ) JOIN `vn`.`parking` `p` ON(`p`.`id` = `sh`.`parkingFk`) ) diff --git a/db/routines/vn/views/itemShelvingStock.sql b/db/routines/vn/views/itemShelvingStock.sql index 41777eaec..725a06f88 100644 --- a/db/routines/vn/views/itemShelvingStock.sql +++ b/db/routines/vn/views/itemShelvingStock.sql @@ -21,7 +21,7 @@ FROM ( ( ( `vn`.`itemShelving` `ish` - LEFT JOIN `vn`.`shelving` `sh` ON(`sh`.`code` = `ish`.`shelvingFk`) + LEFT JOIN `vn`.`shelving` `sh` ON(`sh`.`id` = `ish`.`shelvingFk`) ) LEFT JOIN `vn`.`parking` `p` ON(`p`.`id` = `sh`.`parkingFk`) ) diff --git a/db/routines/vn/views/itemShelvingStockFull.sql b/db/routines/vn/views/itemShelvingStockFull.sql index c767823d6..c8a82685c 100644 --- a/db/routines/vn/views/itemShelvingStockFull.sql +++ b/db/routines/vn/views/itemShelvingStockFull.sql @@ -19,7 +19,7 @@ FROM ( ( ( `vn`.`itemShelving` `ish` - JOIN `vn`.`shelving` `sh` ON(`sh`.`code` = `ish`.`shelvingFk`) + JOIN `vn`.`shelving` `sh` ON(`sh`.`id` = `ish`.`shelvingFk`) ) JOIN `vn`.`parking` `p` ON(`p`.`id` = `sh`.`parkingFk`) ) diff --git a/db/routines/vn/views/lastPurchases.sql b/db/routines/vn/views/lastPurchases.sql index 9dc5ec898..3dcaf8c1d 100644 --- a/db/routines/vn/views/lastPurchases.sql +++ b/db/routines/vn/views/lastPurchases.sql @@ -31,5 +31,5 @@ FROM ( LEFT JOIN `edi`.`ekt` `ek` ON(`ek`.`id` = `b`.`ektFk`) ) WHERE `tr`.`landed` BETWEEN `util`.`yesterday`() AND `util`.`tomorrow`() - AND NOT `tr`.`daysInForward` + AND NOT `tr`.`isRaid` AND `b`.`stickers` > 0 diff --git a/db/routines/vn2008/views/entrySource.sql b/db/routines/vn2008/views/entrySource.sql index 9c0c0f6ed..732603617 100644 --- a/db/routines/vn2008/views/entrySource.sql +++ b/db/routines/vn2008/views/entrySource.sql @@ -8,6 +8,7 @@ AS SELECT `e`.`gestDocFk` AS `gestdoc_id`, `e`.`isExcludedFromAvailable` AS `Inventario`, `e`.`isConfirmed` AS `Confirmada`, `e`.`isOrdered` AS `Pedida`, + `tr`.`isRaid` AS `isRaid`, `tr`.`daysInForward` AS `daysInForward`, `e`.`evaNotes` AS `notas`, `e`.`supplierFk` AS `Id_Proveedor`, diff --git a/db/routines/vn2008/views/travel.sql b/db/routines/vn2008/views/travel.sql index 0e1f5acb2..38dfd40ea 100644 --- a/db/routines/vn2008/views/travel.sql +++ b/db/routines/vn2008/views/travel.sql @@ -18,5 +18,6 @@ AS SELECT `t`.`id` AS `id`, `t`.`totalEntries` AS `totalEntries`, `t`.`appointment` AS `appointment`, `t`.`awbFk` AS `awbFk`, + `t`.`isRaid` AS `isRaid`, `t`.`daysInForward` AS `daysInForward` FROM `vn`.`travel` `t` diff --git a/db/routines/vn2008/views/v_compres.sql b/db/routines/vn2008/views/v_compres.sql index 324e459f6..633feb471 100644 --- a/db/routines/vn2008/views/v_compres.sql +++ b/db/routines/vn2008/views/v_compres.sql @@ -86,4 +86,4 @@ FROM ( ) WHERE NOT `W_IN`.`isFeedStock` AND NOT `E`.`Inventario` - AND NOT `TR`.`daysInForward` + AND NOT `TR`.`isRaid` diff --git a/db/versions/11251-navyChrysanthemum/00-firstScript.sql b/db/versions/11251-navyChrysanthemum/00-firstScript.sql index 801405e59..7c2c69839 100644 --- a/db/versions/11251-navyChrysanthemum/00-firstScript.sql +++ b/db/versions/11251-navyChrysanthemum/00-firstScript.sql @@ -1,3 +1,2 @@ -UPDATE vn.sale - SET originalQuantity = quantity - WHERE originalQuantity IS NULL +-- Debido a que tardaba mucho en la subida a master, se ha creado una nueva versión para que el proceso no se vea afectado y se ejecute por la noche. +-- Se crea de nuevo en la versión 11344-grayBamboo diff --git a/db/versions/11312-navyAralia/00-firstScript.sql b/db/versions/11312-navyAralia/00-firstScript.sql new file mode 100644 index 000000000..452b1feed --- /dev/null +++ b/db/versions/11312-navyAralia/00-firstScript.sql @@ -0,0 +1,23 @@ +ALTER TABLE vn.workerRelatives DROP FOREIGN KEY workerRelatives_disabilityGradeFk; +ALTER TABLE vn.workerRelatives DROP FOREIGN KEY workerRelatives_workerFk; + +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES + ('WorkerRelative','updateAttributes','*','ALLOW','ROLE','hr'), + ('WorkerRelative','crud','WRITE','ALLOW','ROLE','hr'), + ('WorkerRelative','findById','*','ALLOW','ROLE','hr'), + ('WorkerRelative','find','*','ALLOW','ROLE','hr'), + ('WorkerRelative','upsert','*','ALLOW','ROLE','hr'), + ('WorkerRelative','filter','*','ALLOW','ROLE','hr'), + ('WorkerIrpf','updateAttributes','*','ALLOW','ROLE','hr'), + ('WorkerIrpf','crud','*','ALLOW','ROLE','hr'), + ('WorkerIrpf','findById','*','ALLOW','ROLE','hr'), + ('WorkerIrpf','find','*','ALLOW','ROLE','hr'), + ('WorkerIrpf','upsert','*','ALLOW','ROLE','hr'), + ('WorkerIrpf','filter','*','ALLOW','ROLE','hr'), + ('DisabilityGrade','updateAttributes','*','ALLOW','ROLE','hr'), + ('DisabilityGrade','crud','*','ALLOW','ROLE','hr'), + ('DisabilityGrade','findById','*','ALLOW','ROLE','hr'), + ('DisabilityGrade','find','*','ALLOW','ROLE','hr'), + ('DisabilityGrade','upsert','*','ALLOW','ROLE','hr'); + diff --git a/db/versions/11322-azureAspidistra/00-entryAcl.sql b/db/versions/11322-azureAspidistra/00-entryAcl.sql new file mode 100644 index 000000000..836737d4b --- /dev/null +++ b/db/versions/11322-azureAspidistra/00-entryAcl.sql @@ -0,0 +1,40 @@ +-- Eliminar registros existentes donde property = '*' +DELETE FROM `salix`.ACL WHERE model = 'entry' AND property = '*'; + +-- Insertar permisos para los métodos solicitados en el modelo Entry +INSERT INTO `salix`.ACL (model, property, accessType, permission, principalType, principalId) +VALUES + -- Permisos para administrative + ('Entry', 'upsert', 'WRITE', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'updateAttributes', 'WRITE', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'isBooked', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'findById', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'find', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'filter', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'count', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'getEntry', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'getBuys', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'findOne', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'deleteBuys', 'WRITE', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'editLatestBuys', 'WRITE', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'importBuys', 'WRITE', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'importBuysPreview', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'lastItemBuys', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'latestBuysFilter', 'READ', 'ALLOW', 'ROLE', 'administrative'), + + -- Permisos para buyer (excluyendo isBooked) + ('Entry', 'upsert', 'WRITE', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'updateAttributes', 'WRITE', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'findById', 'READ', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'find', 'READ', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'filter', 'READ', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'count', 'READ', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'getEntry', 'READ', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'getBuys', 'READ', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'findOne', 'READ', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'deleteBuys', 'WRITE', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'editLatestBuys', 'WRITE', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'importBuys', 'WRITE', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'importBuysPreview', 'READ', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'lastItemBuys', 'READ', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'latestBuysFilter', 'READ', 'ALLOW', 'ROLE', 'buyer'); diff --git a/db/versions/11324-salmonCataractarum/00-firstScript.sql b/db/versions/11324-salmonCataractarum/00-firstScript.sql new file mode 100644 index 000000000..5c17ed549 --- /dev/null +++ b/db/versions/11324-salmonCataractarum/00-firstScript.sql @@ -0,0 +1,71 @@ +CREATE TABLE IF NOT EXISTS `vn`.`itemTextureTag` ( + `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT + CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Natural y encerado'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Natural y esponjoso'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Natural y foam'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Natural y látex'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Arenosa'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Aterciopelado'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Engomado'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Flocado'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Foam'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Gasa'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Goma'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Látex'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Latón'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Mate'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Metálico'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Natural'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Natural y engomado'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Plastificado'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Plastificado y engomado'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Plastificado y rugoso'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Pluma'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Plástico'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Plástico engomado'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Poliéster'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Poliéster texturizado'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Rugoso'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Rígido'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Seminatural'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Silicona'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Suave'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela con brillo'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela con texturas'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela dura'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela engomada'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela escarchada'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela flocada'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela flocada engomada'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela foam'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela micro peach'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela plastificada'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela plástico engomado'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela poliéster'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela PVC'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela ratan'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela rigida'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela rugosa'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela rústica'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela sintética'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela y cristal'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela y foam'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela y goma'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela y látex'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela y madera'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela y plástico'); +INSERT IGNORE INTO `vn`.`itemTextureTag` (`name`) VALUES ('Tela y seco'); + +UPDATE vn.tag + SET isFree=0, + sourceTable='itemTextureTag' + WHERE name= 'Textura'; + +GRANT SELECT, UPDATE, INSERT, DELETE ON TABLE vn.itemTextureTag TO logisticAssist; diff --git a/db/versions/11330-greenMoss/00-firstScript.sql b/db/versions/11330-greenMoss/00-firstScript.sql new file mode 100644 index 000000000..127c8e40e --- /dev/null +++ b/db/versions/11330-greenMoss/00-firstScript.sql @@ -0,0 +1,16 @@ +CREATE TABLE IF NOT EXISTS vn.saySimpleCountry( + countryFk MEDIUMINT(8) UNSIGNED, + channel INT(4) COMMENT 'channel de whatsapp de saySimple', + PRIMARY KEY (countryFk), + CONSTRAINT `saySimpleCountry_FK` FOREIGN KEY (`countryFk`) REFERENCES vn.country (`id`) ON UPDATE CASCADE +); + +CREATE TABLE IF NOT EXISTS vn.saySimpleConfig( + id INT AUTO_INCREMENT PRIMARY KEY, + url VARCHAR(255) NOT NULL +); + +INSERT IGNORE INTO vn.saySimpleCountry (countryFk, channel) + VALUES (19, 1169), + (8, 1183), + (NULL, 1320); \ No newline at end of file diff --git a/db/versions/11332-tealErica/00-firstScript.sql b/db/versions/11332-tealErica/00-firstScript.sql new file mode 100644 index 000000000..6358695b2 --- /dev/null +++ b/db/versions/11332-tealErica/00-firstScript.sql @@ -0,0 +1,4 @@ +ALTER TABLE vn.travel ADD isRaid tinyint(1) DEFAULT 0 NOT NULL COMMENT 'Redada'; + +ALTER TABLE vn.travel MODIFY COLUMN daysInForward int(10) unsigned DEFAULT NULL + COMMENT 'Cuando es una redada, indica el número de días que se añadirán a la fecha de hoy para establecer el landed. NULL si no es una redada'; diff --git a/db/versions/11336-chocolateRaphis/00-firstScript.sql b/db/versions/11336-chocolateRaphis/00-firstScript.sql new file mode 100644 index 000000000..c86dc39e9 --- /dev/null +++ b/db/versions/11336-chocolateRaphis/00-firstScript.sql @@ -0,0 +1,8 @@ +DELETE FROM salix.ACL + WHERE property IN ('cmrs', 'cmr', 'downloadCmrsZip') + AND model = 'Route'; + +INSERT INTO salix.ACL (model,property,principalId) + VALUES ('Cmr','filter','production'), + ('Cmr','downloadZip','production'), + ('Cmr','print','production') \ No newline at end of file diff --git a/db/versions/11337-limeAsparagus/00-firstScript.sql b/db/versions/11337-limeAsparagus/00-firstScript.sql new file mode 100644 index 000000000..4cfedc8a8 --- /dev/null +++ b/db/versions/11337-limeAsparagus/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.productionConfig DROP COLUMN hasNewLabelMrwMethod; diff --git a/db/versions/11338-brownMonstera/00-firstScript.sql b/db/versions/11338-brownMonstera/00-firstScript.sql new file mode 100644 index 000000000..9752bb90d --- /dev/null +++ b/db/versions/11338-brownMonstera/00-firstScript.sql @@ -0,0 +1,2 @@ +-- Place your SQL code here +RENAME TABLE vn.stockBuyed__ TO vn.stockBuyed; diff --git a/db/versions/11339-goldenMastic/00-firstScript.sql b/db/versions/11339-goldenMastic/00-firstScript.sql new file mode 100644 index 000000000..f1da5798a --- /dev/null +++ b/db/versions/11339-goldenMastic/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.dua ADD comment TEXT DEFAULT NULL NULL; diff --git a/db/versions/11341-pinkSalal/00-firstScript.sql b/db/versions/11341-pinkSalal/00-firstScript.sql new file mode 100644 index 000000000..2c9e912d9 --- /dev/null +++ b/db/versions/11341-pinkSalal/00-firstScript.sql @@ -0,0 +1,5 @@ + +ALTER TABLE vn.travel ADD IF NOT EXISTS isRaid tinyint(1) DEFAULT 0 NOT NULL COMMENT 'Redada'; + +ALTER TABLE vn.travel MODIFY COLUMN daysInForward int(10) unsigned DEFAULT NULL + COMMENT 'Cuando es una redada, indica el número de días que se añadirán a la fecha de hoy para establecer el landed. NULL si no es una redada'; diff --git a/db/versions/11342-crimsonDendro/00-itemShelving.sql b/db/versions/11342-crimsonDendro/00-itemShelving.sql new file mode 100644 index 000000000..4d083bf97 --- /dev/null +++ b/db/versions/11342-crimsonDendro/00-itemShelving.sql @@ -0,0 +1,6 @@ +CREATE OR REPLACE TEMPORARY TABLE tmp.tItemShelving + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT ish.id, s.id shelvingFk + FROM vn.itemShelving ish + JOIN vn.shelving s ON s.code = ish.shelvingFk COLLATE utf8mb3_unicode_ci; diff --git a/db/versions/11342-crimsonDendro/01-itemShelving.sql b/db/versions/11342-crimsonDendro/01-itemShelving.sql new file mode 100644 index 000000000..23099ac6b --- /dev/null +++ b/db/versions/11342-crimsonDendro/01-itemShelving.sql @@ -0,0 +1,2 @@ +ALTER TABLE vn.itemShelving DROP FOREIGN KEY itemShelving_fk2, + MODIFY COLUMN shelvingFk int(11) NOT NULL; diff --git a/db/versions/11342-crimsonDendro/02-itemShelving.sql b/db/versions/11342-crimsonDendro/02-itemShelving.sql new file mode 100644 index 000000000..9d0e65d0b --- /dev/null +++ b/db/versions/11342-crimsonDendro/02-itemShelving.sql @@ -0,0 +1,3 @@ +UPDATE vn.itemShelving ish + JOIN tmp.tItemShelving tish ON tish.id = ish.id + SET ish.shelvingFk = tish.shelvingFk; \ No newline at end of file diff --git a/db/versions/11342-crimsonDendro/03-itemShelving.sql b/db/versions/11342-crimsonDendro/03-itemShelving.sql new file mode 100644 index 000000000..cb9825bfc --- /dev/null +++ b/db/versions/11342-crimsonDendro/03-itemShelving.sql @@ -0,0 +1,4 @@ +ALTER TABLE vn.itemShelving + ADD CONSTRAINT itemShelving_shelving_FK FOREIGN KEY (shelvingFk) REFERENCES vn.shelving(id) + ON DELETE RESTRICT + ON UPDATE CASCADE; diff --git a/db/versions/11342-crimsonDendro/04-itemShelvingLog.sql b/db/versions/11342-crimsonDendro/04-itemShelvingLog.sql new file mode 100644 index 000000000..1135b9d09 --- /dev/null +++ b/db/versions/11342-crimsonDendro/04-itemShelvingLog.sql @@ -0,0 +1,8 @@ +/* +CREATE OR REPLACE TEMPORARY TABLE tmp.tItemShelvingLog + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT ishl.id, s.id shelvingFk + FROM vn.itemShelvingLog ishl + JOIN vn.shelving s ON s.code = ishl.shelvingFk COLLATE utf8mb3_unicode_ci; +*/ diff --git a/db/versions/11342-crimsonDendro/05-itemShelvingLog.sql b/db/versions/11342-crimsonDendro/05-itemShelvingLog.sql new file mode 100644 index 000000000..b0e3b55cc --- /dev/null +++ b/db/versions/11342-crimsonDendro/05-itemShelvingLog.sql @@ -0,0 +1 @@ +-- ALTER TABLE vn.itemShelvingLog MODIFY COLUMN shelvingFk int(11) NOT NULL; diff --git a/db/versions/11342-crimsonDendro/06-itemShelvingLog.sql b/db/versions/11342-crimsonDendro/06-itemShelvingLog.sql new file mode 100644 index 000000000..f97f61e42 --- /dev/null +++ b/db/versions/11342-crimsonDendro/06-itemShelvingLog.sql @@ -0,0 +1,7 @@ +/* +UPDATE vn.itemShelvingLog ishl + JOIN tmp.tItemShelvingLog tishl ON tishl.id = ishl.id + SET ishl.shelvingFk = tishl.shelvingFk; + +DROP TEMPORARY TABLE tmp.tItemShelvingLog; +*/ \ No newline at end of file diff --git a/db/versions/11343-silverAsparagus/00-firstScript.sql b/db/versions/11343-silverAsparagus/00-firstScript.sql new file mode 100644 index 000000000..bcee42eea --- /dev/null +++ b/db/versions/11343-silverAsparagus/00-firstScript.sql @@ -0,0 +1,9 @@ +INSERT INTO salix.ACL (model, property, accessType, principalId) + VALUES ('Collection', 'create', 'WRITE', 'productionBoss'), + ('Collection', 'upsert', 'WRITE', 'productionBoss'), + ('Collection', 'replaceById', 'WRITE', 'productionBoss'), + ('Collection', 'updateAll', 'WRITE', 'productionBoss'), + ('Collection', 'updateAttributes', 'WRITE', 'productionBoss'), + ('Collection', 'deleteById', 'WRITE', 'productionBoss'), + ('Collection', 'destroyAll', 'WRITE', 'productionBoss'), + ('Collection', 'destroyById', 'WRITE', 'productionBoss'); diff --git a/db/versions/11344-grayBamboo/00-firstScript.sql b/db/versions/11344-grayBamboo/00-firstScript.sql new file mode 100644 index 000000000..1fbd2a0d8 --- /dev/null +++ b/db/versions/11344-grayBamboo/00-firstScript.sql @@ -0,0 +1,3 @@ +UPDATE vn.sale + SET originalQuantity = quantity + WHERE originalQuantity IS NULL \ No newline at end of file diff --git a/db/versions/11251-navyChrysanthemum/01-firstScript.sql b/db/versions/11344-grayBamboo/01-firstScript.sql similarity index 100% rename from db/versions/11251-navyChrysanthemum/01-firstScript.sql rename to db/versions/11344-grayBamboo/01-firstScript.sql diff --git a/db/versions/11345-salmonEucalyptus/00-firstScript.sql b/db/versions/11345-salmonEucalyptus/00-firstScript.sql new file mode 100644 index 000000000..ecbc36c40 --- /dev/null +++ b/db/versions/11345-salmonEucalyptus/00-firstScript.sql @@ -0,0 +1,2 @@ +ALTER TABLE account.user CHANGE recoverPass recoverPass__ tinyint(3) unsigned NOT NULL DEFAULT 1 COMMENT '@deprecated 2024-11-13'; +ALTER TABLE account.user CHANGE sync sync__ tinyint(4) NOT NULL DEFAULT 0 COMMENT '@deprecated 2024-11-13'; \ No newline at end of file diff --git a/db/versions/11346-yellowPhormium/00-address.sql b/db/versions/11346-yellowPhormium/00-address.sql new file mode 100644 index 000000000..f91d0ae9f --- /dev/null +++ b/db/versions/11346-yellowPhormium/00-address.sql @@ -0,0 +1,23 @@ +ALTER TABLE vn.address + ADD geoFk int(11) DEFAULT NULL NULL AFTER isLogifloraAllowed, + ADD CONSTRAINT address_zoneGeo_FK FOREIGN KEY (geoFk) + REFERENCES vn.zoneGeo(id) ON DELETE RESTRICT ON UPDATE CASCADE; + +CREATE OR REPLACE TEMPORARY TABLE tmp.tAddressGeo + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT a.id, p.geoFk + FROM vn.address a + JOIN vn.town t ON t.provinceFk = a.provinceFk + JOIN vn.postCode p ON p.townFk = t.id + AND (p.code = a.postalCode OR a.postalCode IS NULL) + JOIN vn.zoneGeo zg ON zg.id = p.geoFk + GROUP BY a.id + ORDER BY (a.city SOUNDS LIKE t.`name`) DESC, + (p.code = a.postalCode) DESC; + +UPDATE vn.address a + JOIN tmp.tAddressGeo tag ON tag.id = a.id + SET a.geoFk = tag.geoFk; + +DROP TEMPORARY TABLE tmp.tAddressGeo; diff --git a/db/versions/11346-yellowPhormium/01-client.sql b/db/versions/11346-yellowPhormium/01-client.sql new file mode 100644 index 000000000..cb6fe41e8 --- /dev/null +++ b/db/versions/11346-yellowPhormium/01-client.sql @@ -0,0 +1,26 @@ +ALTER TABLE vn.client + CHANGE hasDailyInvoice hasDailyInvoice tinyint(1) DEFAULT 0 NOT NULL + COMMENT 'Indica si el cliente requiere facturación diaria por defecto se copiará lo que tenga country.hasDailyInvoice' + AFTER recommendedCredit, + ADD geoFk int(11) DEFAULT NULL NULL AFTER hasDailyInvoice, + ADD CONSTRAINT client_zoneGeo_FK FOREIGN KEY (geoFk) + REFERENCES vn.zoneGeo(id) ON DELETE RESTRICT ON UPDATE CASCADE; + +CREATE OR REPLACE TEMPORARY TABLE tmp.tClientGeo + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT c.id, p.geoFk + FROM vn.client c + JOIN vn.town t ON t.provinceFk = c.provinceFk + JOIN vn.postCode p ON p.townFk = t.id + AND (p.code = c.postcode OR c.postcode IS NULL) + JOIN vn.zoneGeo zg ON zg.id = p.geoFk + GROUP BY c.id + ORDER BY (c.city SOUNDS LIKE t.`name`) DESC, + (p.code = c.postcode) DESC; + +UPDATE vn.client c + JOIN tmp.tClientGeo tcg ON tcg.id = c.id + SET c.geoFk = tcg.geoFk; + +DROP TEMPORARY TABLE tmp.tClientGeo; diff --git a/db/versions/11346-yellowPhormium/02-supplier.sql b/db/versions/11346-yellowPhormium/02-supplier.sql new file mode 100644 index 000000000..4e866525e --- /dev/null +++ b/db/versions/11346-yellowPhormium/02-supplier.sql @@ -0,0 +1,27 @@ +ALTER TABLE vn.supplier + CHANGE companySize companySize enum('small','medium','big') CHARACTER SET utf8mb3 + COLLATE utf8mb3_general_ci DEFAULT NULL NULL AFTER stamp, + ADD geoFk int(11) DEFAULT NULL NULL AFTER companySize, + ADD CONSTRAINT supplier_zoneGeo_FK FOREIGN KEY (geoFk) + REFERENCES vn.zoneGeo(id) ON DELETE RESTRICT ON UPDATE CASCADE; + +CREATE OR REPLACE TEMPORARY TABLE tmp.tSupplierGeo + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT s.id, p.geoFk + FROM vn.supplier s + JOIN vn.town t ON t.provinceFk = s.provinceFk + JOIN vn.postCode p ON p.townFk = t.id + AND (p.code = s.postCode OR s.postCode IS NULL) + LEFT JOIN vn.supplierAddress sad ON sad.supplierFk = s.id + JOIN vn.zoneGeo zg ON zg.id = p.geoFk + GROUP BY s.id + ORDER BY (s.city SOUNDS LIKE t.`name`) DESC, + (p.code = s.postCode) DESC, + (p.code = sad.postalCode) DESC; + +UPDATE vn.supplier s + JOIN tmp.tSupplierGeo tsg ON tsg.id = s.id + SET s.geoFk = tsg.geoFk; + +DROP TEMPORARY TABLE tmp.tSupplierGeo; diff --git a/db/versions/11347-redErica/00-firstScript.sql b/db/versions/11347-redErica/00-firstScript.sql new file mode 100644 index 000000000..5da1d6096 --- /dev/null +++ b/db/versions/11347-redErica/00-firstScript.sql @@ -0,0 +1,9 @@ +DROP TABLE IF EXISTS vn.saySimpleConfig; + +CREATE TABLE vn.saySimpleConfig( + id INT AUTO_INCREMENT PRIMARY KEY, + url VARCHAR(255) NOT NULL, + defaultChannel VARCHAR(128) +); + +ALTER TABLE vn.saySimpleCountry MODIFY COLUMN channel VARCHAR(128); \ No newline at end of file diff --git a/db/versions/11348-bronzeCamellia/00-firstScript.sql b/db/versions/11348-bronzeCamellia/00-firstScript.sql new file mode 100644 index 000000000..fa466f1a4 --- /dev/null +++ b/db/versions/11348-bronzeCamellia/00-firstScript.sql @@ -0,0 +1,2 @@ +ALTER TABLE vn.clientObservation MODIFY COLUMN observationTypeFk tinyint(3) unsigned DEFAULT 4 NOT NULL; +UPDATE vn.clientObservation SET observationTypeFk=4 WHERE observationTypeFk=0; diff --git a/db/versions/11349-azureBamboo/00-firstScript.sql b/db/versions/11349-azureBamboo/00-firstScript.sql new file mode 100644 index 000000000..09c919b79 --- /dev/null +++ b/db/versions/11349-azureBamboo/00-firstScript.sql @@ -0,0 +1,7 @@ + + +UPDATE salix.ACL + SET principalId = 'deliveryAssistant' +WHERE model = 'Ticket' + AND property = 'updateAttributes' + AND principalId = "delivery"; diff --git a/db/versions/11350-silverArborvitae/00-firstScript.sql b/db/versions/11350-silverArborvitae/00-firstScript.sql new file mode 100644 index 000000000..b5e87133e --- /dev/null +++ b/db/versions/11350-silverArborvitae/00-firstScript.sql @@ -0,0 +1,2 @@ +ALTER TABLE vn.shelvingLog + MODIFY COLUMN changedModel enum('Shelving', 'ItemShelving') CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT 'Shelving' NOT NULL; diff --git a/db/versions/11351-bronzeMedeola/00-firstScript.sql b/db/versions/11351-bronzeMedeola/00-firstScript.sql new file mode 100644 index 000000000..c94447a89 --- /dev/null +++ b/db/versions/11351-bronzeMedeola/00-firstScript.sql @@ -0,0 +1,2 @@ + +ALTER TABLE vn.itemConfig ADD defaultPackingTypeFk VARCHAR(1) DEFAULT 'H' NULL; diff --git a/db/versions/11353-wheatCymbidium/00-firstScript.sql b/db/versions/11353-wheatCymbidium/00-firstScript.sql new file mode 100644 index 000000000..557ffab9e --- /dev/null +++ b/db/versions/11353-wheatCymbidium/00-firstScript.sql @@ -0,0 +1,15 @@ + + +USE vn; + +INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) +VALUES('RouteAction', 'find', 'READ', 'ALLOW', 'ROLE', 'delivery'); + +INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) +VALUES('RouteComplement', 'find', 'READ', 'ALLOW', 'ROLE', 'delivery'); + +INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) +VALUES('RouteComplement', 'create', 'WRITE', 'ALLOW', 'ROLE', 'delivery'); + +INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) +VALUES('RouteComplement', 'deleteById', 'WRITE', 'ALLOW', 'ROLE', 'delivery'); \ No newline at end of file diff --git a/db/versions/11354-aquaMastic/00-firstScript.sql b/db/versions/11354-aquaMastic/00-firstScript.sql new file mode 100644 index 000000000..dda3f4752 --- /dev/null +++ b/db/versions/11354-aquaMastic/00-firstScript.sql @@ -0,0 +1,2 @@ +RENAME TABLE vn.workerTimeControlParams TO vn.workerTimeControlParams__; +ALTER TABLE vn.workerTimeControlParams__ COMMENT='@deprecated 2024-11-19'; \ No newline at end of file diff --git a/db/versions/11355-pinkMedeola/00-firstScript.sql b/db/versions/11355-pinkMedeola/00-firstScript.sql new file mode 100644 index 000000000..fc89b386c --- /dev/null +++ b/db/versions/11355-pinkMedeola/00-firstScript.sql @@ -0,0 +1,3 @@ +-- Place your SQL code here +INSERT IGNORE INTO vn.saySimpleConfig (url, defaultChannel) + VALUES ('https://verdnatura.saysimple.io/start-conversation', 1320); \ No newline at end of file diff --git a/db/versions/11357-whiteGerbera/00-firstScript.sql b/db/versions/11357-whiteGerbera/00-firstScript.sql new file mode 100644 index 000000000..c10ec4d26 --- /dev/null +++ b/db/versions/11357-whiteGerbera/00-firstScript.sql @@ -0,0 +1,4 @@ +ALTER TABLE vn.travel ADD IF NOT EXISTS isRaid tinyint(1) DEFAULT 0 NOT NULL COMMENT 'Redada'; + +ALTER TABLE vn.travel MODIFY COLUMN daysInForward int(10) unsigned DEFAULT NULL + COMMENT 'Cuando es una redada, indica el número de días que se añadirán a la fecha de hoy para establecer el landed. NULL si no es una redada'; diff --git a/e2e/paths/04-item/01_summary.spec.js b/e2e/paths/04-item/01_summary.spec.js deleted file mode 100644 index 51195be48..000000000 --- a/e2e/paths/04-item/01_summary.spec.js +++ /dev/null @@ -1,133 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Item summary path', () => { - let browser; - let page; - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('employee', 'item'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should search for an item', async() => { - await page.doSearch('Ranged weapon'); - const resultsCount = await page.countElement(selectors.itemsIndex.searchResult); - - await page.waitForTextInElement(selectors.itemsIndex.firstSearchResult, 'Ranged weapon'); - await page.waitToClick(selectors.itemsIndex.firstResultPreviewButton); - const isVisible = await page.isVisible(selectors.itemSummary.basicData); - - expect(resultsCount).toBe(4); - expect(isVisible).toBeTruthy(); - }); - - it(`should check the item summary preview shows fields from basic data`, async() => { - await page.waitForTextInElement(selectors.itemSummary.basicData, 'Ranged weapon longbow 200cm'); - const result = await page.waitToGetProperty(selectors.itemSummary.basicData, 'innerText'); - - expect(result).toContain('Ranged weapon longbow 200cm'); - }); - - it(`should check the item summary preview shows fields from tags`, async() => { - await page.waitForTextInElement(selectors.itemSummary.tags, 'Brown'); - const result = await page.waitToGetProperty(selectors.itemSummary.tags, 'innerText'); - - expect(result).toContain('Brown'); - }); - - 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'); - - expect(result).toContain('Abelia'); - }); - - it(`should check the item summary preview shows fields from barcode`, async() => { - await page.waitForTextInElement(selectors.itemSummary.barcode, '1'); - const result = await page.waitToGetProperty(selectors.itemSummary.barcode, 'innerText'); - - expect(result).toContain('1'); - }); - - it(`should close the summary popup`, async() => { - await page.closePopup(); - await page.waitForSelector(selectors.itemSummary.basicData, {hidden: true}); - }); - - it('should search for other item', async() => { - await page.doSearch('Melee Reinforced'); - const resultsCount = await page.countElement(selectors.itemsIndex.searchResult); - - await page.waitToClick(selectors.itemsIndex.firstResultPreviewButton); - await page.waitForSelector(selectors.itemSummary.basicData, {visible: true}); - - expect(resultsCount).toBe(3); - }); - - it(`should now check the item summary preview shows fields from basic data`, async() => { - await page.waitForTextInElement(selectors.itemSummary.basicData, 'Melee Reinforced weapon combat fist 15cm'); - const result = await page.waitToGetProperty(selectors.itemSummary.basicData, 'innerText'); - - expect(result).toContain('Melee Reinforced weapon combat fist 15cm'); - }); - - it(`should now check the item summary preview shows fields from tags`, async() => { - await page.waitForTextInElement(selectors.itemSummary.tags, 'Silver'); - const result = await page.waitToGetProperty(selectors.itemSummary.tags, 'innerText'); - - expect(result).toContain('Silver'); - }); - - it(`should now check the item summary preview shows fields from botanical`, async() => { - await page.waitForTextInElement(selectors.itemSummary.botanical, '-'); - const result = await page.waitToGetProperty(selectors.itemSummary.botanical, 'innerText'); - - expect(result).toContain('-'); - }); - - it(`should now close the summary popup`, async() => { - await page.closePopup(); - await page.waitForSelector(selectors.itemSummary.basicData, {hidden: true}); - }); - - it(`should navigate to one of the items detailed section`, async() => { - await page.accessToSearchResult('Melee weapon combat fist 15cm'); - await page.waitForState('item.card.summary'); - }); - - it(`should check the descritor edit button is not visible for employee`, async() => { - const visibleButton = await page.isVisible(selectors.itemDescriptor.editButton); - - expect(visibleButton).toBeFalsy(); - }); - - it(`should check the item summary shows fields from basic data section`, async() => { - await page.waitForTextInElement(selectors.itemSummary.basicData, 'Melee weapon combat fist 15cm'); - const result = await page.waitToGetProperty(selectors.itemSummary.basicData, 'innerText'); - - expect(result).toContain('Melee weapon combat fist 15cm'); - }); - - it(`should check the item summary shows fields from tags section`, async() => { - const result = await page.waitToGetProperty(selectors.itemSummary.tags, 'innerText'); - - expect(result).toContain('Silver'); - }); - - it(`should check the item summary shows fields from botanical section`, async() => { - const result = await page.waitToGetProperty(selectors.itemSummary.botanical, 'innerText'); - - expect(result).toContain('procera'); - }); - - it(`should check the item summary shows fields from barcodes section`, async() => { - const result = await page.waitToGetProperty(selectors.itemSummary.barcode, 'innerText'); - - expect(result).toContain('4'); - }); -}); diff --git a/e2e/paths/04-item/02_basic_data.spec.js b/e2e/paths/04-item/02_basic_data.spec.js deleted file mode 100644 index 3bad18303..000000000 --- a/e2e/paths/04-item/02_basic_data.spec.js +++ /dev/null @@ -1,64 +0,0 @@ -import getBrowser from '../../helpers/puppeteer'; - -const $ = { - form: 'vn-item-basic-data form', - intrastatForm: '.vn-dialog.shown form', - newIntrastatButton: 'vn-item-basic-data vn-icon-button[vn-tooltip="New intrastat"] > button' -}; - -describe('Item Edit basic data path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyer', 'item'); - await page.accessToSearchResult('Melee weapon combat fist 15cm'); - }); - - beforeEach(async() => { - await page.accessToSection('item.card.basicData'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it(`should edit the item basic data and confirm the item data was edited`, async() => { - const values = { - type: 'Anthurium', - intrastat: 'Coral y materiales similares', - relevancy: 1, - generic: 'Pallet', - isActive: false, - priceInKg: true, - isFragile: true, - packingOut: 5 - }; - - const message = await page.sendForm($.form, values); - await page.reloadSection('item.card.basicData'); - const formValues = await page.fetchForm($.form, Object.keys(values)); - - expect(message.isSuccess).toBeTrue(); - expect(formValues).toEqual(values); - }); - - it(`should create a new intrastat and save it`, async() => { - await page.click($.newIntrastatButton); - await page.waitForSelector($.intrastatForm); - await page.fillForm($.intrastatForm, { - id: '588420239', - description: 'Tropical Flowers' - }); - await page.respondToDialog('accept'); - - const message = await page.sendForm($.form); - await page.reloadSection('item.card.basicData'); - const formValues = await page.fetchForm($.form, ['intrastat']); - - expect(message.isSuccess).toBeTrue(); - expect(formValues).toEqual({intrastat: 'Tropical Flowers'}); - }); -}); diff --git a/e2e/paths/04-item/03_tax.spec.js b/e2e/paths/04-item/03_tax.spec.js deleted file mode 100644 index 6013094e9..000000000 --- a/e2e/paths/04-item/03_tax.spec.js +++ /dev/null @@ -1,48 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Item edit tax path', () => { - let browser; - let page; - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyer', 'item'); - await page.accessToSearchResult('Ranged weapon longbow 200cm'); - await page.accessToSection('item.card.tax'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it(`should add the item tax to all countries`, async() => { - await page.autocompleteSearch(selectors.itemTax.firstClass, 'General VAT'); - await page.autocompleteSearch(selectors.itemTax.secondClass, 'General VAT'); - await page.waitToClick(selectors.itemTax.submitTaxButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it(`should confirm the first item tax class was edited`, async() => { - await page.reloadSection('item.card.tax'); - const firstVatType = await page.waitToGetProperty(selectors.itemTax.firstClass, 'value'); - - expect(firstVatType).toEqual('General VAT'); - }); - - it(`should confirm the second item tax class was edited`, async() => { - const secondVatType = await page - .waitToGetProperty(selectors.itemTax.secondClass, 'value'); - - expect(secondVatType).toEqual('General VAT'); - }); - - it(`should edit the first class without saving the form`, async() => { - await page.autocompleteSearch(selectors.itemTax.firstClass, 'Reduced VAT'); - const firstVatType = await page.waitToGetProperty(selectors.itemTax.firstClass, 'value'); - - expect(firstVatType).toEqual('Reduced VAT'); - }); -}); diff --git a/e2e/paths/04-item/04_tags.spec.js b/e2e/paths/04-item/04_tags.spec.js deleted file mode 100644 index f13cf9aa4..000000000 --- a/e2e/paths/04-item/04_tags.spec.js +++ /dev/null @@ -1,79 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Item create tags path', () => { - let browser; - let page; - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyer', 'item'); - await page.accessToSearchResult('Ranged weapon longbow 200cm'); - await page.accessToSection('item.card.tags'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should create a new tag and delete a former one', async() => { - await page.waitToClick(selectors.itemTags.fourthRemoveTagButton); - await page.waitToClick(selectors.itemTags.addItemTagButton); - await page.autocompleteSearch(selectors.itemTags.seventhTag, 'Ancho de la base'); - await page.write(selectors.itemTags.seventhValue, '50'); - await page.clearInput(selectors.itemTags.seventhRelevancy); - await page.write(selectors.itemTags.seventhRelevancy, '4'); - await page.waitToClick(selectors.itemTags.submitItemTagsButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should confirm the fourth row data is the expected one', async() => { - await page.reloadSection('item.card.tags'); - await page.waitForSelector('vn-item-tags'); - let result = await page.waitToGetProperty(selectors.itemTags.fourthTag, 'value'); - - expect(result).toEqual('Ancho de la base'); - - result = await page - .waitToGetProperty(selectors.itemTags.fourthValue, 'value'); - - expect(result).toEqual('50'); - - result = await page - .waitToGetProperty(selectors.itemTags.fourthRelevancy, 'value'); - - expect(result).toEqual('4'); - }); - - it('should confirm the fifth row data is the expected one', async() => { - let tag = await page - .waitToGetProperty(selectors.itemTags.fifthTag, 'value'); - - let value = await page - .waitToGetProperty(selectors.itemTags.fifthValue, 'value'); - - let relevancy = await page - .waitToGetProperty(selectors.itemTags.fifthRelevancy, 'value'); - - expect(tag).toEqual('Color'); - expect(value).toEqual('Brown'); - expect(relevancy).toEqual('5'); - }); - - it('should confirm the sixth row data is the expected one', async() => { - let tag = await page - .waitToGetProperty(selectors.itemTags.sixthTag, 'value'); - - let value = await page - .waitToGetProperty(selectors.itemTags.sixthValue, 'value'); - - let relevancy = await page - .waitToGetProperty(selectors.itemTags.sixthRelevancy, 'value'); - - expect(tag).toEqual('Categoria'); - expect(value).toEqual('+1 precission'); - expect(relevancy).toEqual('6'); - }); -}); diff --git a/e2e/paths/04-item/05_botanical.spec.js b/e2e/paths/04-item/05_botanical.spec.js deleted file mode 100644 index 1671cc5d2..000000000 --- a/e2e/paths/04-item/05_botanical.spec.js +++ /dev/null @@ -1,66 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Item Create botanical path', () => { - let browser; - let page; - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyer', 'item'); - await page.accessToSearchResult('Ranged weapon pistol 9mm'); - await page.accessToSection('item.card.botanical'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it(`should create a new botanical for the item`, async() => { - await page.autocompleteSearch(selectors.itemBotanical.genus, 'Abelia'); - await page.autocompleteSearch(selectors.itemBotanical.species, 'dealbata'); - await page.waitToClick(selectors.itemBotanical.submitBotanicalButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it(`should confirm the Genus for the item was created`, async() => { - await page.waitForTextInField(selectors.itemBotanical.genus, 'Abelia'); - const result = await page - .waitToGetProperty(selectors.itemBotanical.genus, 'value'); - - expect(result).toEqual('Abelia'); - }); - - it(`should confirm the Species for the item was created`, async() => { - const result = await page - .waitToGetProperty(selectors.itemBotanical.species, 'value'); - - expect(result).toEqual('dealbata'); - }); - - it(`should edit botanical for the item`, async() => { - await page.autocompleteSearch(selectors.itemBotanical.genus, 'Abies'); - await page.autocompleteSearch(selectors.itemBotanical.species, 'decurrens'); - await page.waitToClick(selectors.itemBotanical.submitBotanicalButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it(`should confirm the Genus for the item was edited`, async() => { - await page.waitForTextInField(selectors.itemBotanical.genus, 'Abies'); - const result = await page - .waitToGetProperty(selectors.itemBotanical.genus, 'value'); - - expect(result).toEqual('Abies'); - }); - - it(`should confirm the Species for the item was edited`, async() => { - const result = await page - .waitToGetProperty(selectors.itemBotanical.species, 'value'); - - expect(result).toEqual('decurrens'); - }); -}); diff --git a/e2e/paths/04-item/06_barcode.spec.js b/e2e/paths/04-item/06_barcode.spec.js deleted file mode 100644 index 36c9c39ae..000000000 --- a/e2e/paths/04-item/06_barcode.spec.js +++ /dev/null @@ -1,37 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Item Create barcodes path', () => { - let browser; - let page; - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyer', 'item'); - await page.accessToSearchResult('Ranged weapon longbow 200cm'); - await page.accessToSection('item.card.itemBarcode'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it(`should click create a new code and delete a former one`, async() => { - await page.waitToClick(selectors.itemBarcodes.firstCodeRemoveButton); - await page.waitToClick(selectors.itemBarcodes.addBarcodeButton); - await page.write(selectors.itemBarcodes.thirdCode, '5'); - await page.waitToClick(selectors.itemBarcodes.submitBarcodesButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it(`should confirm the barcode 5 is created and it is now the third barcode as the first was deleted`, async() => { - await page.reloadSection('item.card.itemBarcode'); - await page.waitForTextInField(selectors.itemBarcodes.thirdCode, '5'); - const result = await page - .waitToGetProperty(selectors.itemBarcodes.thirdCode, 'value'); - - expect(result).toEqual('5'); - }); -}); diff --git a/e2e/paths/04-item/07_create.spec.js b/e2e/paths/04-item/07_create.spec.js deleted file mode 100644 index c20be9ebc..000000000 --- a/e2e/paths/04-item/07_create.spec.js +++ /dev/null @@ -1,65 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -const $ = { - form: 'vn-item-create form' -}; - -describe('Item Create', () => { - let browser; - let page; - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyer', 'item'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should access to the create item view by clicking the create floating button', async() => { - await page.waitToClick(selectors.itemsIndex.createItemButton); - await page.waitForState('item.create'); - }); - - it('should return to the item index by clickig the cancel button', async() => { - await page.waitToClick(selectors.itemCreateView.cancelButton); - await page.waitForState('item.index'); - }); - - it('should now access to the create item view by clicking the create floating button', async() => { - await page.waitToClick(selectors.itemsIndex.createItemButton); - await page.waitForState('item.create'); - }); - - it('should throw an error when insert an invalid priority', async() => { - const values = { - name: 'Infinity Gauntlet', - type: 'Crisantemo', - intrastat: 'Coral y materiales similares', - origin: 'Holand', - priority: null - }; - const message = await page.sendForm($.form, values); - - expect(message.text).toContain('Valid priorities'); - }); - - it('should create the Infinity Gauntlet item', async() => { - const values = { - name: 'Infinity Gauntlet', - type: 'Crisantemo', - intrastat: 'Coral y materiales similares', - origin: 'Holand', - priority: '2' - }; - - await page.fillForm($.form, values); - const formValues = await page.fetchForm($.form, Object.keys(values)); - const message = await page.sendForm($.form); - - expect(message.isSuccess).toBeTrue(); - expect(formValues).toEqual(values); - }); -}); diff --git a/e2e/paths/04-item/08_regularize.spec.js b/e2e/paths/04-item/08_regularize.spec.js deleted file mode 100644 index 9b3074776..000000000 --- a/e2e/paths/04-item/08_regularize.spec.js +++ /dev/null @@ -1,141 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Item regularize path', () => { - let browser; - let page; - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('employee', 'item'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should edit the user local warehouse', async() => { - await page.waitForSpinnerLoad(); - await page.waitToClick(selectors.globalItems.userMenuButton); - await page.autocompleteSearch(selectors.globalItems.userLocalWarehouse, 'Warehouse Four'); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should check the local settings were saved', async() => { - const userLocalWarehouse = await page - .waitToGetProperty(selectors.globalItems.userLocalWarehouse, 'value'); - - await page.closePopup(); - - expect(userLocalWarehouse).toContain('Warehouse Four'); - }); - - it('should search for a specific item', async() => { - await page.accessToSearchResult('Ranged weapon pistol 9mm'); - await page.waitForState('item.card.summary'); - }); - - it('should open the regularize dialog and check the warehouse matches the local user settings', async() => { - await page.waitToClick(selectors.itemDescriptor.moreMenu); - await page.waitToClick(selectors.itemDescriptor.moreMenuRegularizeButton); - const result = await page.waitToGetProperty(selectors.itemDescriptor.regularizeWarehouse, 'value'); - - expect(result).toEqual('Warehouse Four'); - }); - - it('should regularize the item', async() => { - await page.write(selectors.itemDescriptor.regularizeQuantity, '100'); - await page.autocompleteSearch(selectors.itemDescriptor.regularizeWarehouse, 'Warehouse One'); - await page.waitToClick(selectors.itemDescriptor.regularizeSaveButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should click on the Tickets button of the top bar menu', async() => { - await page.waitToClick(selectors.globalItems.applicationsMenuButton); - await page.waitForSelector(selectors.globalItems.applicationsMenuVisible); - await Promise.all([ - page.waitForNavigation({waitUntil: ['load', 'networkidle0', 'domcontentloaded']}), - page.waitToClick(selectors.globalItems.ticketsButton) - ]); - await page.waitForState('ticket.index'); - }); - - it('should clear the user local settings now', async() => { - await page.waitToClick(selectors.globalItems.userMenuButton); - await page.waitForContentLoaded(); - await page.clearInput(selectors.globalItems.userConfigFirstAutocomplete); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should search for the ticket with alias missing', async() => { - await page.keyboard.press('Escape'); - await page.accessToSearchResult('missing'); - await page.waitForState('ticket.card.summary'); - }); - - it(`should check the ticket sale quantity is showing a negative value`, async() => { - await page.waitForTextInElement(selectors.ticketSummary.firstSaleQuantity, '-100'); - const result = await page - .waitToGetProperty(selectors.ticketSummary.firstSaleQuantity, 'innerText'); - - expect(result).toContain('-100'); - }); - - it(`should check the ticket sale discount is 100%`, async() => { - const result = await page - .waitToGetProperty(selectors.ticketSummary.firstSaleDiscount, 'innerText'); - - expect(result).toContain('100 %'); - }); - - it('should now click on the Items button of the top bar menu', async() => { - await page.waitToClick(selectors.globalItems.applicationsMenuButton); - await page.waitForSelector(selectors.globalItems.applicationsMenuVisible); - await page.waitToClick(selectors.globalItems.itemsButton); - await page.waitForState('item.index'); - }); - - it('should search for the item once again', async() => { - await page.accessToSearchResult('Ranged weapon pistol 9mm'); - await page.waitForState('item.card.summary'); - }); - - it('should regularize the item once more', async() => { - await page.waitToClick(selectors.itemDescriptor.moreMenu); - await page.waitToClick(selectors.itemDescriptor.moreMenuRegularizeButton); - await page.write(selectors.itemDescriptor.regularizeQuantity, '100'); - await page.autocompleteSearch(selectors.itemDescriptor.regularizeWarehouse, 'Warehouse One'); - await page.waitToClick(selectors.itemDescriptor.regularizeSaveButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should again click on the Tickets button of the top bar menu', async() => { - await page.waitToClick(selectors.globalItems.applicationsMenuButton); - await page.waitForSelector(selectors.globalItems.applicationsMenuVisible); - await Promise.all([ - page.waitForNavigation({waitUntil: ['load', 'networkidle0', 'domcontentloaded']}), - page.waitToClick(selectors.globalItems.ticketsButton) - ]); - await page.waitForState('ticket.index'); - }); - - it('should search for the ticket missing once again', async() => { - await page.accessToSearchResult('Missing'); - await page.waitForState('ticket.card.summary'); - }); - - it(`should check the ticket contains now two sales`, async() => { - await page.waitForTextInElement(selectors.ticketSummary.firstSaleQuantity, '-100'); - const result = await page.countElement(selectors.ticketSummary.sale); - - expect(result).toEqual(2); - }); -}); diff --git a/e2e/paths/04-item/09_index.spec.js b/e2e/paths/04-item/09_index.spec.js deleted file mode 100644 index 6e0a4bd5c..000000000 --- a/e2e/paths/04-item/09_index.spec.js +++ /dev/null @@ -1,84 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Item index path', () => { - let browser; - let page; - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('salesPerson', 'item'); - await page.waitToClick(selectors.globalItems.searchButton); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should click on the fields to show button to open the list of columns to show', async() => { - await page.waitToClick(selectors.itemsIndex.shownColumns); - const visible = await page.isVisible(selectors.itemsIndex.shownColumnsList); - - expect(visible).toBeTruthy(); - }); - - it('should unmark all checkboxes except the first and the last ones', async() => { - await page.waitToClick(selectors.itemsIndex.idCheckbox); - await page.waitToClick(selectors.itemsIndex.stemsCheckbox); - await page.waitToClick(selectors.itemsIndex.sizeCheckbox); - await page.waitToClick(selectors.itemsIndex.typeCheckbox); - await page.waitToClick(selectors.itemsIndex.categoryCheckbox); - await page.waitToClick(selectors.itemsIndex.intrastadCheckbox); - await page.waitToClick(selectors.itemsIndex.originCheckbox); - await page.waitToClick(selectors.itemsIndex.buyerCheckbox); - await page.waitToClick(selectors.itemsIndex.weightByPieceCheckbox); - await page.waitToClick(selectors.itemsIndex.saveFieldsButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should navigate forth and back to see the images column is still visible', async() => { - await page.closePopup(); - await page.waitToClick(selectors.itemsIndex.firstSearchResult); - await page.waitToClick(selectors.itemDescriptor.goBackToModuleIndexButton); - await page.waitToClick(selectors.globalItems.searchButton); - await page.waitForSelector(selectors.itemsIndex.searchResult); - await page.waitImgLoad(selectors.itemsIndex.firstItemImage); - const imageVisible = await page.isVisible(selectors.itemsIndex.firstItemImageTd); - - expect(imageVisible).toBeTruthy(); - }); - - it('should check the ids column is not visible', async() => { - await page.waitForSelector(selectors.itemsIndex.firstItemId, {hidden: true}); - }); - - it('should mark all unchecked boxes to leave the index as it was', async() => { - await page.waitToClick(selectors.itemsIndex.shownColumns); - await page.waitToClick(selectors.itemsIndex.idCheckbox); - await page.waitToClick(selectors.itemsIndex.stemsCheckbox); - await page.waitToClick(selectors.itemsIndex.sizeCheckbox); - await page.waitToClick(selectors.itemsIndex.typeCheckbox); - await page.waitToClick(selectors.itemsIndex.categoryCheckbox); - await page.waitToClick(selectors.itemsIndex.intrastadCheckbox); - await page.waitToClick(selectors.itemsIndex.originCheckbox); - await page.waitToClick(selectors.itemsIndex.buyerCheckbox); - await page.waitToClick(selectors.itemsIndex.weightByPieceCheckbox); - await page.waitToClick(selectors.itemsIndex.saveFieldsButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should now navigate forth and back to see the ids column is now visible', async() => { - await page.closePopup(); - await page.waitToClick(selectors.itemsIndex.firstSearchResult); - await page.waitToClick(selectors.itemDescriptor.goBackToModuleIndexButton); - await page.waitToClick(selectors.globalItems.searchButton); - await page.waitForSelector(selectors.itemsIndex.searchResult); - const idVisible = await page.isVisible(selectors.itemsIndex.firstItemId); - - expect(idVisible).toBeTruthy(); - }); -}); diff --git a/e2e/paths/04-item/10_item_log.spec.js b/e2e/paths/04-item/10_item_log.spec.js deleted file mode 100644 index c88fbd337..000000000 --- a/e2e/paths/04-item/10_item_log.spec.js +++ /dev/null @@ -1,45 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Item log path', () => { - let browser; - let page; - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('developer', 'item'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it(`should search for the Knowledge artifact to confirm it isn't created yet`, async() => { - await page.doSearch('Knowledge artifact'); - const nResults = await page.countElement(selectors.itemsIndex.searchResult); - - expect(nResults).toEqual(1); - }); - - it('should access to the create item view by clicking the create floating button', async() => { - await page.waitToClick(selectors.itemsIndex.createItemButton); - await page.waitForState('item.create'); - }); - - it('should create the Knowledge artifact item', async() => { - await page.write(selectors.itemCreateView.temporalName, 'Knowledge artifact'); - await page.autocompleteSearch(selectors.itemCreateView.type, 'Crisantemo'); - await page.autocompleteSearch(selectors.itemCreateView.intrastat, 'Coral y materiales similares'); - await page.autocompleteSearch(selectors.itemCreateView.origin, 'Holand'); - await page.waitToClick(selectors.itemCreateView.createButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should return to the items index by clicking the return to items button', async() => { - await page.waitToClick(selectors.itemBasicData.goToItemIndexButton); - await page.waitForSelector(selectors.itemsIndex.createItemButton); - await page.waitForState('item.index'); - }); -}); diff --git a/e2e/paths/04-item/11_descriptor.spec.js b/e2e/paths/04-item/11_descriptor.spec.js deleted file mode 100644 index eb9ed2573..000000000 --- a/e2e/paths/04-item/11_descriptor.spec.js +++ /dev/null @@ -1,41 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Item descriptor path', () => { - let browser; - let page; - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyer', 'item'); - await page.accessToSearchResult('1'); - await page.accessToSection('item.card.basicData'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should set the item to inactive', async() => { - await page.waitToClick(selectors.itemBasicData.isActiveCheckbox); - await page.waitToClick(selectors.itemBasicData.submitBasicDataButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should reload the section and check the inactive icon is visible', async() => { - await page.reloadSection('item.card.basicData'); - const visibleIcon = await page.isVisible(selectors.itemDescriptor.inactiveIcon); - - expect(visibleIcon).toBeTruthy(); - }); - - it('should set the item back to active', async() => { - await page.waitToClick(selectors.itemBasicData.isActiveCheckbox); - await page.waitToClick(selectors.itemBasicData.submitBasicDataButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); -}); diff --git a/e2e/paths/04-item/12_request.spec.js b/e2e/paths/04-item/12_request.spec.js deleted file mode 100644 index e0f3a1b45..000000000 --- a/e2e/paths/04-item/12_request.spec.js +++ /dev/null @@ -1,45 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Item request path', () => { - let browser; - let page; - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyer', 'item'); - await page.accessToSection('item.request'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should reach the item request section', async() => { - await page.waitForState('item.request'); - }); - - it('should fill the id and quantity then check the concept was updated', async() => { - await page.writeOnEditableTD(selectors.itemRequest.firstRequestItemID, '4'); - await page.writeOnEditableTD(selectors.itemRequest.firstRequestQuantity, '10'); - await page.waitForTextInElement(selectors.itemRequest.firstRequestConcept, 'Melee weapon heavy shield 100cm'); - let filledConcept = await page.waitToGetProperty(selectors.itemRequest.firstRequestConcept, 'innerText'); - - expect(filledConcept).toContain('Melee weapon heavy shield 100cm'); - }); - - it('should check the status of the request should now be accepted', async() => { - let status = await page.waitToGetProperty(selectors.itemRequest.firstRequestStatus, 'innerText'); - - expect(status).toContain('Accepted'); - }); - - it('should now click on the second declain request icon then type the reason', async() => { - await page.waitToClick(selectors.itemRequest.secondRequestDecline); - await page.write(selectors.itemRequest.declineReason, 'Not quite as expected'); - await page.respondToDialog('accept'); - let status = await page.waitToGetProperty(selectors.itemRequest.secondRequestStatus, 'innerText'); - - expect(status).toContain('Denied'); - }); -}); diff --git a/e2e/paths/04-item/13_fixedPrice.spec.js b/e2e/paths/04-item/13_fixedPrice.spec.js deleted file mode 100644 index f36138e18..000000000 --- a/e2e/paths/04-item/13_fixedPrice.spec.js +++ /dev/null @@ -1,97 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -const $ = selectors.itemFixedPrice; - -describe('Item fixed prices path', () => { - let browser; - let page; - let httpRequest; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyer', 'item'); - await page.accessToSection('item.fixedPrice'); - page.on('request', req => { - if (req.url().includes(`FixedPrices/filter`)) - httpRequest = req.url(); - }); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should filter using all the fields', async() => { - await page.write($.generalSearchFilter, 'item'); - await page.keyboard.press('Enter'); - - expect(httpRequest).toContain('search=item'); - - await page.click($.chip); - await page.click($.reignFilter); - - expect(httpRequest).toContain('categoryFk'); - - await page.autocompleteSearch($.typeFilter, 'Alstroemeria'); - - expect(httpRequest).toContain('typeFk'); - - await page.click($.chip); - await page.autocompleteSearch($.buyerFilter, 'buyerNick'); - - expect(httpRequest).toContain('buyerFk'); - - await page.click($.chip); - await page.autocompleteSearch($.warehouseFilter, 'Algemesi'); - - expect(httpRequest).toContain('warehouseFk'); - - await page.click($.chip); - await page.click($.mineFilter); - - expect(httpRequest).toContain('mine=true'); - - await page.click($.chip); - await page.click($.hasMinPriceFilter); - - expect(httpRequest).toContain('hasMinPrice=true'); - - await page.click($.chip); - await page.click($.addTag); - await page.autocompleteSearch($.tagFilter, 'Color'); - await page.autocompleteSearch($.tagValueFilter, 'Brown'); - - expect(httpRequest).toContain('tags'); - - await page.click($.chip); - }); - - it('should click on the add new fixed price button', async() => { - await page.waitToClick($.add); - await page.waitForSelector($.fourthFixedPrice); - }); - - it('should fill the fixed price data', async() => { - const now = Date.vnNew(); - await page.autocompleteSearch($.fourthWarehouse, 'Warehouse one'); - await page.writeOnEditableTD($.fourthGroupingPrice, '1'); - await page.writeOnEditableTD($.fourthPackingPrice, '1'); - await page.write($.fourthMinPrice, '1'); - await page.pickDate($.fourthStarted, now); - await page.pickDate($.fourthEnded, now); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should reload the section and check the created price has the expected ID', async() => { - await page.goto(`http://localhost:5000/#!/item/fixed-price`); - await page.autocompleteSearch($.warehouseFilter, 'Warehouse one'); - await page.click($.chip); - const result = await page.waitToGetProperty($.fourthItemID, 'value'); - - expect(result).toContain('13'); - }); -}); diff --git a/e2e/paths/05-ticket/01-sale/01_list_sales.spec.js b/e2e/paths/05-ticket/01-sale/01_list_sales.spec.js deleted file mode 100644 index ad0975889..000000000 --- a/e2e/paths/05-ticket/01-sale/01_list_sales.spec.js +++ /dev/null @@ -1,99 +0,0 @@ -import selectors from '../../../helpers/selectors.js'; -import getBrowser from '../../../helpers/puppeteer'; - -describe('Ticket List sale path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('employee', 'ticket'); - await page.accessToSearchResult('13'); - await page.accessToSection('ticket.card.sale'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should confirm the first ticket sale contains the colour tag', async() => { - const value = await page - .waitToGetProperty(selectors.ticketSales.firstSaleColour, 'innerText'); - - expect(value).toContain('Black'); - }); - - it('should confirm the first sale contains the price', async() => { - const value = await page - .waitToGetProperty(selectors.ticketSales.firstSalePrice, 'innerText'); - - expect(value).toContain('1.72'); - }); - - it('should confirm the first sale contains the discount', async() => { - const value = await page - .waitToGetProperty(selectors.ticketSales.firstSaleDiscount, 'innerText'); - - expect(value).toContain('0.00%'); - }); - - it('should confirm the first sale contains the total import', async() => { - const value = await page - .waitToGetProperty(selectors.ticketSales.firstSaleImport, 'innerText'); - - expect(value).toContain('34.40'); - }); - - it('should add an empty item to the sale list', async() => { - await page.waitToClick(selectors.ticketSales.newItemButton); - const sales = await page - .countElement(selectors.ticketSales.saleLine); - - expect(sales).toEqual(2); - }); - - it('should select a valid item to be added as the second item in the sales list', async() => { - let searchValue = 'Melee weapon heavy shield 100cm'; - await page.autocompleteSearch(selectors.ticketSales.secondSaleIdAutocomplete, searchValue); - await page.waitToClick(selectors.ticketSales.secondSaleQuantityCell); - await page.type(selectors.ticketSales.secondSaleQuantity, '8'); - await page.keyboard.press('Enter'); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should update the description of the new sale', async() => { - await page.click(selectors.ticketSales.secondSaleConceptCell); - await page.write(selectors.ticketSales.secondSaleConceptInput, 'Aegis of Valor'); - await page.keyboard.press('Enter'); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should add a third empty item to the sale list', async() => { - await page.waitToClick(selectors.ticketSales.newItemButton); - await page.waitForNumberOfElements(selectors.ticketSales.saleLine, 3); - const sales = await page.countElement(selectors.ticketSales.saleLine); - - expect(sales).toEqual(3); - }); - - it('should select the 2nd and 3th item and delete both', async() => { - await page.waitToClick(selectors.ticketSales.secondSaleCheckbox); - await page.waitToClick(selectors.ticketSales.thirdSaleCheckbox); - await page.waitToClick(selectors.ticketSales.deleteSaleButton); - await page.waitToClick(selectors.globalItems.acceptButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it(`should verify there's only 1 single line remaining`, async() => { - const sales = await page.countElement(selectors.ticketSales.saleLine); - - expect(sales).toEqual(1); - }); -}); diff --git a/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js b/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js deleted file mode 100644 index d9689e31a..000000000 --- a/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js +++ /dev/null @@ -1,415 +0,0 @@ -import selectors from '../../../helpers/selectors.js'; -import getBrowser from '../../../helpers/puppeteer'; - -describe('Ticket Edit sale path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('salesPerson', 'ticket'); - await page.accessToSearchResult('16'); - await page.accessToSection('ticket.card.sale'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it(`should click on the first sale claim icon to navigate over there`, async() => { - await page.waitToClick(selectors.ticketSales.firstSaleClaimIcon); - await page.waitForNavigation(); - await page.goBack(); - await page.goBack(); - }); - - it('should navigate to the tickets index', async() => { - await page.waitToClick(selectors.globalItems.applicationsMenuButton); - await page.waitForSelector(selectors.globalItems.applicationsMenuVisible); - await page.waitToClick(selectors.globalItems.ticketsButton); - await page.waitForState('ticket.index'); - }); - - it(`should search for a ticket and then navigate to it's sales`, async() => { - await page.accessToSearchResult('16'); - await page.accessToSection('ticket.card.sale'); - }); - - it(`should set the ticket as libre`, async() => { - const searchValue = 'libre'; - await page.waitToClick(selectors.ticketSales.stateMenuButton); - await page.write(selectors.ticketSales.moreMenuState, searchValue); - try { - await page.waitForFunction(searchValue => { - const element = document.querySelector('li.active'); - if (element) - return element.innerText.toLowerCase().includes(searchValue.toLowerCase()); - }, {}, searchValue); - } catch (error) { - const builtSelector = await page.selectorFormater(selectors.ticketSales.moreMenuState); - const inputValue = await page.evaluate(() => { - return document.querySelector('.vn-drop-down.shown vn-textfield input').value; - }); - throw new Error(`${builtSelector} value is ${inputValue}! ${error}`); - } - await page.waitForState('ticket.card.sale'); - await page.keyboard.press('Enter'); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it(`should check it's state is libre now`, async() => { - await page.waitForTextInElement(selectors.ticketDescriptor.stateLabelValue, 'Libre'); - const result = await page.waitToGetProperty(selectors.ticketDescriptor.stateLabelValue, 'innerText'); - - expect(result).toEqual('State Libre'); - }); - - it(`should set the ticket as OK`, async() => { - await page.waitToClick(selectors.ticketSales.setOk); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it(`should check it's state is OK now`, async() => { - await page.waitForTextInElement(selectors.ticketDescriptor.stateLabelValue, 'OK'); - const result = await page.waitToGetProperty(selectors.ticketDescriptor.stateLabelValue, 'innerText'); - - expect(result).toEqual('State OK'); - }); - - it(`should check the zoomed image isn't present`, async() => { - const result = await page.countElement(selectors.ticketSales.firstSaleZoomedImage); - - expect(result).toEqual(0); - }); - - it(`should click on the thumbnail image of the 1st sale and see the zoomed image`, async() => { - await page.waitToClick(selectors.ticketSales.firstSaleThumbnailImage); - const result = await page.countElement(selectors.ticketSales.firstSaleZoomedImage); - - expect(result).toEqual(1); - }); - - it(`should click on the zoomed image to close it`, async() => { - await page.waitToClick(selectors.ticketSales.firstSaleZoomedImage); - const result = await page.countElement(selectors.ticketSales.firstSaleZoomedImage); - - expect(result).toEqual(0); - }); - - it(`should click on the first sale ID making now the item descriptor visible`, async() => { - await page.waitToClick(selectors.ticketSales.firstSaleId); - await page.waitImgLoad(selectors.ticketSales.firstSaleDescriptorImage); - const visible = await page.isVisible(selectors.ticketSales.saleDescriptorPopover); - - expect(visible).toBeTruthy(); - }); - - it(`should click on the descriptor image of the 1st sale and see the zoomed image`, async() => { - await page.waitToClick('vn-item-descriptor img'); - const result = await page.countElement(selectors.ticketSales.firstSaleZoomedImage); - - expect(result).toEqual(1); - }); - - it(`should now click on the zoomed image to close it`, async() => { - await page.waitToClick(selectors.ticketSales.firstSaleZoomedImage); - const result = await page.countElement(selectors.ticketSales.firstSaleZoomedImage); - - expect(result).toEqual(0); - }); - - it(`should click on the summary icon of the item-descriptor to access to the item summary`, async() => { - await page.waitToClick(selectors.ticketSales.saleDescriptorPopoverSummaryButton); - await page.waitForState('item.card.summary'); - }); - - it('should return to ticket sales section', async() => { - await page.waitToClick(selectors.globalItems.applicationsMenuButton); - await page.waitForSelector(selectors.globalItems.applicationsMenuVisible); - await page.waitToClick(selectors.globalItems.ticketsButton); - await page.accessToSearchResult('16'); - await page.accessToSection('ticket.card.sale'); - }); - - it('should remove 1 from the first sale quantity', async() => { - await page.waitToClick(selectors.ticketSales.firstSaleQuantityCell); - await page.waitForSelector(selectors.ticketSales.firstSaleQuantity); - await page.type(selectors.ticketSales.firstSaleQuantity, '9\u000d'); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should update the price', async() => { - await page.waitToClick(selectors.ticketSales.firstSalePrice); - await page.waitForSelector(selectors.ticketSales.firstSalePriceInput); - await page.type(selectors.ticketSales.firstSalePriceInput, '5\u000d'); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should confirm the price have been updated', async() => { - const result = await page.waitToGetProperty(selectors.ticketSales.firstSalePrice, 'innerText'); - - expect(result).toContain('5.00'); - }); - - it('should confirm the total price for that item have been updated', async() => { - const result = await page.waitToGetProperty(selectors.ticketSales.firstSaleImport, 'innerText'); - - expect(result).toContain('45.00'); - }); - - it('should update the discount', async() => { - await page.waitToClick(selectors.ticketSales.firstSaleDiscount); - await page.waitForSelector(selectors.ticketSales.firstSaleDiscountInput); - await page.type(selectors.ticketSales.firstSaleDiscountInput, '50'); - await page.waitToClick(selectors.ticketSales.saveSaleDiscountButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should confirm the discount have been updated', async() => { - await page.waitForTextInElement(selectors.ticketSales.firstSaleDiscount, '50.00%'); - const result = await page.waitToGetProperty(selectors.ticketSales.firstSaleDiscount, 'innerText'); - - expect(result).toContain('50.00%'); - }); - - it('should confirm the total import for that item have been updated', async() => { - await page.waitForTextInElement(selectors.ticketSales.firstSaleImport, '22.50'); - const result = await page.waitToGetProperty(selectors.ticketSales.firstSaleImport, 'innerText'); - - expect(result).toContain('22.50'); - }); - - it('should recalculate price of sales', async() => { - await page.waitToClick(selectors.ticketSales.firstSaleCheckbox); - await page.waitToClick(selectors.ticketSales.secondSaleCheckbox); - - await page.waitToClick(selectors.ticketSales.moreMenu); - await page.waitToClick(selectors.ticketSales.moreMenuRecalculatePrice); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should log in as salesAssistant and navigate to ticket sales', async() => { - await page.loginAndModule('salesAssistant', 'ticket'); - await page.accessToSearchResult('15'); - await page.accessToSection('ticket.card.sale'); - }); - - it('should select the first sale and create a refund with warehouse', async() => { - await page.waitToClick(selectors.ticketSales.firstSaleCheckbox); - await page.waitToClick(selectors.ticketSales.moreMenu); - await page.waitToClick(selectors.ticketSales.moreMenuRefund); - await page.waitToClick(selectors.ticketSales.refundWithWarehouse); - await page.waitForSnackbar(); - await page.waitForState('ticket.card.sale'); - }); - - it('should select the first sale and create a refund without warehouse', async() => { - await page.accessToSearchResult('18'); - await page.waitToClick(selectors.ticketSales.firstSaleCheckbox); - await page.waitToClick(selectors.ticketSales.moreMenu); - await page.waitToClick(selectors.ticketSales.moreMenuRefund); - await page.waitToClick(selectors.ticketSales.refundWithoutWarehouse); - await page.waitForSnackbar(); - await page.waitForState('ticket.card.sale'); - }); - - it('should show error trying to delete a ticket with a refund', async() => { - await page.loginAndModule('salesPerson', 'ticket'); - await page.accessToSearchResult('8'); - await page.waitToClick(selectors.ticketDescriptor.moreMenu); - await page.waitToClick(selectors.ticketDescriptor.moreMenuDeleteTicket); - await page.waitToClick(selectors.globalItems.acceptButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Tickets with associated refunds can\'t be deleted'); - await page.waitToClick(selectors.globalItems.cancelButton); - }); - - it('should select the third sale and create a claim of it', async() => { - await page.accessToSearchResult('16'); - await page.accessToSection('ticket.card.sale'); - await page.waitToClick(selectors.ticketSales.thirdSaleCheckbox); - await page.waitToClick(selectors.ticketSales.moreMenu); - await page.waitToClick(selectors.ticketSales.moreMenuCreateClaim); - await page.waitToClick(selectors.globalItems.acceptButton); - await page.waitForNavigation(); - }); - - it('should search for a ticket then access to the sales section', async() => { - await page.goBack(); - await page.goBack(); - await page.loginAndModule('salesPerson', 'ticket'); - await page.accessToSearchResult('16'); - await page.accessToSection('ticket.card.sale'); - }); - - it('should select the third sale and delete it', async() => { - await page.waitToClick(selectors.ticketSales.thirdSaleCheckbox); - await page.waitToClick(selectors.ticketSales.deleteSaleButton); - await page.waitToClick(selectors.globalItems.acceptButton); - await page.waitForSpinnerLoad(); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it(`should confirm the third sale was deleted`, async() => { - const result = await page.countElement(selectors.ticketSales.saleLine); - - expect(result).toEqual(3); - }); - - it('should select the second sale and transfer it to a valid ticket', async() => { - const targetTicketId = '12'; - - await page.waitToClick(selectors.ticketSales.secondSaleCheckbox); - await page.waitToClick(selectors.ticketSales.transferSaleButton); - await page.waitToClick(selectors.ticketSales.transferQuantityCell); - await page.type(selectors.ticketSales.transferQuantityInput, '10\u000d'); - await page.type(selectors.ticketSales.moveToTicketInput, targetTicketId); - await page.waitToClick(selectors.ticketSales.moveToTicketButton); - await page.expectURL(`ticket/${targetTicketId}/sale`); - }); - - it('should confirm the transfered line is the correct one', async() => { - await page.waitForSelector(selectors.ticketSales.secondSaleText); - const result = await page.waitToGetProperty(selectors.ticketSales.secondSaleText, 'innerText'); - - expect(result).toContain(`Melee weapon heavy shield`); - }); - - it('should confirm the transfered quantity is the correct one', async() => { - const result = await page.waitToGetProperty(selectors.ticketSales.firstSaleQuantityCell, 'innerText'); - - expect(result).toContain('20'); - }); - - it('should go back to the original ticket sales section', async() => { - await page.waitToClick(selectors.ticketDescriptor.goBackToModuleIndexButton); - await page.accessToSearchResult('16'); - await page.accessToSection('ticket.card.sale'); - }); - - it(`should confirm the original ticket has still three lines`, async() => { - await page.waitForSelector(selectors.ticketSales.saleLine); - const result = await page.countElement(selectors.ticketSales.saleLine); - - expect(result).toEqual(3); - }); - - it(`should confirm the second sale quantity is now half of it's original value after the transfer`, async() => { - const result = await page.waitToGetProperty(selectors.ticketSales.secondSaleQuantityCell, 'innerText'); - - expect(result).toContain('10'); - }); - - it('should go back to the receiver ticket sales section', async() => { - await page.waitToClick(selectors.ticketDescriptor.goBackToModuleIndexButton); - await page.accessToSearchResult('12'); - await page.accessToSection('ticket.card.sale'); - }); - - it('should transfer the sale back to the original ticket', async() => { - const targetTicketId = '16'; - - await page.waitToClick(selectors.ticketSales.secondSaleCheckbox); - await page.waitToClick(selectors.ticketSales.transferSaleButton); - await page.type(selectors.ticketSales.moveToTicketInput, targetTicketId); - await page.waitToClick(selectors.ticketSales.moveToTicketButton); - await page.expectURL(`ticket/${targetTicketId}/sale`); - }); - - it('should confirm the original ticket received the line', async() => { - const expectedLines = 4; - await page.waitForNumberOfElements(selectors.ticketSales.saleLine, expectedLines); - const result = await page.countElement(selectors.ticketSales.saleLine); - - expect(result).toEqual(expectedLines); - }); - - it(`should throw an error when attempting to create a ticket for an inactive client`, async() => { - await page.waitToClick(selectors.ticketSales.firstSaleCheckbox); - await page.waitToClick(selectors.ticketSales.transferSaleButton); - await page.waitToClick(selectors.ticketSales.moveToNewTicketButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain(`You can't create a ticket for an inactive client`); - - await page.closePopup(); - }); - - it('should go now to the ticket sales section of an active, not frozen client', async() => { - await page.waitToClick(selectors.ticketDescriptor.goBackToModuleIndexButton); - await page.accessToSearchResult('13'); - await page.accessToSection('ticket.card.sale'); - }); - - it(`should select all sales, tranfer them to a new ticket and delete the sender ticket as it would've been left empty`, async() => { - const senderTicketId = '13'; - - await page.waitToClick(selectors.ticketSales.selectAllSalesCheckbox); - await page.waitToClick(selectors.ticketSales.transferSaleButton); - await page.waitToClick(selectors.ticketSales.moveToNewTicketButton); - await page.evaluate((selector, ticketId) => { - return document.querySelector(selector).innerText.toLowerCase().indexOf(`#${ticketId}`) == -1; - }, selectors.ticketDescriptor.id, senderTicketId); - await page.waitForState('ticket.card.sale'); - }); - - it('should confirm the new ticket received the line', async() => { - const expectedLines = 1; - const result = await page.countElement(selectors.ticketSales.saleLine); - - expect(result).toEqual(expectedLines); - }); - - it('should check the first sale reserved icon isnt visible', async() => { - const result = await page.isVisible(selectors.ticketSales.firstSaleReservedIcon); - - expect(result).toBeFalsy(); - }); - - it('should mark the first sale as reserved', async() => { - await page.waitToClick(selectors.ticketSales.firstSaleCheckbox); - - await page.waitToClick(selectors.ticketSales.moreMenu); - await page.waitToClick(selectors.ticketSales.moreMenuReserve); - await page.closePopup(); - await page.waitForClassNotPresent(selectors.ticketSales.firstSaleReservedIcon, 'ng-hide'); - const result = await page.isVisible(selectors.ticketSales.firstSaleReservedIcon); - - expect(result).toBeTruthy(); - }); - - it('should unmark the first sale as reserved', async() => { - await page.waitToClick(selectors.ticketSales.moreMenu); - await page.waitToClick(selectors.ticketSales.moreMenuUnmarkReseved); - await page.waitForClassPresent(selectors.ticketSales.firstSaleReservedIcon, 'ng-hide'); - const result = await page.isVisible(selectors.ticketSales.firstSaleReservedIcon); - - expect(result).toBeFalsy(); - }); - - it('should log in as Production role and go to a target ticket summary', async() => { - await page.loginAndModule('production', 'ticket'); - await page.accessToSearchResult('13'); - await page.waitForState('ticket.card.summary'); - }); - - it(`should check the ticket is deleted`, async() => { - await page.waitForSelector(selectors.ticketDescriptor.isDeletedIcon); - }); -}); diff --git a/e2e/paths/05-ticket/01_observations.spec.js b/e2e/paths/05-ticket/01_observations.spec.js deleted file mode 100644 index cf37f9ff1..000000000 --- a/e2e/paths/05-ticket/01_observations.spec.js +++ /dev/null @@ -1,50 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Ticket Create notes path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('employee', 'ticket'); - await page.accessToSearchResult('5'); - await page.accessToSection('ticket.card.observation'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should create a new note', async() => { - await page.waitToClick(selectors.ticketNotes.addNoteButton); - await page.autocompleteSearch(selectors.ticketNotes.firstNoteType, 'ItemPicker'); - await page.write(selectors.ticketNotes.firstDescription, 'description'); - await page.waitToClick(selectors.ticketNotes.submitNotesButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should confirm the note is the expected one', async() => { - await page.reloadSection('ticket.card.observation'); - const result = await page - .waitToGetProperty(selectors.ticketNotes.firstNoteType, 'value'); - - expect(result).toEqual('ItemPicker'); - - const firstDescription = await page - .waitToGetProperty(selectors.ticketNotes.firstDescription, 'value'); - - expect(firstDescription).toEqual('description'); - }); - - it('should delete the note', async() => { - await page.waitToClick(selectors.ticketNotes.firstNoteRemoveButton); - await page.waitToClick(selectors.ticketNotes.submitNotesButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); -}); diff --git a/e2e/paths/05-ticket/02_expeditions_and_log.spec.js b/e2e/paths/05-ticket/02_expeditions_and_log.spec.js deleted file mode 100644 index 4e8005043..000000000 --- a/e2e/paths/05-ticket/02_expeditions_and_log.spec.js +++ /dev/null @@ -1,32 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Ticket expeditions and log path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('production', 'ticket'); - await page.accessToSearchResult('1'); - await page.accessToSection('ticket.card.expedition'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it(`should delete a former expedition and confirm the remaining expedition are the expected ones`, async() => { - await page.waitToClick(selectors.ticketExpedition.thirdSaleCheckbox); - await page.waitToClick(selectors.ticketExpedition.deleteExpeditionButton); - await page.waitToClick(selectors.globalItems.acceptButton); - await page.reloadSection('ticket.card.expedition'); - - await page.waitForSelector(selectors.ticketExpedition.expeditionRow, {}); - const result = await page - .countElement(selectors.ticketExpedition.expeditionRow); - - expect(result).toEqual(6); - }); -}); diff --git a/e2e/paths/05-ticket/04_packages.spec.js b/e2e/paths/05-ticket/04_packages.spec.js deleted file mode 100644 index 1e6a0a173..000000000 --- a/e2e/paths/05-ticket/04_packages.spec.js +++ /dev/null @@ -1,78 +0,0 @@ -import getBrowser from '../../helpers/puppeteer'; - -const $ = { - firstPackage: 'vn-autocomplete[label="Package"]', - firstQuantity: 'vn-ticket-package vn-horizontal:nth-child(1) vn-input-number[ng-model="package.quantity"]', - firstRemovePackageButton: 'vn-icon-button[vn-tooltip="Remove package"]', - addPackageButton: 'vn-icon-button[vn-tooltip="Add package"]', - savePackagesButton: `button[type=submit]` -}; - -describe('Ticket Create packages 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.package'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it(`should attempt create a new package but receive an error if package is blank`, async() => { - await page.waitToClick($.firstRemovePackageButton); - await page.waitToClick($.addPackageButton); - await page.write($.firstQuantity, '99'); - await page.waitToClick($.savePackagesButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Package cannot be blank'); - }); - - it(`should delete the first package and receive and error to save a new one with blank quantity`, async() => { - await page.clearInput($.firstQuantity); - await page.autocompleteSearch($.firstPackage, 'Container medical box 100cm'); - await page.waitToClick($.savePackagesButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Some fields are invalid'); - }); - - it(`should confirm the quantity input isn't invalid yet`, async() => { - const result = await page - .evaluate(selector => { - return document.querySelector(`${selector} input`).checkValidity(); - }, $.firstQuantity); - - expect(result).toBeTruthy(); - }); - - it(`should create a new package with correct data`, async() => { - await page.clearInput($.firstQuantity); - await page.write($.firstQuantity, '-99'); - await page.waitToClick($.savePackagesButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it(`should confirm the first select is the expected one`, async() => { - await page.reloadSection('ticket.card.package'); - await page.waitForTextInField($.firstPackage, 'Container medical box 100cm'); - const result = await page.waitToGetProperty($.firstPackage, 'value'); - - expect(result).toEqual('Container medical box 100cm'); - }); - - it(`should confirm quantity is just a number and the string part was ignored by the imput number`, async() => { - await page.waitForTextInField($.firstQuantity, '-99'); - const result = await page.waitToGetProperty($.firstQuantity, 'value'); - - expect(result).toEqual('-99'); - }); -}); diff --git a/e2e/paths/05-ticket/05_tracking_state.spec.js b/e2e/paths/05-ticket/05_tracking_state.spec.js deleted file mode 100644 index 5cfc1c9d4..000000000 --- a/e2e/paths/05-ticket/05_tracking_state.spec.js +++ /dev/null @@ -1,72 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Ticket Create new tracking state path', () => { - let browser; - let page; - - afterAll(async() => { - await browser.close(); - }); - - describe('as production', () => { - it('should log into the ticket 1 tracking', async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('production', 'ticket'); - await page.accessToSearchResult('1'); - await page.accessToSection('ticket.card.tracking.index'); - }); - - it('should access to the create state view by clicking the create floating button', async() => { - await page.waitToClick(selectors.ticketTracking.createStateButton); - await page.waitForSelector(selectors.createStateView.state, {visible: true}); - await page.waitForState('ticket.card.tracking.edit'); - }); - - it(`should create a new state`, async() => { - await page.autocompleteSearch(selectors.createStateView.state, 'OK'); - await page.waitToClick(selectors.createStateView.saveStateButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - }); - - describe('as salesPerson', () => { - it('should now log into the ticket 1 tracking', async() => { - await page.loginAndModule('salesPerson', 'ticket'); - await page.accessToSearchResult('1'); - await page.accessToSection('ticket.card.tracking.index'); - }); - - it('should now access to the create state view by clicking the create floating button', async() => { - await page.waitForSelector('.vn-popup', {hidden: true}); - await page.waitToClick(selectors.ticketTracking.createStateButton); - await page.waitForState('ticket.card.tracking.edit'); - }); - - it(`should attemp to create an state for which salesPerson doesn't have permissions`, async() => { - await page.autocompleteSearch(selectors.createStateView.state, 'Encajado'); - await page.waitToClick(selectors.createStateView.saveStateButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain(`You don't have enough privileges`); - }); - - it(`should make sure the worker gets autocomplete uppon selecting the assigned state`, async() => { - await page.autocompleteSearch(selectors.createStateView.state, 'asignado'); - const result = await page - .waitToGetProperty(selectors.createStateView.worker, 'value'); - - expect(result).toEqual('salesperson'); - }); - - it(`should succesfully create a valid state`, async() => { - await page.waitToClick(selectors.createStateView.saveStateButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - }); -}); diff --git a/e2e/paths/05-ticket/06_basic_data_steps.spec.js b/e2e/paths/05-ticket/06_basic_data_steps.spec.js deleted file mode 100644 index 77f0e0459..000000000 --- a/e2e/paths/05-ticket/06_basic_data_steps.spec.js +++ /dev/null @@ -1,143 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Ticket Edit basic data path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('employee', 'ticket'); - await page.accessToSearchResult('11'); - await page.accessToSection('ticket.card.basicData.stepOne'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it(`should confirm the zone autocomplete is disabled unless your role is productionBoss`, async() => { - await page.waitForSelector(selectors.ticketBasicData.zone, {}); - const disabled = await page.evaluate(selector => { - return document.querySelector(selector).disabled; - }, `${selectors.ticketBasicData.zone} input`); - - expect(disabled).toBeTruthy(); - }); - - it(`should now log as productionBoss to perform the rest of the tests`, async() => { - await page.loginAndModule('productionBoss', 'ticket'); - await page.accessToSearchResult('11'); - await page.accessToSection('ticket.card.basicData.stepOne'); - }); - - it(`should confirm the zone autocomplete is enabled for the role productionBoss`, async() => { - await page.waitForSpinnerLoad(); - await page.waitForSelector(selectors.ticketBasicData.zone); - const disabled = await page.evaluate(selector => { - return document.querySelector(selector).disabled; - }, `${selectors.ticketBasicData.zone} input`); - - expect(disabled).toBeFalsy(); - }); - - it(`should check the zone is for Gotham247`, async() => { - let zone = await page - .waitToGetProperty(selectors.ticketBasicData.zone, 'value'); - - expect(zone).toContain('Zone 247 A'); - }); - - it(`should edit the ticket agency then check there are no zones for it`, async() => { - await page.autocompleteSearch(selectors.ticketBasicData.agency, 'Super-Man delivery'); - let emptyZone = await page - .expectPropertyValue(selectors.ticketBasicData.zone, 'value', ''); - - expect(emptyZone).toBeTruthy(); - }); - - it(`should edit the ticket zone then check the agency is for the new zone`, async() => { - await page.clearInput(selectors.ticketBasicData.agency); - await page.autocompleteSearch(selectors.ticketBasicData.zone, 'Zone expensive A'); - let zone = await page - .waitToGetProperty(selectors.ticketBasicData.agency, 'value'); - - expect(zone).toContain('Gotham247Expensive'); - }); - - it(`should click next`, async() => { - await page.waitToClick(selectors.ticketBasicData.nextStepButton); - await page.waitForState('ticket.card.basicData.stepTwo'); - }); - - it(`should have a price diference`, async() => { - const result = await page - .waitToGetProperty(selectors.ticketBasicData.stepTwoTotalPriceDif, 'innerText'); - - expect(result).toContain('-€228.25'); - }); - - it(`should select a new reason for the changes made then click on finalize`, async() => { - await page.waitToClick(selectors.ticketBasicData.chargesReason); - await page.waitToClick(selectors.ticketBasicData.finalizeButton); - await page.waitForState('ticket.card.summary'); - }); - - it(`should not find ticket`, async() => { - await page.doSearch('29'); - const count = await page.countElement(selectors.ticketsIndex.searchResult); - - expect(count).toEqual(0); - }); - - it(`should split ticket without negatives`, async() => { - const newAgency = 'Gotham247'; - const newDate = Date.vnNew(); - newDate.setDate(newDate.getDate() - 1); - - await page.accessToSearchResult('14'); - await page.accessToSection('ticket.card.basicData.stepOne'); - - await page.autocompleteSearch(selectors.ticketBasicData.agency, newAgency); - await page.pickDate(selectors.ticketBasicData.shipped, newDate); - - await page.waitToClick(selectors.ticketBasicData.nextStepButton); - - await page.waitToClick(selectors.ticketBasicData.finalizeButton); - - await page.waitForState('ticket.card.summary'); - - const newTicketAgency = await page - .waitToGetProperty(selectors.ticketDescriptor.descriptorDeliveryAgency, 'innerText'); - const newTicketDate = await page - .waitToGetProperty(selectors.ticketDescriptor.descriptorDeliveryDate, 'innerText'); - - expect(newAgency).toEqual(newTicketAgency); - expect(newTicketDate).toContain(newDate.getDate()); - }); - - it(`should new ticket have sale of old ticket`, async() => { - await page.accessToSection('ticket.card.sale'); - await page.waitForState('ticket.card.sale'); - - const item = await page.waitToGetProperty(selectors.ticketSales.firstSaleId, 'innerText'); - - expect(item).toEqual('4'); - }); - - it(`should old ticket have old date and agency`, async() => { - const oldDate = Date.vnNew(); - const oldAgency = 'Super-Man delivery'; - - await page.accessToSearchResult('14'); - - const oldTicketAgency = await page - .waitToGetProperty(selectors.ticketDescriptor.descriptorDeliveryAgency, 'innerText'); - const oldTicketDate = await page - .waitToGetProperty(selectors.ticketDescriptor.descriptorDeliveryDate, 'innerText'); - - expect(oldTicketAgency).toEqual(oldAgency); - expect(oldTicketDate).toContain(oldDate.getDate()); - }); -}); diff --git a/e2e/paths/05-ticket/08_components.spec.js b/e2e/paths/05-ticket/08_components.spec.js deleted file mode 100644 index ab2aa85b2..000000000 --- a/e2e/paths/05-ticket/08_components.spec.js +++ /dev/null @@ -1,30 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Ticket List components 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.components'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should confirm the total base is correct', async() => { - const name = 'Base €'; - const minLength = name.length; - - await page.waitPropertyLength(selectors.ticketComponents.base, 'innerText', minLength); - const base = await page.waitToGetProperty(selectors.ticketComponents.base, 'innerText'); - - expect(base).toContain('Base'); - expect(base.length).toBeGreaterThan(minLength); - }); -}); diff --git a/e2e/paths/05-ticket/09_weekly.spec.js b/e2e/paths/05-ticket/09_weekly.spec.js deleted file mode 100644 index 370d422e6..000000000 --- a/e2e/paths/05-ticket/09_weekly.spec.js +++ /dev/null @@ -1,123 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Ticket descriptor path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyerBoss', 'ticket'); - await page.accessToSection('ticket.weekly.index'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should count the amount of tickets in the turns section', async() => { - const result = await page.countElement(selectors.ticketsIndex.weeklyTicket); - - expect(result).toEqual(6); - }); - - it('should go back to the ticket index then search and access a ticket summary', async() => { - await page.accessToSection('ticket.index'); - await page.accessToSearchResult('33'); - }); - - it('should add the ticket to thursday turn using the descriptor more menu', async() => { - await page.waitToClick(selectors.ticketDescriptor.moreMenu); - await page.waitToClick(selectors.ticketDescriptor.moreMenuAddToTurn); - await page.waitToClick(selectors.ticketDescriptor.thursdayButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Current ticket deleted and added to shift'); - }); - - it('should again click on the Tickets button of the top bar menu', async() => { - await page.waitToClick(selectors.globalItems.applicationsMenuButton); - await page.waitForSelector(selectors.globalItems.applicationsMenuVisible); - await page.waitToClick(selectors.globalItems.ticketsButton); - await page.waitForState('ticket.index'); - }); - - it('should confirm the ticket 33 was added to thursday', async() => { - await page.accessToSection('ticket.weekly.index'); - const result = await page.waitToGetProperty(selectors.ticketsIndex.thirdWeeklyTicket, 'value'); - - expect(result).toEqual('Thursday'); - }); - - it('should click on the Tickets button of the top bar menu once more', async() => { - await page.waitToClick(selectors.globalItems.applicationsMenuButton); - await page.waitForSelector(selectors.globalItems.applicationsMenuVisible); - await page.waitToClick(selectors.globalItems.ticketsButton); - await page.waitForState('ticket.index'); - }); - - it('should now search for the ticket 33', async() => { - await page.accessToSearchResult('33'); - await page.waitForState('ticket.card.summary'); - }); - - it('should add the ticket to saturday turn using the descriptor more menu', async() => { - await page.waitToClick(selectors.ticketDescriptor.moreMenu); - await page.waitToClick(selectors.ticketDescriptor.moreMenuAddToTurn); - await page.waitToClick(selectors.ticketDescriptor.saturdayButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Current ticket deleted and added to shift'); - }); - - it('should click on the Tickets button of the top bar menu once again', async() => { - await page.waitToClick(selectors.globalItems.applicationsMenuButton); - await page.waitForSelector(selectors.globalItems.applicationsMenuVisible); - await page.waitToClick(selectors.globalItems.ticketsButton); - await page.waitForState('ticket.index'); - }); - - it('should confirm the ticket 33 was added on saturday', async() => { - await page.accessToSection('ticket.weekly.index'); - await page.waitForTimeout(5000); - - const result = await page.waitToGetProperty(selectors.ticketsIndex.thirdWeeklyTicket, 'value'); - - expect(result).toEqual('Saturday'); - }); - - it('should now search for the weekly ticket 33', async() => { - await page.doSearch('33'); - const nResults = await page.countElement(selectors.ticketsIndex.searchWeeklyResult); - - expect(nResults).toEqual(2); - }); - - it('should delete the weekly ticket 33', async() => { - await page.waitToClick(selectors.ticketsIndex.firstWeeklyTicketDeleteIcon); - await page.waitToClick(selectors.ticketsIndex.acceptDeleteTurn); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should confirm the sixth weekly ticket was deleted', async() => { - await page.doSearch(); - const nResults = await page.countElement(selectors.ticketsIndex.searchWeeklyResult); - - expect(nResults).toEqual(6); - }); - - it('should update the agency then remove it afterwards', async() => { - await page.autocompleteSearch(selectors.ticketsIndex.firstWeeklyTicketAgency, 'Gotham247'); - let message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - - await page.clearInput(selectors.ticketsIndex.firstWeeklyTicketAgency); - message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); -}); diff --git a/e2e/paths/05-ticket/10_request.spec.js b/e2e/paths/05-ticket/10_request.spec.js deleted file mode 100644 index 1b580aec2..000000000 --- a/e2e/paths/05-ticket/10_request.spec.js +++ /dev/null @@ -1,77 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Ticket purchase request path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('salesPerson', 'ticket'); - await page.accessToSearchResult('1'); - await page.accessToSection('ticket.card.request.index'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should add a new request', async() => { - await page.waitToClick(selectors.ticketRequests.addRequestButton); - await page.write(selectors.ticketRequests.descriptionInput, 'New stuff'); - await page.write(selectors.ticketRequests.quantity, '9'); - await page.autocompleteSearch(selectors.ticketRequests.atender, 'buyerNick'); - await page.write(selectors.ticketRequests.price, '999'); - await page.waitToClick(selectors.ticketRequests.saveButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should have been redirected to the request index', async() => { - await page.waitForState('ticket.card.request.index'); - }); - - it(`should edit the third request quantity as it's state is still new`, async() => { - await page.write(selectors.ticketRequests.thirdRequestQuantity, '9'); - await page.keyboard.press('Enter'); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should check the new request was added', async() => { - await page.reloadSection('ticket.card.request.index'); - const result = await page.waitToGetProperty(selectors.ticketRequests.thirdRequestQuantity, 'value'); - - expect(result).toEqual('99'); - }); - - it(`should check the first request can't be edited as its state is different to new`, async() => { - await page.waitForClassPresent(selectors.ticketRequests.firstRequestQuantity, 'disabled'); - const result = await page.isDisabled(selectors.ticketRequests.firstRequestQuantity); - - expect(result).toBe(true); - }); - - it(`should check the second request can't be edited as its state is different to new`, async() => { - await page.waitForClassPresent(selectors.ticketRequests.secondRequestQuantity, 'disabled'); - const result = await page.isDisabled(selectors.ticketRequests.secondRequestQuantity); - - expect(result).toBe(true); - }); - - it('should delete the added request', async() => { - await page.waitToClick(selectors.ticketRequests.thirdRemoveRequestButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should check the request was deleted', async() => { - await page.reloadSection('ticket.card.request.index'); - await page.waitForSelector(selectors.ticketRequests.addRequestButton); - await page.waitForSelector(selectors.ticketRequests.thirdDescription, {hidden: true}); - }); -}); diff --git a/e2e/paths/05-ticket/12_descriptor.spec.js b/e2e/paths/05-ticket/12_descriptor.spec.js deleted file mode 100644 index 95a114c45..000000000 --- a/e2e/paths/05-ticket/12_descriptor.spec.js +++ /dev/null @@ -1,148 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Ticket descriptor path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('salesperson', 'ticket'); - }); - - afterAll(async() => { - await browser.close(); - }); - - describe('Delete ticket', () => { - it('should search for an specific ticket', async() => { - await page.accessToSearchResult('18'); - await page.waitForState('ticket.card.summary'); - }); - - it(`should update the shipped hour using the descriptor menu`, async() => { - await page.waitToClick(selectors.ticketDescriptor.moreMenu); - await page.waitToClick(selectors.ticketDescriptor.moreMenuChangeShippedHour); - await page.pickTime(selectors.ticketDescriptor.changeShippedHour, '08:15'); - await page.waitToClick(selectors.ticketDescriptor.acceptChangeHourButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Shipped hour updated'); - }); - - it(`should confirm the ticket descriptor shows the correct shipping hour`, async() => { - await page.waitForState('ticket.card.summary'); - const result = await page - .waitToGetProperty(selectors.ticketDescriptor.descriptorDeliveryDate, 'innerText'); - - expect(result).toContain('08:15'); - }); - - it('should delete the ticket using the descriptor menu', async() => { - await page.waitToClick(selectors.ticketDescriptor.moreMenu); - await page.waitToClick(selectors.ticketDescriptor.moreMenuDeleteTicket); - await page.waitToClick(selectors.ticketDescriptor.acceptDialog); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Ticket deleted. You can undo this action within the first hour'); - }); - - it('should have been relocated to the ticket index', async() => { - await page.waitForState('ticket.index'); - }); - - it(`should search for the deleted ticket and check the deletedTicket icon and it's date`, async() => { - await page.write(selectors.ticketsIndex.topbarSearch, '18'); - await page.waitToClick(selectors.globalItems.searchButton); - await page.waitForState('ticket.card.summary'); - await page.isVisible(selectors.ticketDescriptor.isDeletedIcon); - const result = await page.waitToGetProperty(selectors.ticketsIndex.searchResultDate, 'innerText'); - - expect(result).toContain(2000); - }); - }); - - describe('Restore ticket', () => { - it('should restore the ticket using the descriptor menu', async() => { - await page.waitToClick(selectors.ticketDescriptor.moreMenu); - await page.waitToClick(selectors.ticketDescriptor.moreMenuRestoreTicket); - await page.waitToClick(selectors.ticketDescriptor.acceptDialog); - await page.waitForState('ticket.card.summary'); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - }); - - describe('Make invoice', () => { - it('should login as administrative role then search for a ticket', async() => { - const invoiceableTicketId = '14'; - - await page.loginAndModule('administrative', 'ticket'); - await page.accessToSearchResult(invoiceableTicketId); - await page.waitForState('ticket.card.summary'); - }); - - it(`should make sure the ticket doesn't have an invoiceOutFk yet`, async() => { - const result = await page - .waitToGetProperty(selectors.ticketSummary.invoiceOutRef, 'innerText'); - - expect(result).toEqual('-'); - }); - - it('should invoice the ticket using the descriptor menu', async() => { - await page.waitToClick(selectors.ticketDescriptor.moreMenu); - await page.waitForContentLoaded(); - await page.waitToClick(selectors.ticketDescriptor.moreMenuMakeInvoice); - await page.waitToClick(selectors.ticketDescriptor.acceptInvoiceOutButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Ticket invoiced'); - }); - - it(`should make sure the ticket summary have an invoiceOutFk`, async() => { - await page.waitForTextInElement(selectors.ticketSummary.invoiceOutRef, 'T4444445'); - const result = await page.waitToGetProperty(selectors.ticketSummary.invoiceOutRef, 'innerText'); - - expect(result).toEqual('T4444445'); - }); - - it(`should regenerate the invoice using the descriptor menu`, async() => { - const expectedMessage = 'The invoice PDF document has been regenerated'; - - await page.waitToClick(selectors.ticketDescriptor.moreMenu); - await page.waitForContentLoaded(); - await page.waitToClick(selectors.ticketDescriptor.moreMenuRegenerateInvoice); - await page.respondToDialog('accept'); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain(expectedMessage); - }); - }); - - describe('SMS', () => { - it('should send the payment SMS using the descriptor menu', async() => { - await page.waitToClick(selectors.ticketDescriptor.moreMenu); - await page.waitToClick(selectors.ticketDescriptor.moreMenuSMSOptions); - await page.waitToClick(selectors.ticketDescriptor.moreMenuPaymentSMS); - await page.waitForSelector(selectors.ticketDescriptor.SMStext); - await page.waitPropertyLength(selectors.ticketDescriptor.SMStext, 'value', 128); - await page.waitToClick(selectors.ticketDescriptor.sendSMSbutton); - const message = await page.waitForSnackbar(); - - expect(message).toBeDefined(); - }); - - it('should send the import SMS using the descriptor menu', async() => { - await page.waitToClick(selectors.ticketDescriptor.moreMenuSMSOptions); - await page.waitToClick(selectors.ticketDescriptor.moreMenuSendImportSms); - await page.waitForSelector(selectors.ticketDescriptor.SMStext); - await page.waitPropertyLength(selectors.ticketDescriptor.SMStext, 'value', 144); - await page.waitToClick(selectors.ticketDescriptor.sendSMSbutton); - const message = await page.waitForSnackbar(); - - expect(message).toBeDefined(); - }); - }); -}); diff --git a/e2e/paths/05-ticket/13_services.spec.js b/e2e/paths/05-ticket/13_services.spec.js deleted file mode 100644 index 50df23582..000000000 --- a/e2e/paths/05-ticket/13_services.spec.js +++ /dev/null @@ -1,127 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Ticket services path', () => { - let browser; - let page; - const invoicedTicketId = '1'; - - afterAll(async() => { - await browser.close(); - }); - - describe('as employee', () => { - it('should log in as employee, search for an invoice and get to services', async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('employee', 'ticket'); - await page.accessToSearchResult(invoicedTicketId); - await page.accessToSection('ticket.card.service'); - }); - - it('should find the add descripton button disabled for this user role', async() => { - await page.waitForClassPresent(selectors.ticketService.firstAddServiceTypeButton, 'disabled'); - await page.waitToClick(selectors.ticketService.addServiceButton); - await page.waitForSelector(selectors.ticketService.firstAddServiceTypeButton); - const disabled = await page.isDisabled(selectors.ticketService.firstAddServiceTypeButton); - - expect(disabled).toBe(true); - }); - - it('should receive an error if you attempt to save a service without access rights', async() => { - await page.clearInput(selectors.ticketService.firstPrice); - await page.write(selectors.ticketService.firstPrice, '999'); - await page.waitToClick(selectors.ticketService.saveServiceButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain(`The current ticket can't be modified`); - }); - }); - - describe('as administrative', () => { - let editableTicketId = '16'; - it('should navigate to the services of a target ticket', async() => { - await page.loginAndModule('administrative', 'ticket'); - await page.accessToSearchResult(editableTicketId); - await page.accessToSection('ticket.card.service'); - }); - - it('should click on the add button to prepare the form to create a new service', async() => { - await page.waitToClick(selectors.ticketService.addServiceButton); - const result = await page - .isVisible(selectors.ticketService.firstServiceType); - - expect(result).toBeTruthy(); - }); - - it('should receive an error if you attempt to save it with empty fields', async() => { - await page.waitToClick(selectors.ticketService.saveServiceButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain(`can't be blank`); - }); - - it('should click on the add new service type to open the dialog', async() => { - await page.waitToClick(selectors.ticketService.firstAddServiceTypeButton); - await page.waitForSelector('.vn-dialog.shown'); - const result = await page.isVisible(selectors.ticketService.newServiceTypeName); - - expect(result).toBeTruthy(); - }); - - it('should receive an error if service type is empty on submit', async() => { - await page.waitToClick(selectors.ticketService.saveServiceTypeButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain(`Name can't be empty`); - }); - - it('should create a new service type then add price then create the service', async() => { - await page.write(selectors.ticketService.newServiceTypeName, 'Documentos'); - await page.waitToClick(selectors.ticketService.saveServiceTypeButton); - await page.write(selectors.ticketService.firstPrice, '999'); - await page.waitToClick(selectors.ticketService.saveServiceButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should confirm the service description was created correctly', async() => { - await page.reloadSection('ticket.card.service'); - const result = await page - .waitToGetProperty(selectors.ticketService.firstServiceType, 'value'); - - expect(result).toEqual('Documentos'); - }); - - it('should confirm the service quantity was created correctly', async() => { - const result = await page - .waitToGetProperty(selectors.ticketService.firstQuantity, 'value'); - - expect(result).toEqual('1'); - }); - - it('should confirm the service price was created correctly', async() => { - const result = await page - .waitToGetProperty(selectors.ticketService.firstPrice, 'value'); - - expect(result).toEqual('999'); - }); - - it('should delete the service', async() => { - await page.waitToClick(selectors.ticketService.fistDeleteServiceButton); - await page.waitForNumberOfElements(selectors.ticketService.serviceLine, 0); - await page.waitToClick(selectors.ticketService.saveServiceButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it(`should confirm the service was removed`, async() => { - await page.reloadSection('ticket.card.service'); - const nResults = await page.countElement(selectors.ticketService.serviceLine); - - expect(nResults).toEqual(0); - }); - }); -}); diff --git a/e2e/paths/05-ticket/14_create_ticket.spec.js b/e2e/paths/05-ticket/14_create_ticket.spec.js deleted file mode 100644 index 1f9c0c40a..000000000 --- a/e2e/paths/05-ticket/14_create_ticket.spec.js +++ /dev/null @@ -1,69 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Ticket create path', () => { - let browser; - let page; - let nextMonth = Date.vnNew(); - nextMonth.setMonth(nextMonth.getMonth() + 1); - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('salesPerson', 'ticket'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should open the new ticket form', async() => { - await page.waitToClick(selectors.ticketsIndex.newTicketButton); - await page.waitForState('ticket.create'); - }); - - it('should succeed to create a ticket', async() => { - await page.autocompleteSearch(selectors.createTicketView.client, 'Clark Kent'); - await page.pickDate(selectors.createTicketView.deliveryDate, nextMonth); - await page.autocompleteSearch(selectors.createTicketView.warehouse, 'Warehouse Two'); - await page.autocompleteSearch(selectors.createTicketView.agency, 'Gotham247'); - await page.waitToClick(selectors.createTicketView.createButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should check the url is now the summary of the ticket', async() => { - await page.waitForState('ticket.card.summary'); - }); - - it('should again open the new ticket form', async() => { - await page.waitToClick(selectors.globalItems.returnToModuleIndexButton); - await page.waitToClick(selectors.ticketsIndex.newTicketButton); - await page.waitForState('ticket.create'); - }); - - it('should succeed to create another ticket for the same client', async() => { - await page.autocompleteSearch(selectors.createTicketView.client, 'Clark Kent'); - await page.pickDate(selectors.createTicketView.deliveryDate, nextMonth); - await page.autocompleteSearch(selectors.createTicketView.warehouse, 'Warehouse One'); - await page.autocompleteSearch(selectors.createTicketView.agency, 'Gotham247'); - await page.waitToClick(selectors.createTicketView.createButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should check the url is now the summary of the created ticket', async() => { - await page.waitForState('ticket.card.summary'); - }); - - it('should delete the current ticket', async() => { - await page.waitToClick(selectors.ticketDescriptor.moreMenu); - await page.waitToClick(selectors.ticketDescriptor.moreMenuDeleteTicket); - await page.waitToClick(selectors.ticketDescriptor.acceptDialog); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Ticket deleted. You can undo this action within the first hour'); - }); -}); diff --git a/e2e/paths/05-ticket/15_create_ticket_from_client.spec.js b/e2e/paths/05-ticket/15_create_ticket_from_client.spec.js deleted file mode 100644 index 51ead6461..000000000 --- a/e2e/paths/05-ticket/15_create_ticket_from_client.spec.js +++ /dev/null @@ -1,37 +0,0 @@ -import getBrowser from '../../helpers/puppeteer'; - -const $ = { - form: 'vn-ticket-create-card', - moreMenu: 'vn-client-descriptor vn-icon-button[icon=more_vert]', - simpleTicketButton: '.vn-menu [name="simpleTicket"]' -}; - -describe('Ticket create from client path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('employee', 'client'); - await page.accessToSearchResult('Petter Parker'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should create simple ticket and check if the client details are the expected ones', async() => { - await page.waitToClick($.moreMenu); - await page.waitToClick($.simpleTicketButton); - await page.waitForState('ticket.create'); - - const values = { - client: 'Petter Parker', - address: 'Petter Parker' - }; - const formValues = await page.fetchForm($.form, Object.keys(values)); - - expect(formValues).toEqual(values); - }); -}); diff --git a/e2e/paths/05-ticket/16_summary.spec.js b/e2e/paths/05-ticket/16_summary.spec.js deleted file mode 100644 index a6017e454..000000000 --- a/e2e/paths/05-ticket/16_summary.spec.js +++ /dev/null @@ -1,108 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Ticket Summary path', () => { - let browser; - let page; - const ticketId = '20'; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should navigate to the target ticket summary section', async() => { - await page.loginAndModule('employee', 'ticket'); - await page.accessToSearchResult(ticketId); - await page.waitForState('ticket.card.summary'); - }); - - it(`should display details from the ticket and it's client on the top of the header`, async() => { - await page.waitForTextInElement(selectors.ticketSummary.header, 'Bruce Banner'); - const result = await page.waitToGetProperty(selectors.ticketSummary.header, 'innerText'); - - expect(result).toContain(`Ticket #${ticketId}`); - expect(result).toContain('Bruce Banner (1109)'); - expect(result).toContain('Somewhere in Thailand'); - }); - - it('should display ticket details', async() => { - let result = await page - .waitToGetProperty(selectors.ticketSummary.state, 'innerText'); - - expect(result).toContain('Arreglar'); - }); - - it('should display delivery details', async() => { - let result = await page - .waitToGetProperty(selectors.ticketSummary.route, 'innerText'); - - expect(result).toContain('3'); - }); - - it('should display the ticket total', async() => { - let result = await page - .waitToGetProperty(selectors.ticketSummary.total, 'innerText'); - - expect(result).toContain('€155.54'); - }); - - it('should display the ticket line(s)', async() => { - let result = await page - .waitToGetProperty(selectors.ticketSummary.firstSaleItemId, 'innerText'); - - expect(result).toContain('2'); - }); - - it(`should click on the first sale ID to make the item descriptor visible`, async() => { - await page.waitToClick(selectors.ticketSummary.firstSaleItemId); - await page.waitImgLoad(selectors.ticketSummary.firstSaleDescriptorImage); - const visible = await page.isVisible(selectors.ticketSummary.itemDescriptorPopover); - - expect(visible).toBeTruthy(); - }); - - it(`should check the url for the item diary link of the descriptor is for the right item id`, async() => { - await page.waitForSelector(selectors.ticketSummary.itemDescriptorPopoverItemDiaryButton, {visible: true}); - }); - - it('should log in as production then navigate to the summary of the same ticket', async() => { - await page.loginAndModule('production', 'ticket'); - await page.accessToSearchResult(ticketId); - await page.waitForState('ticket.card.summary'); - }); - - it('should set the ticket state to OK using the top right button', async() => { - const searchValue = 'OK'; - await page.waitToClick(selectors.ticketSummary.stateButton); - await page.write(selectors.ticketSummary.stateAutocomplete, searchValue); - try { - await page.waitForFunction(text => { - const element = document.querySelector('li.active'); - if (element) - return element.innerText.toLowerCase().includes(text.toLowerCase()); - }, {}, searchValue); - } catch (error) { - const state = await page.evaluate(() => { - const stateSelector = 'vn-ticket-summary vn-label-value:nth-child(1) > section > span'; - return document.querySelector(stateSelector).value; - }); - throw new Error(`${stateSelector} innerText is ${state}! ${error}`); - } - await page.keyboard.press('Enter'); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should confirm the ticket state was updated', async() => { - await page.waitForSpinnerLoad(); - const result = await page.waitToGetProperty(selectors.ticketSummary.state, 'innerText'); - - expect(result).toContain('OK'); - }); -}); diff --git a/e2e/paths/05-ticket/17_log.spec.js b/e2e/paths/05-ticket/17_log.spec.js deleted file mode 100644 index e1da2df44..000000000 --- a/e2e/paths/05-ticket/17_log.spec.js +++ /dev/null @@ -1,34 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Ticket log path', () => { - let browser; - let page; - const ticketId = '5'; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should navigate to the target ticket notes section', async() => { - await page.loginAndModule('employee', 'ticket'); - await page.accessToSearchResult(ticketId); - await page.accessToSection('ticket.card.observation'); - await page.waitForState('ticket.card.observation'); - }); - - it('should create a new note for the test', async() => { - await page.waitToClick(selectors.ticketNotes.addNoteButton); - await page.autocompleteSearch(selectors.ticketNotes.firstNoteType, 'ItemPicker'); - await page.write(selectors.ticketNotes.firstDescription, 'description'); - await page.waitToClick(selectors.ticketNotes.submitNotesButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); -}); diff --git a/e2e/paths/05-ticket/18_index_payout.spec.js b/e2e/paths/05-ticket/18_index_payout.spec.js deleted file mode 100644 index 9c5518424..000000000 --- a/e2e/paths/05-ticket/18_index_payout.spec.js +++ /dev/null @@ -1,70 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; -const $ = { - newPayment: '.vn-dialog.shown', - anyBalanceLine: 'vn-client-balance-index vn-tbody > vn-tr', - firstLineReference: 'vn-client-balance-index vn-tbody > vn-tr:nth-child(1) > vn-td-editable' -}; - -describe('Ticket index payout path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('administrative', 'ticket'); - await page.waitForState('ticket.index'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should check the second ticket from a client and 1 of another', async() => { - await page.waitToClick(selectors.globalItems.searchButton); - await page.waitToClick(selectors.ticketsIndex.thirdTicketCheckbox); - await page.waitToClick(selectors.ticketsIndex.fifthTicketCheckbox); - await page.waitToClick(selectors.ticketsIndex.payoutButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('You cannot make a payment on account from multiple clients'); - }); - - 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, '1101'); - await page.keyboard.press('Enter'); - await page.waitForNumberOfElements(selectors.ticketsIndex.anySearchResult, 10); - await page.waitToClick(selectors.ticketsIndex.firstTicketCheckbox); - await page.waitToClick(selectors.ticketsIndex.secondTicketCheckbox); - - await page.waitToClick(selectors.ticketsIndex.payoutButton); - - await page.waitForSelector(selectors.ticketsIndex.payoutCompany); - }); - - it('should fill the company and bank to perform a payout and check a new balance line was entered', async() => { - await page.fillForm($.newPayment, { - company: 'VNL', - bank: 'cash', - amountPaid: 100, - description: 'Payment', - viewReceipt: false - }); - await page.respondToDialog('accept'); - const message = await page.waitForSnackbar(); - - await page.waitToClick(selectors.globalItems.homeButton); - await page.selectModule('client'); - await page.accessToSearchResult('1101'); - await page.accessToSection('client.card.balance.index'); - await page.waitForSelector($.anyBalanceLine); - const count = await page.countElement($.anyBalanceLine); - const reference = await page.innerText($.firstLineReference); - - expect(message.isSuccess).toBeTrue(); - expect(count).toEqual(4); - expect(reference).toContain('Payment'); - }); -}); diff --git a/e2e/paths/05-ticket/19_dms.spec.js b/e2e/paths/05-ticket/19_dms.spec.js deleted file mode 100644 index be2ac4338..000000000 --- a/e2e/paths/05-ticket/19_dms.spec.js +++ /dev/null @@ -1,49 +0,0 @@ -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/05-ticket/20_moveExpedition.spec.js b/e2e/paths/05-ticket/20_moveExpedition.spec.js deleted file mode 100644 index ae23c9c99..000000000 --- a/e2e/paths/05-ticket/20_moveExpedition.spec.js +++ /dev/null @@ -1,50 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Ticket expeditions', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('production', 'ticket'); - await page.accessToSearchResult('1'); - await page.accessToSection('ticket.card.expedition'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it(`should move one expedition to new ticket withoute route`, async() => { - await page.waitToClick(selectors.ticketExpedition.thirdSaleCheckbox); - await page.waitToClick(selectors.ticketExpedition.moveExpeditionButton); - await page.waitToClick(selectors.ticketExpedition.moreMenuWithoutRoute); - await page.waitToClick(selectors.ticketExpedition.saveButton); - await page.waitForState('ticket.card.summary'); - await page.accessToSection('ticket.card.expedition'); - - await page.waitForSelector(selectors.ticketExpedition.expeditionRow, {}); - const result = await page - .countElement(selectors.ticketExpedition.expeditionRow); - - expect(result).toEqual(2); - }); - - it(`should move one expedition to new ticket with route`, async() => { - await page.waitToClick(selectors.ticketExpedition.firstSaleCheckbox); - await page.waitToClick(selectors.ticketExpedition.moveExpeditionButton); - await page.waitToClick(selectors.ticketExpedition.moreMenuWithRoute); - await page.write(selectors.ticketExpedition.newRouteId, '1'); - await page.waitToClick(selectors.ticketExpedition.saveButton); - await page.waitForState('ticket.card.summary'); - await page.accessToSection('ticket.card.expedition'); - - await page.waitForSelector(selectors.ticketExpedition.expeditionRow, {}); - const result = await page - .countElement(selectors.ticketExpedition.expeditionRow); - - expect(result).toEqual(2); - }); -}); diff --git a/e2e/paths/05-ticket/21_future.spec.js b/e2e/paths/05-ticket/21_future.spec.js deleted file mode 100644 index 60bb9c38d..000000000 --- a/e2e/paths/05-ticket/21_future.spec.js +++ /dev/null @@ -1,99 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Ticket Future path', () => { - let browser; - let page; - let httpRequest; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('employee', 'ticket'); - await page.accessToSection('ticket.future'); - page.on('request', req => { - if (req.url().includes(`Tickets/getTicketsFuture`)) - httpRequest = req.url(); - }); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should search with required data, check three last tickets and move to the future', async() => { - await page.waitToClick(selectors.ticketFuture.openAdvancedSearchButton); - await page.clearInput(selectors.ticketFuture.warehouseFk); - await page.waitToClick(selectors.ticketFuture.submit); - let message = await page.waitForSnackbar(); - - expect(message.text).toContain('warehouseFk is a required argument'); - - await page.waitToClick(selectors.ticketFuture.openAdvancedSearchButton); - await page.clearInput(selectors.ticketFuture.futureScopeDays); - await page.waitToClick(selectors.ticketFuture.submit); - message = await page.waitForSnackbar(); - - expect(message.text).toContain('futureScopeDays is a required argument'); - - await page.waitToClick(selectors.ticketFuture.openAdvancedSearchButton); - await page.clearInput(selectors.ticketFuture.originScopeDays); - await page.waitToClick(selectors.ticketFuture.submit); - message = await page.waitForSnackbar(); - - expect(message.text).toContain('originScopeDays is a required argument'); - - await page.waitToClick(selectors.ticketFuture.openAdvancedSearchButton); - await page.waitToClick(selectors.ticketFuture.submit); - - expect(httpRequest).toBeDefined(); - - await page.waitToClick(selectors.ticketFuture.openAdvancedSearchButton); - - await page.autocompleteSearch(selectors.ticketFuture.ipt, 'H'); - await page.waitToClick(selectors.ticketFuture.submit); - - expect(httpRequest).toContain('ipt=H'); - - await page.waitToClick(selectors.ticketFuture.openAdvancedSearchButton); - - await page.clearInput(selectors.ticketFuture.ipt); - - await page.autocompleteSearch(selectors.ticketFuture.futureIpt, 'H'); - await page.waitToClick(selectors.ticketFuture.submit); - - expect(httpRequest).toContain('futureIpt=H'); - - await page.waitToClick(selectors.ticketFuture.openAdvancedSearchButton); - - await page.clearInput(selectors.ticketFuture.futureIpt); - - await page.autocompleteSearch(selectors.ticketFuture.state, 'Free'); - await page.waitToClick(selectors.ticketFuture.submit); - - expect(httpRequest).toContain('state=0'); - - await page.waitToClick(selectors.ticketFuture.openAdvancedSearchButton); - - await page.clearInput(selectors.ticketFuture.state); - - await page.autocompleteSearch(selectors.ticketFuture.futureState, 'Free'); - await page.waitToClick(selectors.ticketFuture.submit); - - expect(httpRequest).toContain('futureState=0'); - - await page.waitToClick(selectors.ticketFuture.openAdvancedSearchButton); - await page.clearInput(selectors.ticketFuture.state); - await page.clearInput(selectors.ticketFuture.futureState); - await page.waitToClick(selectors.ticketFuture.submit); - - await page.waitForNumberOfElements(selectors.ticketFuture.searchResult, 5); - await page.waitToClick(selectors.ticketFuture.multiCheck); - await page.waitToClick(selectors.ticketFuture.firstCheck); - await page.waitToClick(selectors.ticketFuture.moveButton); - await page.waitToClick(selectors.globalItems.acceptButton); - message = await page.waitForSnackbar(); - - expect(message.text).toContain('Tickets moved successfully!'); - }); -}); diff --git a/e2e/paths/05-ticket/22_advance.spec.js b/e2e/paths/05-ticket/22_advance.spec.js deleted file mode 100644 index 0e5b5e0c3..000000000 --- a/e2e/paths/05-ticket/22_advance.spec.js +++ /dev/null @@ -1,79 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Ticket Advance path', () => { - let browser; - let page; - let httpRequest; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('employee', 'ticket'); - await page.accessToSection('ticket.advance'); - page.on('request', req => { - if (req.url().includes(`Tickets/getTicketsAdvance`)) - httpRequest = req.url(); - }); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should search with the required data, check the first ticket and move to the present', async() => { - await page.waitToClick(selectors.ticketAdvance.openAdvancedSearchButton); - await page.clearInput(selectors.ticketAdvance.warehouseFk); - - await page.waitToClick(selectors.ticketAdvance.submit); - let message = await page.waitForSnackbar(); - - expect(message.text).toContain('warehouseFk is a required argument'); - - await page.waitToClick(selectors.ticketAdvance.openAdvancedSearchButton); - await page.clearInput(selectors.ticketAdvance.dateToAdvance); - await page.waitToClick(selectors.ticketAdvance.submit); - message = await page.waitForSnackbar(); - - expect(message.text).toContain('dateToAdvance is a required argument'); - - await page.waitToClick(selectors.ticketAdvance.openAdvancedSearchButton); - await page.clearInput(selectors.ticketAdvance.dateFuture); - await page.waitToClick(selectors.ticketAdvance.submit); - message = await page.waitForSnackbar(); - - expect(message.text).toContain('dateFuture is a required argument'); - - await page.waitToClick(selectors.ticketAdvance.openAdvancedSearchButton); - await page.waitToClick(selectors.ticketAdvance.submit); - - expect(httpRequest).toBeDefined(); - - await page.waitToClick(selectors.ticketAdvance.openAdvancedSearchButton); - await page.autocompleteSearch(selectors.ticketAdvance.futureIpt, 'H'); - await page.waitToClick(selectors.ticketAdvance.submit); - - expect(httpRequest).toContain('futureIpt=H'); - - await page.waitToClick(selectors.ticketAdvance.openAdvancedSearchButton); - await page.clearInput(selectors.ticketAdvance.futureIpt); - await page.waitToClick(selectors.ticketAdvance.submit); - - await page.waitToClick(selectors.ticketAdvance.openAdvancedSearchButton); - await page.autocompleteSearch(selectors.ticketAdvance.ipt, 'H'); - await page.waitToClick(selectors.ticketAdvance.submit); - - expect(httpRequest).toContain('ipt=H'); - - await page.waitToClick(selectors.ticketAdvance.openAdvancedSearchButton); - await page.clearInput(selectors.ticketAdvance.ipt); - await page.waitToClick(selectors.ticketAdvance.submit); - - await page.waitToClick(selectors.ticketAdvance.firstCheck); - await page.waitToClick(selectors.ticketAdvance.moveButton); - await page.waitToClick(selectors.ticketAdvance.acceptButton); - message = await page.waitForSnackbar(); - - expect(message.text).toContain('Tickets moved successfully!'); - }); -}); diff --git a/front/core/services/app.js b/front/core/services/app.js index dba6e70bf..816167835 100644 --- a/front/core/services/app.js +++ b/front/core/services/app.js @@ -70,10 +70,18 @@ export default class App { if (this.logger.$params.q) { let tableValue = this.logger.$params.q; - const q = JSON.parse(tableValue); - if (typeof q === 'number') - tableValue = JSON.stringify({id: tableValue}); - newRoute = newRoute.concat(`?table=${tableValue}`); + if (Array.isArray(tableValue)) { + const [key, param1, param2] = tableValue; + const payload = key === 'createForm' + ? {[param1]: param2} + : {[key]: param1}; + newRoute += `?${key}=${JSON.stringify(payload)}`; + } else { + const q = JSON.parse(tableValue); + if (typeof q === 'number') + tableValue = JSON.stringify({id: tableValue}); + newRoute = newRoute.concat(`?table=${tableValue}`); + } } else if (!hasId && this.logger.$params.id && newRoute.indexOf(this.logger.$params.id) < 0) newRoute = newRoute.concat(`${this.logger.$params.id}`); diff --git a/loopback/common/methods/vn-model/printService.js b/loopback/common/methods/vn-model/printService.js index 12a6a67cc..ed784229b 100644 --- a/loopback/common/methods/vn-model/printService.js +++ b/loopback/common/methods/vn-model/printService.js @@ -2,7 +2,7 @@ const {Report, Email} = require('vn-print'); module.exports = Self => { Self.printReport = async function(ctx, id, reportName) { - const args = Object.assign({}, ctx.args); + const args = Object.assign({id}, ctx.args); const params = {lang: ctx.req.getLocale()}; delete args.ctx; diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 4ad3f76e2..24f5b3eec 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -223,7 +223,6 @@ "Shelving not valid": "Shelving not valid", "printerNotExists": "The printer does not exist", "There are not picking tickets": "There are not picking tickets", - "ticketCommercial": "The ticket {{ ticket }} for the salesperson {{ salesMan }} is in preparation. (automatically generated message)", "This password can only be changed by the user themselves": "This password can only be changed by the user themselves", "They're not your subordinate": "They're not your subordinate", "InvoiceIn is already booked": "InvoiceIn is already booked", @@ -242,8 +241,10 @@ "The maximum height of the wagon is 200cm": "The maximum height of the wagon is 200cm", "The quantity claimed cannot be greater than the quantity of the line": "The quantity claimed cannot be greater than the quantity of the line", "There are tickets for this area, delete them first": "There are tickets for this area, delete them first", - "ticketLostExpedition": "The ticket [{{ticketId}}]({{{ticketUrl}}}) has the following lost expedition:{{ expeditionId }}", - "null": "null", + "Payment method is required": "Payment method is required", + "You do not have permission to modify the booked field": "You do not have permission to modify the booked field", "Invalid or expired verification code": "Invalid or expired verification code", - "Payment method is required": "Payment method is required" -} \ No newline at end of file + "ticketLostExpedition": "The ticket [{{ticketId}}]({{{ticketUrl}}}) has the following lost expedition:{{ expeditionId }}", + "The raid information is not correct": "The raid information is not correct", + "Sales already moved": "Sales already moved" +} diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 37976c0ea..0b10d4702 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -359,7 +359,6 @@ "This workCenter is already assigned to this agency": "Este centro de trabajo ya está asignado a esta agencia", "Select ticket or client": "Elija un ticket o un client", "It was not able to create the invoice": "No se pudo crear la factura", - "ticketCommercial": "El ticket {{ ticket }} para el vendedor {{ salesMan }} está en preparación. (mensaje generado automáticamente)", "Incoterms and Customs agent are required for a non UEE member": "Se requieren Incoterms y agente de aduanas para un no miembro de la UEE", "You can not use the same password": "No puedes usar la misma contraseña", "This PDA is already assigned to another user": "Este PDA ya está asignado a otro usuario", @@ -386,6 +385,10 @@ "type cannot be blank": "Se debe rellenar el tipo", "There are tickets for this area, delete them first": "Hay tickets para esta sección, borralos primero", "There is no company associated with that warehouse": "No hay ninguna empresa asociada a ese almacén", + "You do not have permission to modify the booked field": "No tienes permisos para modificar el campo contabilizada", "ticketLostExpedition": "El ticket [{{ticketId}}]({{{ticketUrl}}}) tiene la siguiente expedición perdida:{{ expeditionId }}", - "The web user's email already exists": "El correo del usuario web ya existe" -} \ No newline at end of file + "The web user's email already exists": "El correo del usuario web ya existe", + "Sales already moved": "Ya han sido transferidas", + "The raid information is not correct": "La información de la redada no es correcta" +} + diff --git a/loopback/locale/fr.json b/loopback/locale/fr.json index 0e876f89c..9941358be 100644 --- a/loopback/locale/fr.json +++ b/loopback/locale/fr.json @@ -362,8 +362,9 @@ "The invoices have been created but the PDFs could not be generated": "La facture a été émise mais le PDF n'a pas pu être généré", "It has been invoiced but the PDF of refund not be generated": "Il a été facturé mais le PDF de remboursement n'a pas été généré", "Cannot send mail": "Impossible d'envoyer le mail", - "Original invoice not found": "Facture originale introuvable", - "The quantity claimed cannot be greater than the quantity of the line": "Le montant réclamé ne peut pas être supérieur au montant de la ligne", + "Original invoice not found": "Facture originale introuvable", + "The quantity claimed cannot be greater than the quantity of the line": "Le montant réclamé ne peut pas être supérieur au montant de la ligne", + "You do not have permission to modify the booked field": "Vous n'avez pas la permission de modifier le champ comptabilisé", "ticketLostExpedition": "Le ticket [{{ticketId}}]({{{ticketUrl}}}) a l'expédition perdue suivante : {{expeditionId}}", "The web user's email already exists": "L'email de l'internaute existe déjà" -} \ No newline at end of file +} diff --git a/loopback/locale/pt.json b/loopback/locale/pt.json index e08336273..e84b30f3d 100644 --- a/loopback/locale/pt.json +++ b/loopback/locale/pt.json @@ -366,4 +366,4 @@ "The quantity claimed cannot be greater than the quantity of the line": "O valor reclamado não pode ser superior ao valor da linha", "ticketLostExpedition": "O ticket [{{ticketId}}]({{{ticketUrl}}}) tem a seguinte expedição perdida: {{expeditionId}}", "The web user's email already exists": "O e-mail do utilizador da web já existe." -} \ No newline at end of file +} diff --git a/modules/account/back/locale/vn-user/en.yml b/modules/account/back/locale/vn-user/en.yml index 51de7c40d..f911ee1eb 100644 --- a/modules/account/back/locale/vn-user/en.yml +++ b/modules/account/back/locale/vn-user/en.yml @@ -15,7 +15,5 @@ columns: image: image hasGrant: has grant userFk: user - recoverPass: recover password role: role - sync: pending sync lastPassChange: password changed diff --git a/modules/account/back/locale/vn-user/es.yml b/modules/account/back/locale/vn-user/es.yml index 85e8bc0dc..c05dd872c 100644 --- a/modules/account/back/locale/vn-user/es.yml +++ b/modules/account/back/locale/vn-user/es.yml @@ -15,7 +15,5 @@ columns: image: imagen hasGrant: puede delegar userFk: usuario - recoverPass: recuperar contraseña role: rol - sync: Pendiente de sincronizar lastPassChange: contraseña modificada diff --git a/modules/client/back/methods/client/filter.js b/modules/client/back/methods/client/filter.js index f805c4be9..7df973f19 100644 --- a/modules/client/back/methods/client/filter.js +++ b/modules/client/back/methods/client/filter.js @@ -1,4 +1,3 @@ - const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; const buildFilter = require('vn-loopback/util/filter').buildFilter; const mergeFilters = require('vn-loopback/util/filter').mergeFilters; diff --git a/modules/client/back/methods/client/summary.js b/modules/client/back/methods/client/summary.js index 8162096f0..9242fbd44 100644 --- a/modules/client/back/methods/client/summary.js +++ b/modules/client/back/methods/client/summary.js @@ -54,7 +54,10 @@ module.exports = Self => { { relation: 'country', scope: { - fields: ['name'] + fields: ['id', 'name'], + include: { + relation: 'saySimpleCountry', + } } }, { diff --git a/modules/client/back/models/client-observation.json b/modules/client/back/models/client-observation.json index 86351862d..1d906420a 100644 --- a/modules/client/back/models/client-observation.json +++ b/modules/client/back/models/client-observation.json @@ -55,7 +55,7 @@ "relation": "user", "scope": { "fields": [ - "nickname" + "name" ] } } diff --git a/modules/client/front/descriptor/index.html b/modules/client/front/descriptor/index.html index f2dbd64b6..cecd7ee62 100644 --- a/modules/client/front/descriptor/index.html +++ b/modules/client/front/descriptor/index.html @@ -99,7 +99,7 @@
- |
- - Item ID - | -- Description - | -- Grouping price - | -- Packing price - | -- Min price - | -- Started - | -- Ended - | -- Warehouse - | -- |
---|---|---|---|---|---|---|---|---|---|
- |
-
- {{id}}
-
- |
-
-
-
- {{itemFk.selection.name}}
-
-
- {{price.subName}}- |
-
- |
-
- |
-
- |
-
- |
-
- |
-
- |
-
- |
-
- | - Identifier - | -- Grouping - | -- Packing - | -- Description - | -- Stems - | -- Size - | -- Type - | -- Category - | -- Intrastat - | -- Origin - | -- Buyer - | -- Weight/Piece - | -- Multiplier - | -- Active - | -- Producer - | -- Landed - | -- |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
- - | -- - {{::item.id}} - - | -{{::item.grouping | dashIfEmpty}} | -{{::item.packing | dashIfEmpty}} | -
-
-
- {{::item.subName}}- |
- {{::item.stems}} | -{{::item.size}} | -- {{::item.typeName}} - | -- {{::item.category}} - | -- {{::item.intrastat}} - | -{{::item.origin}} | -- - {{::item.userName}} - - | -{{::item.weightByPiece}} | -{{::item.stemMultiplier}} | -
- |
- {{::item.producer | dashIfEmpty}} | -{{::item.landed | date:'dd/MM/yyyy'}} | -
- |
-
- |
- - Created - | -- Item - | -- Concept - | -- Parking - | -- Shelving - | -- Etiqueta - | -- Packing - | -
---|---|---|---|---|---|---|---|
- |
- {{::itemShelvingPlacementSupplyStock.created | date: 'dd/MM/yyyy'}} | -- {{::itemShelvingPlacementSupplyStock.itemFk}} - | -- - {{itemShelvingPlacementSupplyStock.longName}} - - | -- {{::itemShelvingPlacementSupplyStock.parking}} - | -- {{::itemShelvingPlacementSupplyStock.shelving}} - | -- {{(itemShelvingPlacementSupplyStock.stock / itemShelvingPlacementSupplyStock.packing).toFixed(2)}} - | -- {{::itemShelvingPlacementSupplyStock.packing}} - | -
Visible
-{{$ctrl.summary.visible}}
-Available
-{{$ctrl.summary.available}}
-
-
- {{$ctrl.summary.item.description}} -
-- {{barcode.code}} -
-{{$t('code')}} | {{$t('boxes')}} | -+ | {{$t('packing')}} | -{{$t('concept')}} | -{{$t('reference')}} | -{{$t('tags')}} | -{{$t('quantity')}} | -- | {{$t('price')}} | -- | {{$t('amount')}} | +{{$t('concept')}} | +{{$t('reference')}} | +{{$t('tags')}} | +{{$t('quantity')}} | ++ | {{$t('price')}} | ++ | {{$t('amount')}} | ||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
{{buy.itemFk}} | {{buy.stickers}} | -x | -{{buy.packing}} | -{{buy.name}} | -{{buy.comment}} | -- {{buy.tag5}} → {{buy.value5}} - {{buy.tag6}} → {{buy.value6}} - {{buy.tag7}} → {{buy.value7}} + | x | +{{buy.packing}} | +{{buy.name}} | +referencia de prueba | +
+
+
+ {{buy.tag5}}→ {{buy.value5}}
+ {{buy.tag6}}→ {{buy.value6}}
+
+
{{buy.tag7}}→ {{buy.value7}}
+ {{buy.tag8}}→ {{buy.value8}}
+ |
- {{buy.quantity | number($i18n.locale)}} | -x | -{{buy.buyingValue | currency('EUR', $i18n.locale)}} | -= | -+ | {{buy.quantity | number($i18n.locale)}} | +x | +{{buy.buyingValue | currency('EUR', $i18n.locale)}} | += | +{{buy.buyingValue * buy.quantity | currency('EUR', $i18n.locale)}} |
{{getTotalBy('stickers')}} | diff --git a/print/templates/reports/entry-order/locale/es.yml b/print/templates/reports/entry-order/locale/es.yml index 5a6716ba1..9ec357802 100644 --- a/print/templates/reports/entry-order/locale/es.yml +++ b/print/templates/reports/entry-order/locale/es.yml @@ -16,4 +16,5 @@ entry: Entrada {0} supplierData: Datos del proveedor notes: Notas reference: Referencia -tags: Tags \ No newline at end of file +tags: Etiquetas +code: Código \ No newline at end of file diff --git a/print/templates/reports/entry-order/sql/buys.sql b/print/templates/reports/entry-order/sql/buys.sql index 92c055483..545849908 100644 --- a/print/templates/reports/entry-order/sql/buys.sql +++ b/print/templates/reports/entry-order/sql/buys.sql @@ -10,7 +10,9 @@ SELECT b.itemFk, i.tag6, i.value6, i.tag7, - i.value7 + i.value7, + i.tag8, + i.value8 FROM buy b JOIN item i ON i.id = b.itemFk LEFT JOIN item i2 ON i2.id = b.itemOriginalFk |